EN
Node.js - PostgreSQL - select first N rows
0 points
In this article, we would like to show you how to select the first N rows 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 (count) => {
12
try {
13
await client.connect(); // gets connection
14
const { rows } = await client.query('SELECT * FROM "users" LIMIT $1', [count]);
15
console.table(rows);
16
} catch (error) {
17
console.error(error.stack);
18
} finally {
19
await client.end(); // closes connection
20
}
21
};
22
23
fetchUsers(3); // fetch first 3 rows
Result:
xxxxxxxxxx
1
┌─────────┬────┬─────────┬───────────────────┬──────────┐
2
│ (index) │ id │ name │ email │ country │
3
├─────────┼────┼─────────┼───────────────────┼──────────┤
4
│ 0 │ 1 │ 'Tom' │ 'tom@email.com' │ 'Poland' │
5
│ 1 │ 2 │ 'Chris' │ 'chris@email.com' │ 'Spain' │
6
│ 2 │ 3 │ 'Jack' │ 'jack@email.com' │ 'Spain' │
7
└─────────┴────┴─────────┴───────────────────┴──────────┘
create_tables.sql
file:
xxxxxxxxxx
1
CREATE TABLE "users" (
2
"id" SERIAL,
3
"name" VARCHAR(100) NOT NULL,
4
"email" VARCHAR(100) NOT NULL,
5
"country" VARCHAR(15) NOT NULL,
6
PRIMARY KEY ("id")
7
);
insert_data.sql
file:
xxxxxxxxxx
1
INSERT INTO "users"
2
("name", "email", "country")
3
VALUES
4
('Tom', 'tom@email.com', 'Poland'),
5
('Chris', 'chris@email.com', 'Spain'),
6
('Jack', 'jack@email.com', 'Spain'),
7
('Kim', 'kim@email.com', 'Vietnam'),
8
('Marco', 'marco@email.com', 'Italy'),
9
('Kate', 'kate@email.com', 'Spain'),
10
('Nam', 'nam@email.com', 'Vietnam');
Native SQL query (used in the above example):
xxxxxxxxxx
1
SELECT *
2
FROM "users"
3
LIMIT 3 -- LIMIT N