title: Deleting duplicate records using a temporary table
body: <p>Take the tsql query below:</p>
  
  <pre><code>DECLARE @table TABLE(data VARCHAR(20))
  INSERT INTO @table VALUES ('not duplicate row')
  INSERT INTO @table VALUES ('duplicate row')    
  INSERT INTO @table VALUES ('duplicate row')    
  INSERT INTO @table VALUES ('second duplicate row')    
  INSERT INTO @table VALUES ('second duplicate row')
  
  SELECT   data    
  INTO     #duplicates    
  FROM     @table    
  GROUP BY data    
  HAVING   COUNT(*) &gt; 1    
  
  -- delete all rows that are duplicated   
  DELETE   FROM @table    
  FROM     @table o INNER JOIN #duplicates d
           ON d.data = o.data         
  
  -- insert one row for every duplicate set    
  INSERT   INTO @table(data)    
           SELECT   data    
           FROM     #duplicates
  </code></pre>
  
  <p>I understand what it is doing, but the last part of logic (after --insert one row for every duplicate set), doesn't make sense. Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section?</p>
  
  <p>This query was found <a href="http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/" rel="nofollow noreferrer">here</a></p>
  
  <p>Thanks</p>