Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Devops
  3. Question
Devops

How to compare dates in datetime fields in Postgresql?

Asked by Danna Sahi Jul 1, 2021 10.8K views 2 answers
Share

About this question

I have been facing a strange scenario when comparing dates in PostgreSQL(version 9.2.4 in windows). I have a column in my table say update_date with type 'timestamp without timezone'. Client can search over this field with only date (i.e: 2013-05-03) or date with time (i.e: 2013-05-03 12:20:00). This column has the value as the timestamp for all rows currently and has the same date part(2013-05-03) but the difference in time part.

When I'm comparing over this column, I'm getting different results. Like the followings:

select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date < '2013-05-03' -> No results
select * from table where update_date >= '2013-05-03' AND update_date <= '2013-05-04' -> results found
select * from table where update_date >= '2013-05-03' -> results found

My question is how can I make the first query possible to get results, I mean why the 3rd query is working but not the first one?

Why use Postgre date comparison?

Can anybody help me with this? Thanks in advance.

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on May 22, 2024

In PostgreSQL, comparing dates in datetime fields can be done using several methods and operators. Here are some common approaches:

1. Using Comparison Operators

PostgreSQL supports standard comparison operators such as <, <=, >, >=, =, and != for comparing dates.

Example:

SELECT *
FROM your_table
WHERE date_column > '2023-05-22';

2. Using the BETWEEN Operator

The BETWEEN operator can be used to check if a date falls within a specific range.

Example:

SELECT *
FROM your_table
WHERE date_column BETWEEN '2023-01-01' AND '2023-12-31';

3. Using the AGE Function

The AGE function can be used to calculate the interval between two dates, which can then be compared.

Example:

SELECT *
FROM your_table
WHERE AGE(NOW(), date_column) > INTERVAL '1 year';

4. Extracting Date Parts

You can extract parts of a date (like year, month, day) and compare them.

Example:

SELECT *
FROM your_table
WHERE EXTRACT(YEAR FROM date_column) = 2023;


Was this helpful?

More Devops discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest DevOps Blogs

Guides, tips and career advice on DevOps from JanBask experts.