Languages
[Edit]
EN

Node.js - PostgreSQL - find duplicated values in multiple columns

0 points
Created by:
Dirask Admin - MR
1340

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

Node.js - PostgreSQL - find duplicated values in multiple columns
Data used in the example - HeidiSQL

Note: at the end of this article you can find database preparation SQL queries.

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'postgres',
    database: 'database_name',
    password: 'password',
    port: 5432,
});

const fetchDuplicateCollumns = async () => {
    const query = `
		SELECT 
			"name", COUNT("name") AS "name_count",
			"country", COUNT("country") AS "country_count"
		FROM "users"
		GROUP BY "name", "country"
		HAVING (COUNT("name") > 1) AND (COUNT("country") > 1);`;
    try {
        await client.connect();  // creates connection
        const { rows } = await client.query(query); // sends query
		console.table(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();      // closes connection
    }
};

fetchDuplicateCollumns(); 

Result: 

┌─────────┬─────────┬────────────┬───────────┬───────────────┐
│ (index) │  name   │ name_count │  country  │ country_count │
├─────────┼─────────┼────────────┼───────────┼───────────────┤
│    0    │  'Kim'  │    '2'     │ 'Vietnam' │      '2'      │
│    1    │ 'Chris' │    '2'     │  'Spain'  │      '2'      │
│    2    │  'Tom'  │    '3'     │ 'Poland'  │      '3'      │
└─────────┴─────────┴────────────┴───────────┴───────────────┘

Note:

Notice that Chris user both name_count and country_count equals 2 because one user is from a different country.

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

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

Native SQL query (used in the above example):

SELECT "name", COUNT("name") AS "name_count"
FROM "users"
GROUP BY "name"
HAVING COUNT("name") > 1

Node.js - PostgreSQL - Problems

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