SQL date functions
Almost every business question involves time: orders per month, customers per year, days since signup. PostgreSQL has excellent date functions.
EXTRACT pulls out a part of a date (YEAR, MONTH, DOW). DATE_TRUNC rounds a date down to the start of a period, which is ideal for grouping by month. Subtracting two dates gives the number of days between them.
Syntax
EXTRACT(YEAR FROM date_col)
DATE_TRUNC('month', date_col)
date_col + INTERVAL '7 days'
DATE '2026-01-01' - date_colTry it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Group by year
SELECT EXTRACT(YEAR FROM signup_date) AS year, COUNT(*) FROM customers GROUP BY 1 ORDER BY 1;
Signups per year.
2. Monthly report
SELECT DATE_TRUNC('month', order_date)::date AS month, COUNT(*) FROM orders GROUP BY 1 ORDER BY 1;Orders per month.
3. Date difference
SELECT first_name, DATE '2026-01-01' - hire_date AS days FROM employees;
Days since hire.
Common mistakes
- Grouping by EXTRACT(MONTH ...) alone, which mixes January 2024 with January 2025. Use DATE_TRUNC.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
For 2025, return each month (as the first day of the month, a date) and the number of orders placed in it.
FAQ
How do I get today's date?
CURRENT_DATE for a date, NOW() for a timestamp.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.