Languages
[Edit]
EN

PostgreSQL - Find rows created within the last month / months

0 points
Created by:
Wade
352

In this article, we would like to show you how to find rows created within the last months in PostgreSQL.

PostgreSQL - Find rows created within the last hour / hours
Table used in the example - HeidiSQL

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

Query:

SELECT *
FROM "events"
WHERE "event_timestamp" > NOW() - '1 month'::interval; -- or 2,3,4... months

In the example above, the code runs on 4/24/2021, so the results are:

PostgreSQL - Find rows created within the last month / months
Results - HeidiSQL

Note:

Instead of '1 month'::interval we can write interval '1 months' - this is an older notation.

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

PostgreSQL - dates

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