Languages
[Edit]
EN

Node.js - PostgreSQL - select first N rows

0 points
Created by:
Dirask Admin - MR
1340

In this article, we would like to show you how to select the first N rows in the PostgreSQL database using Node.js.

Node.js - PostgreSQL - select first N rows
Data used in the example - 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 fetchUsers = async (count) => {
    try {
        await client.connect(); // gets connection
        const { rows } = await client.query('SELECT * FROM "users" LIMIT $1', [count]);
        console.table(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();     // closes connection
    }
};

fetchUsers(3); // fetch first 3 rows

Result: 

┌─────────┬────┬─────────┬───────────────────┬──────────┐
│ (index) │ id │  name   │       email       │ country  │
├─────────┼────┼─────────┼───────────────────┼──────────┤
│    0    │ 1  │  'Tom'  │  'tom@email.com'  │ 'Poland' │
│    1    │ 2  │ 'Chris' │ 'chris@email.com' │ 'Spain'  │
│    2    │ 3  │ 'Jack'  │ 'jack@email.com'  │ 'Spain'  │
└─────────┴────┴─────────┴───────────────────┴──────────┘

Database preparation

create_tables.sql file:

CREATE TABLE "users" (
	"id" SERIAL,
	"name" VARCHAR(100) NOT NULL,
	"email" VARCHAR(100) NOT NULL,
	"country" VARCHAR(15) NOT NULL,
	PRIMARY KEY ("id")
);

insert_data.sql file:

INSERT INTO "users"
    ("name", "email", "country")
VALUES
    ('Tom', 'tom@email.com', 'Poland'),
    ('Chris', 'chris@email.com', 'Spain'),
    ('Jack', 'jack@email.com', 'Spain'),
    ('Kim', 'kim@email.com', 'Vietnam'),
    ('Marco', 'marco@email.com', 'Italy'),
    ('Kate', 'kate@email.com', 'Spain'),
    ('Nam', 'nam@email.com', 'Vietnam');

Native SQL query (used in the above example):

SELECT * 
FROM "users" 
LIMIT 3      -- LIMIT N

Node.js - PostgreSQL - Problems

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