SQL Date Functions
Date functions answer questions like “orders per month” and “days since signup”. This is the area where databases differ most, so each example notes the equivalents.
Updated December 1, 2026
Syntax
strftime('%Y-%m', date) -- format or extract parts
date(date, '+7 days') -- date arithmetic
julianday(end) - julianday(start) -- difference in days
Group by month
strftime formats a date. PostgreSQL uses DATE_TRUNC('month', d) or TO_CHAR, MySQL DATE_FORMAT, SQL Server FORMAT.
SELECT strftime('%Y-%m', signed_up) AS month, COUNT(*) AS signups
FROM signups
GROUP BY month
ORDER BY month;
| month | signups |
|---|---|
| 2024-01 | 7 |
| 2024-02 | 1 |
Add days to a date
When does each order’s 30-day return window close? PostgreSQL writes d + INTERVAL '30 days', MySQL DATE_ADD(d, INTERVAL 30 DAY), SQL Server DATEADD(day, 30, d).
SELECT id, ordered_on, date(ordered_on, '+30 days') AS return_by
FROM orders
WHERE status = 'delivered';
| id | ordered_on | return_by |
|---|---|---|
| 1 | 2025-02-01 | 2025-03-03 |
| 2 | 2025-02-03 | 2025-03-05 |
| 3 | 2025-02-15 | 2025-03-17 |
| 6 | 2025-03-20 | 2025-04-19 |
| 7 | 2025-04-02 | 2025-05-02 |
Difference between dates
Years of service as of January 1, 2026. Elsewhere: DATE_PART or subtraction in PostgreSQL, DATEDIFF in MySQL and SQL Server.
SELECT name, hired,
ROUND((julianday('2026-01-01') - julianday(hired)) / 365.25, 1) AS years
FROM employees
ORDER BY years DESC;
| name | hired | years |
|---|---|---|
| Maya Chen | 2018-03-12 | 7.8 |
| Jack Miller | 2018-09-03 | 7.3 |
| Omar Haddad | 2019-07-01 | 6.5 |
| Diego Alvarez | 2019-11-11 | 6.1 |
| Lena Park | 2020-01-15 | 6 |
Common mistakes
- Storing dates in formats like
07/04/2024. Use ISOYYYY-MM-DD, which sorts and compares correctly. - Grouping by a full timestamp when you meant the day or month.
- Forgetting time zones when timestamps come from different places. Store UTC, convert for display.
Practice Date Functions interactively
Write real queries in your browser and get instant feedback in the lesson “Working with dates” (Unit 7). New learners can start free from the first lesson.
Frequently asked questions
How do I get today’s date in SQL?
date('now') in SQLite, CURRENT_DATE in PostgreSQL and MySQL, GETDATE() or CAST(GETDATE() AS date) in SQL Server.
How do I extract the year?
strftime('%Y', d) in SQLite; EXTRACT(YEAR FROM d) in PostgreSQL and MySQL; YEAR(d) in MySQL and SQL Server.