Date Functions
Dates are usually stored as text in YYYY-MM-DD form so they sort correctly. Databases offer functions to extract parts, add time and measure the difference between two dates. The names differ a lot between systems.
Example
SELECT name, joined, strftime('%Y', joined) AS year, strftime('%m', joined) AS month
FROM students
WHERE id <= 2;Result
name | joined | year | month Ada | 2026-01-10 | 2026 | 01 Kofi | 2026-01-22 | 2026 | 01
Example
SELECT name, date(joined, '+30 days') AS trial_ends
FROM students
WHERE id = 1;Result
name | trial_ends Ada | 2026-02-09
Example
SELECT CAST(julianday('2026-03-01') - julianday('2026-01-10') AS INTEGER) AS days_between;Result
days_between 50
- The examples use SQLite functions. In MySQL use YEAR(), DATE_ADD() and DATEDIFF(). In PostgreSQL use EXTRACT() and date arithmetic. SQL Server uses DATEPART(), DATEADD() and DATEDIFF().
Exercise
Which format sorts dates correctly?
Store dates as -MM-DD
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.