EN
Node.js - PostgreSQL GROUP BY
0 points
In this article, we would like to show you how to use PostgreSQL GROUP BY in 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 fetchGroupedUsers = async () => {
12
const query = `SELECT COUNT("id") AS "number of users", "country"
13
FROM "users"
14
GROUP BY "country"
15
ORDER BY COUNT("id") DESC;`;
16
try {
17
await client.connect(); // creates connection
18
const { rows } = await client.query(query); // sends query
19
console.table(rows);
20
} catch (error) {
21
console.error(error.stack);
22
} finally {
23
await client.end(); // closes connection
24
}
25
};
26
27
fetchGroupedUsers();
Result:
xxxxxxxxxx
1
┌─────────┬─────────────────┬───────────┐
2
│ (index) │ number of users │ country │
3
├─────────┼─────────────────┼───────────┤
4
│ 0 │ '3' │ 'Spain' │
5
│ 1 │ '2' │ 'Vietnam' │
6
│ 2 │ '1' │ 'Italy' │
7
│ 3 │ '1' │ 'Poland' │
8
└─────────┴─────────────────┴───────────┘
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"country" VARCHAR(15) NOT NULL,
5
PRIMARY KEY ("id")
6
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "country")
3
VALUES
4
('Tom', 'Poland'),
5
('Chris', 'Spain'),
6
('Jack', 'Spain'),
7
('Kim', 'Vietnam'),
8
('Marco', 'Italy'),
9
('Kate', 'Spain'),
10
('Nam', 'Vietnam');