Languages
[Edit]
EN

Node.js - PostgreSQL HAVING clause

0 points
Created by:
Dirask Admin - MR
1340

In this article, we would like to show you how to use PostgreSQL HAVING clause in Node.js.

Example data used with GROUP BY statement - HeidiSQL
Example data used with HAVING clause - 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 fetchGroupedUsers = async (minimum) => {
    const query = `SELECT COUNT("id") AS "number of users", "country"
                   FROM "users"
                   GROUP BY "country"
                   HAVING COUNT("id") >= $1;`;
    try {
        await client.connect();  // creates connection
        const { rows } = await client.query(query, [minimum]); // sends query
        console.table(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();      // closes connection
    }
};

fetchGroupedUsers(2); // Each group will have at least 2 users.

Result: 

┌─────────┬─────────────────┬───────────┐
│ (index) │ number of users │  country  │
├─────────┼─────────────────┼───────────┤
│    0    │       '3'       │  'Spain'  │
│    1    │       '2'       │ 'Vietnam' │
└─────────┴─────────────────┴───────────┘

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