EN
Node.js - PostgreSQL - GROUP BY multiple columns
0 points
In this article, we would like to show you how to GROUP BY 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 fetchUsers = async () => {
12
const query = `SELECT "name", "department_id", COUNT(*)
13
FROM "users"
14
GROUP BY "name","department_id"
15
ORDER BY "name";`;
16
try {
17
await client.connect(); // gets 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
fetchUsers();
Result:
xxxxxxxxxx
1
┌─────────┬─────────────┬───────────────┬───────┐
2
│ (index) │ name │ department_id │ count │
3
├─────────┼─────────────┼───────────────┼───────┤
4
│ 0 │ 'Ailisa' │ 3 │ '2' │
5
│ 1 │ 'Chris' │ 3 │ '2' │
6
│ 2 │ 'Gwendolyn' │ 2 │ '1' │
7
│ 3 │ 'John' │ 1 │ '1' │
8
│ 4 │ 'Kate' │ 3 │ '2' │
9
│ 5 │ 'Simon' │ 3 │ '2' │
10
│ 6 │ 'Simon' │ 2 │ '1' │
11
└─────────┴─────────────┴───────────────┴───────┘
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(50) NOT NULL,
4
"surname" VARCHAR(50) NOT NULL,
5
"department_id" INTEGER,
6
"salary" DECIMAL(15,2) NOT NULL,
7
PRIMARY KEY ("id")
8
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
( "name", "surname", "department_id", "salary")
3
VALUES
4
('John', 'Stewart', 1, '2000.00'),
5
('Chris', 'Brown', 3, '2000.00'),
6
('Chris', 'Lewis', 3, '2000.00'),
7
('Kate', 'Lewis', 3, '2000.00'),
8
('Kate', 'Stewart', 3, '2000.00'),
9
('Ailisa', 'Lewis', 3, '2000.00'),
10
('Ailisa', 'Gomez', 3, '3000.00'),
11
('Gwendolyn', 'James', 2, '3000.00'),
12
('Simon', 'James', 2, '2000.00'),
13
('Simon', 'Brown', 3, '2000.00'),
14
('Simon', 'Collins', 3, '3000.00');
Native SQL query (used in the above example):
xxxxxxxxxx
1
SELECT "name", "department_id", COUNT(*)
2
FROM "users"
3
GROUP BY "name","department_id"
4
ORDER BY "name"