1

This is the table I want to delete duplicate

So I want to DELETE the duplicate rows not just FIND IT My current code can only let me know which ROWS have to be deleted. But I am confusing how to "DELETE" them from my target table. Any suggestion?

WITH tmp AS ( SELECT Code ,ROW_NUMBER() OVER(PARTITION BY Code ORDER BY Code) AS ROWNUMBER FROM CouponCode ) SELECT * FROM tmp WHERE ROWNUMBER > 1 
2
  • You could simply select into a temp table, clear out the existing table and insert into the now cleaned table all results from the temp table. Commented Jul 25, 2018 at 21:15
  • @JakoBasson yes you are correct. What I am thinking is if we have a millions of data rows in the table, it could be slow if we copy data to a new table and rebuild later. Commented Jul 25, 2018 at 21:41

2 Answers 2

3

You just change your select to a delete, basically:

WITH tmp AS ( SELECT Code, ROW_NUMBER() OVER(PARTITION BY Code ORDER BY Code) AS ROWNUMBER FROM CouponCode ) DELETE tmp WHERE ROWNUMBER > 1; 
Sign up to request clarification or add additional context in comments.

2 Comments

Wow..I didn't know that CTE can let me modify original table directly. Can I say CTE is the same as VIEW in this point, since we can also modify original table by modifying view
@Aiden . . . Yes. Both CTEs and Views have the same rules for being updatable (well, you can define a trigger on a view as well, but that is another matter).
3

Step 1:

Select distinct rows into temporary table:

SELECT DISTINCT Code, ExpiredDate INTO temp_CouponCode FROM CouponCode 

Step 2:

Empty original table:

truncate table CouponCode 

Step 3:

Copy data from temporary table:

INSERT INTO CouponCode SELECT Code, ExpiredDate FROM temp_CouponCode 

Step 4:

Remove temporary table:

DROP TABLE temp_CouponCode 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.