SQLite vs PostgreSQL date functions
Dates as text versus real date types: a side-by-side of strftime, julianday, date_trunc and intervals, with examples that run on the course database.
SQLite vs PostgreSQL date functions
SQLite stores dates as text; PostgreSQL has real date types. Both answer the same questions, but the functions are different enough to waste an afternoon. Here is the side-by-side you can keep.
How each one stores a date
- SQLite has no dedicated date type. ISO strings (
YYYY-MM-DD) or Unix timestamps are stored asTEXT/INTEGER, and the date functions parse them on demand. - PostgreSQL has
date,timestampandtimestamptz. Arithmetic and time zones are part of the type system.
In SQLite, store dates as ISO text. It sorts correctly and every function below understands it.
Extract a year or a month
SQLite:
SELECT invoice_date, strftime('%Y', invoice_date) AS year
FROM invoices
ORDER BY invoice_date
LIMIT 5;
PostgreSQL:
SELECT invoice_date, EXTRACT(YEAR FROM invoice_date) AS year
FROM invoices
ORDER BY invoice_date
LIMIT 5;
strftime uses format strings (%Y, %m, %d); PostgreSQL uses EXTRACT or date_part.
Add days
SQLite:
SELECT date('2024-03-05', '+30 days') AS due_date;
PostgreSQL:
SELECT DATE '2024-03-05' + INTERVAL '30 days' AS due_date;
SQLite passes the modifier as text. PostgreSQL adds an INTERVAL to a date.
Measure the gap between two dates
SQLite:
SELECT julianday('2024-03-05') - julianday('2024-01-12') AS days;
PostgreSQL:
SELECT DATE '2024-03-05' - DATE '2024-01-12' AS days;
julianday() returns a fractional day number, so subtracting two of them gives days. In PostgreSQL, subtracting dates already returns an integer.
Group by month
SQLite:
SELECT strftime('%Y-%m', invoice_date) AS month, COUNT(*) AS invoices
FROM invoices
GROUP BY month
ORDER BY month;
PostgreSQL:
SELECT date_trunc('month', invoice_date) AS month, COUNT(*) AS invoices
FROM invoices
GROUP BY month
ORDER BY month;
This is the query you will write most often in reporting: collapse dates to a month, then aggregate.
Rules that save time
| Task | SQLite | PostgreSQL |
|---|---|---|
| Current time | CURRENT_TIMESTAMP | now() |
| Parse a date | date('2024-03-05') | DATE '2024-03-05' |
| Add an interval | date(x, '+30 days') | x + INTERVAL '30 days' |
| Truncate to month | strftime('%Y-%m', x) | date_trunc('month', x) |
| Difference in days | julianday(a) - julianday(b) | a - b |
| Time zones | not built in | timestamptz |
Keep exploring: the numbers and dates chapter covers rounding, math and date functions with seven graded exercises on this same data.