EN
MS SQL Server - delete all duplicated rows except one
0
points
In this article, we would like to show you how to delete duplicated rows except one in MS SQL Server.
Quick solution:
DELETE n1
FROM [users] n1, [users] n2
WHERE n1.id > n2.id AND n1.name = n2.name
Practical example
To show how to delete duplicated rows except one, we will use the following users
table:
Note:
At the end of this article you can find database preparation SQL queries.
Example 1 - keep row with the lowest id
value
In this example, we will delete all the rows with duplicated name except one, with the lowest id
value.
Query:
DELETE n1
FROM [users] n1, [users] n2
WHERE n1.id > n2.id AND n1.name = n2.name;
Result:
Example 2 - keep row with the highest id
value
In this example, we will delete all the rows with duplicated name except one, with the highest id
value.
Query:
DELETE n1
FROM [users] n1, [users] n2
WHERE n1.id < n2.id AND n1.name = n2.name;
Result:
Database preparation
create_tables.sql
file:
CREATE TABLE [users] (
[id] INT IDENTITY(1,1),
[name] VARCHAR(100) NOT NULL,
[email] VARCHAR(100) NOT NULL,
[country] VARCHAR(15) NOT NULL,
PRIMARY KEY ([id])
);
insert_data.sql
file:
INSERT INTO [users]
([name], [email], [country])
VALUES
('Tom', 'tom1@email.com', 'Poland'),
('Tom', 'tom2@email.com', 'Poland'),
('Tom', 'tom3@email.com', 'Poland'),
('Kim', 'kim1@email.com', 'Vietnam'),
('Kim', 'kim2@email.com', 'Vietnam'),
('Chris', 'chris1@email.com', 'Spain'),
('Chris', 'chris2@email.com', 'Spain'),
('Chris', 'chris3@email.com', 'USA');