Languages
[Edit]
EN

Node.js - PostgreSQL - find first row

0 points
Created by:
cory
1486

In this article, we would like to show you how to find the first row in the PostgreSQL database usingΒ Node.js.

Node.js - PostgreSQL - find first row
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 getFirstRowOrderedByName = async () => {
    const query = `SELECT *
			       FROM "users"
			       ORDER BY "name"
			       LIMIT 1;`;
    try {
        await client.connect();  // creates connection
        const { rows } = await client.query(query); // sends query
		console.table(rows);
    } catch (error) {
        console.error(error.stack);
    } finally {
        await client.end();      // closes connection
    }
};

getFirstRowOrderedByName();

Result:Β 

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ (index) β”‚ id β”‚  name   β”‚       email       β”‚ country β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚    0    β”‚ 2  β”‚ 'Chris' β”‚ 'chris@email.com' β”‚ 'Spain' β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

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"
ORDER BY "name"
LIMIT 1
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 - 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