Languages
[Edit]
EN

Node.js - PostgreSQL BETWEEN clause

0 points
Created by:
Mariam-Barron
391

In this article, we would like to show you how to use SQL BETWEEN clause in Node.js.

Note: at the end of this article you can find database preparation SQL queries.

Between clause example

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 (fromID, toID) => {
    const query = `SELECT * FROM "users"
                   WHERE "id" BETWEEN $1 AND $2`;
    try {
        await client.connect();                                     // gets connection
        const { rows } = await client.query(query, [fromID, toID]); // sends queries
        console.log(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();                                         // closes connection
    }
};

fetchUsers(2, 4); // id >= 2 AND id <= 4

Result: 

[
    { id: 2, name: 'Chris', role: 'moderator' },
    { id: 3, name: 'Kate',  role: 'user' },
    { id: 4, name: 'Denis', role: 'moderator' }
]

Note: 

BETWEEN clause is used very often for dates.

Database preparation

create_tables.sql file:

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

insert_data.sql file:

INSERT INTO "users"
	("name", "role")
VALUES
	('John', 'admin'),
	('Chris', 'moderator'),
	('Kate', 'user'),
	('Denis', 'moderator');

Node.js - PostgreSQL

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