Languages
[Edit]
EN

Node.js - PostgreSQL WHERE clause

0 points
Created by:
Bess
571

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

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

fetchUsers('Chris'); // username 

Result: 

[{ id: 2, name: 'Chris', role: 'moderator' }]

Multiple conditions example:

const { Client } = require('pg');

const client = new Client({
    host: '127.0.0.1',
    user: 'postgres',
    database: 'dirask',
    password: 'password',
    port: 5432,
});

const fetchUsers = async (userName, userRole) => {
    const query = `SELECT * 
                   FROM "users"
                   WHERE "name" = $1 OR "role" = $2`;
    try {
        await client.connect(); // gets connection
        const { rows } = await client.query(query, [userName, userRole]); // sends queries
        console.log(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end(); // closes connection
    }
};

fetchUsers('Chris', 'admin');

Result: 

[
    { id: 1, name: 'John', role: 'admin' },
    { id: 2, name: 'Chris', role: 'moderator' }
]

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');

Alternative titles

  1. Node.js - PostgreSQL WHERE clause with async/await
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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