Delete duplicate records from table in SQL Server using ROW_NUMBER()
In this article I will explain how to Delete duplicate records from table in SQL Server using ROW_NUMBER().
sometimes we required to delete duplicate records from a table .
Suppose we have a table with some duplicate data
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Students](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Class] [nchar](10) NULL,
CONSTRAINT [PK_tbl_Students] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
sometimes we required to delete duplicate records from a table .
Suppose we have a table with some duplicate data
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Students](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](50) NULL,
[Class] [nchar](10) NULL,
CONSTRAINT [PK_tbl_Students] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Now Create Query for delete and Excute it
WITH Tempstudents(Name,duplicateCount)
AS
(
SELECT Name,ROW_NUMBER() OVER(PARTITION by Name ORDER BY Name)
AS duplicateCount
FROM tbl_Students
)
DELETE FROM Tempstudents
WHERE duplicateCount > 1
Snapshot After Excute above Query :
Comments
Post a Comment