SQLite date functions: handling TEXT dates properly
SQLite has no DATE type. Dates are usually TEXT and are handled with string and date functions. Once the format is right, sorting, comparing and grouping all follow.
Format is everything
SQLite's date functions understand 'YYYY-MM-DD' and 'YYYY-MM-DD HH:MM:SS'. In that format lexical order equals chronological order, so BETWEEN works for ranges without conversion.
Other formats need converting first: '2026/09/01' becomes strftime('%Y-%m-%d', replace(order_date, '/', '-')). Cleaning at load time is usually simpler.
SELECT order_date, strftime('%Y-%m', order_date) AS month
FROM orders
LIMIT 5;
Grouping by month and weekday
strftime('%Y-%m', col) creates a month key, and %w gives the weekday with 0 for Sunday. Group by the month string and order by it to get a readable trend.
SELECT strftime('%Y-%m', order_date) AS month,
COUNT(*) AS orders,
ROUND(SUM(revenue), 0) AS revenue
FROM orders
GROUP BY month
ORDER BY month;
Elapsed days and period comparisons
julianday('2026-09-30') - julianday(started_on) gives a difference in days, useful for age or for finding subscriptions older than 90 days.
date('now') is today in UTC. For Korean local time add the offset: date('now', '+9 hours'). Ignoring that shifts the date near midnight.
SELECT sub_id, started_on,
CAST(julianday('2026-09-30') - julianday(started_on) AS INTEGER) AS days
FROM subscriptions
WHERE status = 'active'
ORDER BY days DESC
LIMIT 5;
Common traps
Dates stored as integers (20260901) or mixed timezones compare incorrectly. Do not compute month ends by hand either: date('2026-01-31', '+1 month') applies SQLite's own month arithmetic, so check the result rather than assuming it lands on the last day of February.
| Goal | Expression | Note |
|---|---|---|
| year-month | strftime('%Y-%m', d) | monthly grouping |
| days between | julianday(a) - julianday(b) | a real number; CAST to integer |
| today (UTC) | date('now') | Korea: '+9 hours' |
| month end | date(d, 'start of month', '+1 month', '-1 day') | verify the arithmetic |
Handling month boundaries
A missing month in a monthly report means no rows that month. To show zero, build a calendar table and LEFT JOIN it: SQL will not invent months the data does not contain.
Questions
Can I strip the time from a timestamp?
Yes. date(col) or strftime('%Y-%m-%d', col) returns just the date part.
String comparison or date functions?
With ISO dates, string comparison is faster and can use an index. Convert only when formats are mixed.
Sources
Every query in this guide runs against the built-in sample data.
Open the lab