Languages
[Edit]
EN

Node.js - PostgreSQL ORDER BY

3 points
Created by:
a_horse
538

In this article, we would like to show you how to use SQL ORDER BY in Node.js with Postgress.

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

Ascending order:

In this section you can find example that orders results using A-Z direction.

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 (orderBy) => {
    const query = `SELECT * 
                   FROM "users"
                   ORDER BY $1`; // it abbreviated form to: ORDER BY $1 ASC
    try {
        await client.connect();                                // creates connection
        const { rows } = await client.query(query, [orderBy]); // sends queries
        console.log(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();                                    // closes connection
    }
};

fetchUsers('name');

Result: 

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

Descending order:

In this section you can find example that orders results using Z-A direction.

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

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

const fetchUsers = async (orderBy) => {
    const query = `SELECT * 
                   FROM "users"
                   ORDER BY $1 DESC`;
    try {
        await client.connect();                                // gets connection
        const { rows } = await client.query(query, [orderBy]); // sends queries
        console.log(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();                                    // closes connection
    }
};

fetchUsers('id');

Result: 

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

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 ORDER BY with async/await
  2. Node.js - PostgreSQL Sort in ascending or descending order
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