SQL Query

PostgreSQL: How to Calculate Date Difference in SQL

PostgreSQL guide: Calculate the difference between two dates in days, months, or years.

This guide is specifically for PostgreSQL syntax.

How to Calculate Date Difference in SQL

Calculate the difference between two dates in days, months, or years.

Quick Answer

SELECT DATEDIFF(end_date, start_date) FROM table;

Explanation

DATEDIFF calculates the difference between dates. Syntax varies by database. MySQL uses DATEDIFF(date1, date2), SQL Server uses DATEDIFF(unit, date1, date2).

Query Variants

Mysql Days

SELECT DATEDIFF(end_date, start_date) as days FROM projects;

Postgres Days

SELECT end_date - start_date as days FROM projects;

Sqlserver

SELECT DATEDIFF(day, start_date, end_date) as days FROM projects;

Months

SELECT TIMESTAMPDIFF(MONTH, start_date, end_date) as months FROM projects;

Pro Tips

  • Check your database's date function syntax
  • Consider timezone issues
  • Use appropriate units (day, month, year)

Related SQL Queries

Continue learning with more SQL query examples:


PostgreSQL-Specific Notes

This page covers PostgreSQL syntax. Other databases may have different syntax for similar operations.

Related Content

Try it yourself

Practice this query in our interactive SQL sandbox.