Languages
[Edit]
EN

MS SQL Server - delete all duplicated rows except one

0 points
Created by:
Dirask JS Member
3610

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:

MS SQL Server - example data used to delete duplicated rows except one
MS SQL Server - example data used to delete duplicated rows except one

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:

delete duplicated rows except one - result
delete duplicated rows except one - 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:

delete duplicated rows except one - result
delete duplicated rows except one - 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');

MS SQL Server - problems

MS SQL Server - delete all duplicated rows except one
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join