Languages
[Edit]
EN

PostgreSQL - delete all duplicated rows except one

0 points
Created by:
Dirask Admin - MR
1340

In this article, we would like to show you how to delete duplicated rows except one in PostgreSQL.

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:

PostgreSQL - example data used to delete duplicated rows except one
PostgreSQL - 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" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"email" VARCHAR(100) NOT NULL,
	"country" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
)
ENGINE=InnoDB;

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');

PostgreSQL - problems

PostgreSQL - 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