0

I have tried,

delete from Student where FirstName in ( select FirstName from ( select FirstName, row_number() over(partition by FirstName order by FirstName) as rn from Student ) Student WHERE rn > 1 ); 

but its deleting both duplicate records. please correct my query. thanks in advance.

8
  • Tag the dbms you're using! Commented Aug 21, 2017 at 9:36
  • have table primary key? Commented Aug 21, 2017 at 9:38
  • MS SQL SERVER........ Commented Aug 21, 2017 at 9:38
  • No primary key and any id column. all columns are varchar type. Commented Aug 21, 2017 at 9:39
  • 1
    stackoverflow.com/questions/985384/… Commented Aug 21, 2017 at 9:43

2 Answers 2

2

You can use CTE

 WITH MyCTE AS ( SELECT [FirstName], ROW_NUMBER() OVER(PARTITION BY FirstName ORDER BY FirstName) RN FROM Student ) DELETE FROM MyCTE WHERE RN > 1; SELECT * FROM Students; 
Sign up to request clarification or add additional context in comments.

1 Comment

I think you need ";" before WITH
0

You're deleting based on FirstName hence it's deleting all the records from your table, try like this will do.

Live Demo

WITH StudentCte As ( SELECT FirstName, ROW_NUMBER() OVER(Partition by FirstName ORDER BY (SELECT NULL)) as RowNum FROM Student ) DELETE FROM StudentCte WHERE RowNum > 1; SELECT * From Student; 

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.