EN
Node.js - PostgreSQL - find duplicated values in multiple columns
0 points
In this article, we would like to show you how to find duplicated values in multiple columns in the PostgreSQL database using Node.js.

Note: at the end of this article you can find database preparation SQL queries.
xxxxxxxxxx
1
const { Client } = require('pg');
2
3
const client = new Client({
4
host: '127.0.0.1',
5
user: 'postgres',
6
database: 'database_name',
7
password: 'password',
8
port: 5432,
9
});
10
11
const fetchDuplicateCollumns = async () => {
12
const query = `
13
SELECT
14
"name", COUNT("name") AS "name_count",
15
"country", COUNT("country") AS "country_count"
16
FROM "users"
17
GROUP BY "name", "country"
18
HAVING (COUNT("name") > 1) AND (COUNT("country") > 1);`;
19
try {
20
await client.connect(); // creates connection
21
const { rows } = await client.query(query); // sends query
22
console.table(rows);
23
} catch (error) {
24
console.error(error.stack);
25
} finally {
26
await client.end(); // closes connection
27
}
28
};
29
30
fetchDuplicateCollumns();
Result:
xxxxxxxxxx
1
┌─────────┬─────────┬────────────┬───────────┬───────────────┐
2
│ (index) │ name │ name_count │ country │ country_count │
3
├─────────┼─────────┼────────────┼───────────┼───────────────┤
4
│ 0 │ 'Kim' │ '2' │ 'Vietnam' │ '2' │
5
│ 1 │ 'Chris' │ '2' │ 'Spain' │ '2' │
6
│ 2 │ 'Tom' │ '3' │ 'Poland' │ '3' │
7
└─────────┴─────────┴────────────┴───────────┴───────────────┘
Note:
Notice that
Chris
user bothand
name_count
equals
country_count
2
because one user is from a different country.
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"email" VARCHAR(100) NOT NULL,
5
"country" VARCHAR(15) NOT NULL,
6
PRIMARY KEY ("id")
7
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "email", "country")
3
VALUES
4
('Tom', 'tom1@email.com', 'Poland'),
5
('Tom', 'tom2@email.com', 'Poland'),
6
('Tom', 'tom3@email.com', 'Poland'),
7
('Kim', 'kim1@email.com', 'Vietnam'),
8
('Kim', 'kim2@email.com', 'Vietnam'),
9
('Chris', 'chris1@email.com', 'Spain'),
10
('Chris', 'chris2@email.com', 'Spain'),
11
('Chris', 'chris3@email.com', 'USA');
Native SQL query (used in the above example):
xxxxxxxxxx
1
SELECT "name", COUNT("name") AS "name_count"
2
FROM "users"
3
GROUP BY "name"
4
HAVING COUNT("name") > 1