Dates in PostgreSQL: DATE_TRUNC, EXTRACT and INTERVAL
PostgreSQL handles dates with DATE_TRUNC, EXTRACT and intervals.
Dialects · PostgreSQL
Free. No sign up. Your progress stays in this browser.
What you will learn
DATE_TRUNC is the workhorse of monthly reports.
Intervals read like English: INTERVAL '30 days'.
The basics
PostgreSQL works with dates through DATE_TRUNC, EXTRACT and intervals.
SELECT DATE_TRUNC('month', due_date) AS month, COUNT(*)
FROM invoices
GROUP BY DATE_TRUNC('month', due_date)
ORDER BY monthSELECT due_date + INTERVAL '30 days' AS reminder_date,
EXTRACT(YEAR FROM due_date) AS year
FROM invoicesDATE_TRUNC returns the start of the period, as a timestamp in real PostgreSQL. Intervals move dates: INTERVAL '1 month'. Subtracting two dates gives the number of days. There is no DATEADD, DATEDIFF or YEAR().
Worked examples
Example 1
Signups per month.
SELECT DATE_TRUNC('month', signup_date) AS month, COUNT(*)
FROM users
GROUP BY DATE_TRUNC('month', signup_date)
ORDER BY monthEach date becomes the first day of its month.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Using DATEADD or DATEDIFF.
- Forgetting the quotes around the unit in DATE_TRUNC.
- Expecting DATE_TRUNC to return a plain date; it returns a timestamp.
Where you will use it at work
- Product: monthly active users.
- Marketing: leads per week.
- Finance: revenue per quarter.
Questions people ask
How do I add days?
d + INTERVAL '30 days', or d + 30 for a date.
Days between two dates?
Subtract them: end_date minus start_date gives a whole number of days.
Year of a date?
EXTRACT(YEAR FROM d) or DATE_PART('year', d).
Ready to write it yourself?
Practice Dates in PostgreSQLRelated guides
SQL Practice is independent and not affiliated with the maker of this database. The exercises run on SQLite in your browser and imitate this dialect’s syntax for practice.