← SQL and databases

Dates in SQLite

Compare dates, pull out the year or month, count days.

Start this lesson

SQLite stores dates as text like '2024-03-21' (year-month-day). Because the biggest unit comes first, sorting and comparing this text puts dates in the right order, so BETWEEN and < just work. strftime pulls out parts of a date: strftime('%Y', d) is the year and strftime('%m', d) is the month, both as text. julianday(d) turns a date into a day number, so julianday(a) - julianday(b) is the number of days between them.

SELECT id, order_date FROM orders
WHERE strftime('%m', order_date) = '03';

Keeps orders from March. The month comes back as the text '03', so compare it with '03' in quotes.

A date like '3/21/2024' would NOT sort correctly as text, which is why databases use the YYYY-MM-DD format.

date(d, '+7 days') adds days to a date, and date('now') is today.