Languages
[Edit]
EN

Node.js - PostgreSQL SELECT DISTINCT statement

0 points
Created by:
Dirask Admin - Marvin
1940

In this article, we would like to show you how to make PostgreSQL SELECT DISTINCT statement in Node.js.

example data used with SELECT DISTINCT statement
Example data used with SELECT DISTINCT statement - HeidiSQL

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

1.Β Practical example

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

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

const fetchUniqueUsers = async () => {
    try {
        await client.connect();      // gets connection
        const { rows } = await client.query('SELECT DISTINCT "country" FROM "users"');
        console.table(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();          // closes connection
    }
};

fetchUniqueUsers();

Result:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚  country  β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚  'Spain'  β”‚
β”‚    1    β”‚  'Italy'  β”‚
β”‚    2    β”‚ 'Vietnam' β”‚
β”‚    3    β”‚ 'Poland'  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

2.Β Database preparation

create_tables.sqlΒ file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"country" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
);

insert_data.sqlΒ file:

INSERT INTO "users"
	("name", "country")
VALUES
    ('Tom', 'Poland'),
    ('Chris', 'Spain'),
    ('Jack', 'Spain'),
    ('Kim', 'Vietnam'),
    ('Marco', 'Italy'),
    ('Kate', 'Spain'),
    ('Nam', 'Vietnam');

Node.js - PostgreSQL

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