SQL STRFTIME bucketing
strftime is SQLite's main bucketing tool: drop precision by formatting, then group on the resulting text.
- Categoría
- Dates & times
- Returns
text- In this category
- 91 of 121
Sintaxis
strftime('%Y-%m', t)
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Different name or syntax | FORMAT(d, 'yyyy-MM') or DATETRUNC |
| PostgreSQL | Different name or syntax | to_char(d, 'YYYY-MM') or date_trunc |
| MySQL | Different name or syntax | DATE_FORMAT(d, '%Y-%m') |
| SQLite | Sí | Supported under this name. |
| Oracle | Different name or syntax | TO_CHAR(d, 'YYYY-MM') |
Ejemplos
SQLite
SELECT strftime('%Y-%m', created_at) AS month, COUNT(*) FROM events GROUP BY month;
SQLite
SELECT strftime('%Y-%W', created_at) AS week FROM events;
SQLite
SELECT date(created_at, 'start of month') AS month_start FROM events;
Conviene saberlo
- strftime has no month or weekday names: %m and %w are numbers only. Labels like 'Aug' or 'Monday' need a CASE over %m or %w.
- Week buckets: %W (Monday-first) runs 00-53, with days before the year's first Monday in week 00. SQLite 3.46 added %U (Sunday-first, same week-00 rule), ISO %V and its year %G; older builds need date arithmetic for Sunday or ISO weeks.
- For a date-typed month bucket, date(t, 'start of month') beats strftime: it returns a date string you can compare with other dates directly.
Questions about STRFTIME bucketing
How do I bucket by quarter in SQLite?
Compute it: CAST((strftime('%m', t) - 1) / 3 + 1 AS INTEGER) gives 1-4, or build the quarter start with 'start of month' plus month arithmetic.
Why does '%Y-%W' show week 00?
%W puts days before the year's first Monday in week 00, so 2026-01-01 is week 00. ISO 8601 assigns those days to week 1 or to the previous year's last week; use '%G-%V' (SQLite 3.46+) for ISO keys.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.