How can I remove duplicate rows in SQL Server?
This article will use a table variable for reference with sample data.
Query:
DECLARE @Employee TABLE(Id INT IDENTITY(1,1), [EmployeeName] VARCHAR(100))
INSERT INTO @Employee ([EmployeeName])
SELECT 'Vikram' AS [EmployeeName]
UNION ALL
SELECT 'Vijay' AS [EmployeeName]
UNION ALL
SELECT 'Vinod' AS [EmployeeName]
UNION ALL
SELECT 'Vijay' AS [EmployeeName]
Query to get duplicate records:
SELECT T1.Id
, T1.EmployeeName
FROM @Employee T1
OUTER APPLY (
SELECT T.Id
, T.EmployeeName,
ROW_NUMBER() OVER (PARTITION BY T.EmployeeName ORDER BY T.EmployeeName ASC) AS Sno
FROM @Employee T
) AS T2
WHERE T1.Id = T2.Id AND T2.Sno > 1
Query to get unique records:
SELECT T1.Id
, T1.EmployeeName
FROM @Employee T1
OUTER APPLY (
SELECT T.Id
, T.EmployeeName,
ROW_NUMBER() OVER (PARTITION BY T.EmployeeName ORDER BY T.EmployeeName ASC) AS Sno
FROM @Employee T
) AS T2
WHERE T1.Id = T2.Id AND T2.Sno = 1
Query to delete the duplicate records from the table:
DELETE T1
FROM @Employee T1
OUTER APPLY (
SELECT T.Id
, T.EmployeeName,
ROW_NUMBER() OVER (PARTITION BY T.EmployeeName ORDER BY T.EmployeeName ASC) AS Sno
FROM @Employee T
) AS T2
WHERE T1.Id = T2.Id AND T2.Sno > 1
SELECT * FROM @Employee AS T
-
CreatedJan 26, 2020
-
UpdatedNov 03, 2020
-
Views1,448
Related Articles
Different types of variables in SQL Server
What is Cross Join in SQL Server
How delete record from parent table when there is Foreign Key relation in SQL Server
What is the differences between CHAR, NCHAR, VARCHAR and NVARCHAR in SQL Server?
How to add or remove a column from a table in SQL Server?
How to insert values into Identity Column in SQL Server?
How to get a fixed-length value in SQL Server?
What is Left Join (or) Left Outer Join in SQL Server?
How to get current week dates in SQL Server?
What are the different types of Date formats in SQL Server?