EN
Node.js - PostgreSQL Find rows created within the last hour / hours
0
points
In this article, we would like to show you how to find rows created within the last hours in the Postgres database from Node.js level.
Note:Β at the end of this article you can find database preparation SQL queries.
const pg = require('pg');
const pg = require('pg');
const types = pg.types;
types.setTypeParser(1114, (stringValue) => {
return stringValue;
});
const client = new Client({
host: '127.0.0.1',
user: 'my_username',
database: 'my_database',
password: 'my_password',
port: 5432,
});
const fetchEventsFromLastHours = async (hourCount) => {
const query = `
SELECT *
FROM "events"
WHERE "event_timestamp" > NOW() - $1 * interval '1 hour';
`;
await client.connect(); // creates connection
try {
const { rows } = await client.query(query, [hourCount]); // sends query
return rows;
} finally {
await client.end(); // closes connection
}
};
fetchEventsFromLastHours(2) // enter the number of hours you want to get results
.then(result => console.table(result))
.catch(error => console.error(error.stack));
In the example above, the code runs on 4/23/2021 21:00:00
, so the results are:
βββββββββββ¬βββββ¬ββββββββββββββββββββββββ
β (index) β id β event_timestamp β
βββββββββββΌβββββΌββββββββββββββββββββββββ€
β 0 β 11 β '2021-04-23 19:49:39' β
β 1 β 12 β '2021-04-23 20:50:40' β
βββββββββββ΄βββββ΄ββββββββββββββββββββββββ
Database preparation
create_tables.sql
Β file:
CREATE TABLE "events" (
"id" SERIAL PRIMARY KEY,
"event_timestamp" TIMESTAMP NOT NULL
);
insert_data.sql
Β file:
INSERT INTO "events"
("event_timestamp")
VALUES
('2021-03-11 11:41:31'),
('2021-03-21 12:42:32'),
('2021-03-22 14:44:34'),
('2021-03-22 15:45:35'),
('2021-03-23 16:46:36'),
('2021-04-05 17:47:37'),
('2021-04-05 19:49:39'),
('2021-04-16 20:50:40'),
('2021-04-17 15:45:35'),
('2021-04-23 16:46:36'),
('2021-04-23 19:49:39'),
('2021-04-23 20:50:40');
Native SQL query (used in the above example):
SELECT *
FROM "events"
WHERE "event_timestamp" > NOW() - 2 * interval '1 hour';