PostgreSQL: Select All Records Older than N Days


Often in PostgreSQL you may want to select all records from a table with a date older than a specific number of days.

You can use the following syntax to do so:

SELECT *
FROM emp
WHERE start_date < CURRENT_DATE - interval '30 days';

This particular example will select all records from the table named emp where the date in the start_date column is older than 30 days.

Note that the CURRENT_DATE command in PostgreSQL returns the current date.

Also note that you can change 30 to any number you’d like to instead select records older than a different number of days.

The following example shows how to use this syntax in practice.

Example: Select All Records Older than N Days in PostgreSQL

Suppose that we create the following table named emp that contains information about various employees at some company including their starting date and their total sales made:

-- create table named 'emp'
CREATE TABLE emp (
  empID INT PRIMARY KEY,
  start_date DATE,
  sales INT
);

-- add rows to the table 
INSERT INTO emp VALUES (0001, '2024-08-01', 134);
INSERT INTO emp VALUES (0002, '2024-07-01', 201);
INSERT INTO emp VALUES (0003, '2024-08-22', 155);
INSERT INTO emp VALUES (0004, '2024-08-26', 98);
INSERT INTO emp VALUES (0005, '2024-08-28', 65);
INSERT INTO emp VALUES (0006, '2024-06-20', 52);
INSERT INTO emp VALUES (0007, '2024-08-22', 50);

-- view all rows in table
SELECT * FROM emp;

 empid | start_date | sales 
-------+------------+-------
     1 | 2024-08-01 |   134
     2 | 2024-07-01 |   201
     3 | 2024-08-22 |   155
     4 | 2024-08-26 |    98
     5 | 2024-08-28 |    65
     6 | 2024-06-20 |    52
     7 | 2024-08-22 |    50

This article is currently being written on 9/17/2024.

Suppose that we would like to select all records from this table where the date in the start_date column is older than 30 days.

We can use the following syntax to do so:

SELECT *
FROM emp
WHERE start_date < CURRENT_DATE - interval '30 days';

 empid | start_date | sales 
-------+------------+-------
     1 | 2024-08-01 |   134
     2 | 2024-07-01 |   201
     6 | 2024-06-20 |    52

The resulting table contains all records from the original table where the date in the start_date column is older than 30 days.

Feel free to use similar syntax to select all records older than a specific number of days in your own table.

Additional Resources

The following tutorials explain how to perform other common tasks in PostgreSQL:

PostgreSQL: How to Select Rows in Date Range
PostgreSQL: How to Extract Date from a Timestamp
PostgreSQL: How to Extract Month from Date
PostgreSQL: How to Extract Year from Date

Leave a Reply