Working with dates
Count the days between two dates, or group loans by month.
JULIANDAY turns a date into a day number; STRFTIME picks out parts like the month.
Count the loans in each month, with the month written like 2026-03: columns month and loans.
| loan_id | book_id | member_id | loan_date | returned |
|---|---|---|---|---|
| 1 | 1 | 102 | 2026-01-02 | 2026-01-22 |
| 2 | 3 | 101 | 2026-02-10 | 2026-02-17 |
| 3 | 10 | 106 | 2026-03-05 | 2026-03-21 |
| 4 | 8 | 101 | 2026-04-07 | 2026-04-28 |
| 5 | 6 | 102 | 2026-05-20 | 2026-06-03 |
| 6 | 4 | 104 | 2026-06-22 | 2026-06-29 |
| 7 | 4 | 106 | 2026-08-02 | 2026-08-20 |
| 8 | 7 | 104 | 2026-08-11 | 2026-09-01 |
| 9 | 2 | 104 | 2026-09-09 | NULL |
| 10 | 5 | 105 | 2026-09-15 | NULL |
| 11 | 3 | 106 | 2026-10-28 | NULL |
Run your query to see the result table.
Press the green Run button or Ctrl+Enter.
How JULIANDAY, STRFTIME works
How does SQLite store dates?
As text in the form
2026-03-08. Year first means they sort, compare and filter correctly:WHERE loan_date >= '2026-03-01'works.How do I count days between dates?
julianday(returned) - julianday(loan_date)julianday turns a date into a day number, like an Excel date serial, so subtracting gives days.
How do I pick out the year or month?
strftime('%Y', loan_date)gives the year,'%m'the month and'%Y-%m'both.date('now')is today, anddate(loan_date, '+21 days')adds days.Is this the same in every database?
No, dates are where databases differ most. The tables below show the main ones.
How is this like Excel?
julianday is like Excel's date serials (
=C2-B2for days), and strftime is like=TEXT(B2, "yyyy-mm").
How other databases do it
The lessons run on SQLite. Most of SQL is the same everywhere; these are the places where this lesson's SQL differs.
| Database | How | Note |
|---|---|---|
| SQLite (these lessons) | julianday(returned) - julianday(loan_date) | SQLite has no date type: dates are text, and these functions read them. |
| PostgreSQL | returned - loan_date | With real date columns, subtracting gives days. |
| MySQL / MariaDB | DATEDIFF(returned, loan_date) | |
| SQL Server | DATEDIFF(day, loan_date, returned) | The earlier date comes first. |
| Oracle | returned - loan_date | With DATE columns, subtracting gives days. |
| Sybase ASE | DATEDIFF(day, loan_date, returned) |
| Database | How | Note |
|---|---|---|
| SQLite (these lessons) | strftime('%m', loan_date) | Gives text like '03'. |
| PostgreSQL | EXTRACT(MONTH FROM loan_date) | TO_CHAR(loan_date, 'YYYY-MM') for 2026-03. |
| MySQL / MariaDB | MONTH(loan_date) | DATE_FORMAT(loan_date, '%Y-%m') for 2026-03. |
| SQL Server | MONTH(loan_date) | FORMAT(loan_date, 'yyyy-MM') for 2026-03. |
| Oracle | EXTRACT(MONTH FROM loan_date) | TO_CHAR(loan_date, 'YYYY-MM') for 2026-03. |
| Sybase ASE | MONTH(loan_date) | Or DATEPART(month, loan_date). |
Know someone fighting with a spreadsheet? Send them this page.