EN
Node.js - PostgreSQL - rows pagination
3 points
In this article, we would like to show you how to paginate data rows in the PostgreSQL using Node.js.
Note:
Pagination consists in dividing data into pages and sending only those rows that the client currently needs - we do not have to send all data at once.

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: 'my_username',
6
database: 'my_database',
7
password: 'my_password',
8
port: 5432,
9
});
10
11
const fetchRows = async (pageNumber, pageSize) => {
12
const query = `
13
SELECT *
14
FROM "users"
15
ORDER BY "users"."id"
16
LIMIT $2
17
OFFSET (($1 - 1) * $2);
18
`;
19
await client.connect(); // creates connection
20
try {
21
const { rows } = await client.query(query, [pageNumber, pageSize]); // sends query
22
return rows;
23
} finally {
24
await client.end(); // closes connection
25
}
26
};
27
28
fetchRows(1, 3) // fetch 3 rows from page 1
29
.then(result => console.table(result))
30
.catch(error => console.error(error.stack));
Result:
xxxxxxxxxx
1
┌─────────┬────┬─────────┬───────────┬───────────────┬───────────┐
2
│ (index) │ id │ name │ surname │ department_id │ salary │
3
├─────────┼────┼─────────┼───────────┼───────────────┼───────────┤
4
│ 0 │ 1 │ 'John' │ 'Stewart' │ 1 │ '2000.00' │
5
│ 1 │ 2 │ 'Chris' │ 'Brown' │ 3 │ '2000.00' │
6
│ 2 │ 3 │ 'Chris' │ 'Lewis' │ 3 │ '2000.00' │
7
└─────────┴────┴─────────┴───────────┴───────────────┴───────────┘
Result for fetchRows(2, 4)
:
xxxxxxxxxx
1
┌─────────┬────┬─────────────┬───────────┬───────────────┬───────────┐
2
│ (index) │ id │ name │ surname │ department_id │ salary │
3
├─────────┼────┼─────────────┼───────────┼───────────────┼───────────┤
4
│ 0 │ 5 │ 'Kate' │ 'Stewart' │ 3 │ '2000.00' │
5
│ 1 │ 6 │ 'Ailisa' │ 'Lewis' │ 3 │ '2000.00' │
6
│ 2 │ 7 │ 'Ailisa' │ 'Gomez' │ 3 │ '3000.00' │
7
│ 3 │ 8 │ 'Gwendolyn' │ 'James' │ 2 │ '3000.00' │
8
└─────────┴────┴─────────────┴───────────┴───────────────┴───────────┘
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 *
2
FROM "users"
3
ORDER BY "users"."id"
4
LIMIT 4
5
OFFSET 1 * 4;