Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Query WHERE date is greater than 3 years old

I have a table that contains 4 dates:

CREATE TABLE dates (
    date date
);

    11-mar-2008
    25-now-2007
    18-apr-2012
    20-apr-2012

I need a query that returns all dates that are older than three-years-old. That should be the first 2 dates.

This doesn't work for me:

SELECT * FROM dates WHERE date = now()::-1095;
like image 521
Danny Calladine Avatar asked Apr 21 '12 11:04

Danny Calladine


People also ask

Is greater than in PostgreSQL?

You can use the > operator in PostgreSQL to test for an expression greater than. SELECT * FROM products WHERE product_id > 50; In this example, the SELECT statement would return all rows from the products table where the product_id is greater than 50.

Does Postgres have datediff?

PostgreSQL provides a datediff function to users. The datediff means we can return the difference between two dates based on their specified interval. The datediff function plays an important role in the database management system because datediff functions as a calendar and it is very helpful to users.

How does Postgres store historical data?

To store historical data in Postgres, we are going to use two slightly more advanced tools: partitioning and triggers. Partitioning will allow us to separate our table into logical partitions, i.e. by month or week, while still allowing for queries among all rows.


1 Answers

SELECT 
  * 
FROM 
  dates 
WHERE 
  date < now() - '3 years' :: interval;

Also, naming your column date is not a good practice, as this is a reserved word in PostgreSQL.

like image 65
vyegorov Avatar answered Sep 21 '22 05:09

vyegorov