// dates & times reference

SQL STRFTIME bucketing

strftime is SQLite's main bucketing tool: drop precision by formatting, then group on the resulting text.

类别
Dates & times
Returns
text
In this category
91 of 121

语法

strftime('%Y-%m', t)

引擎支持

引擎Support备注
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 是 Supported under this name.
Oracle Different name or syntax TO_CHAR(d, 'YYYY-MM')

示例

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;

值得了解

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.