EN
Node.js - PostgreSQL Select last row
0
points
In this article, we would like to show you how to select the last row in theΒ PostgresΒ database from Node.js level.
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: 'my_username',
database: 'my_database',
password: 'my_password',
port: 5432,
});
const fetchLastRows = async (count) => {
const query = `
SELECT * FROM "users"
ORDER BY "id" DESC
LIMIT $1;
`;
await client.connect(); // creates connection
try {
const { rows } = await client.query(query, [count]); // sends query
return rows;
} finally {
await client.end(); // closes connection
}
};
fetchLastRows(1) // get only 1 row from the end of the table
.then(result => console.table(result))
.catch(error => console.error(error.stack));
Result:Β
βββββββββββ¬βββββ¬ββββββββ¬ββββββββββββββββββ¬ββββββββββββ
β (index) β id β name β email β country β
βββββββββββΌβββββΌββββββββΌββββββββββββββββββΌββββββββββββ€
β 0 β 7 β 'Nam' β 'nam@email.com' β 'Vietnam' β
βββββββββββ΄βββββ΄ββββββββ΄ββββββββββββββββββ΄ββββββββββββ
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"
ORDER BY "id" DESC
LIMIT 1;