SQL DATE_FORMAT bucketing
Formatting the day away with DATE_FORMAT is MySQL's idiom for month and day buckets, at the cost of returning text.
- カテゴリ
- Dates & times
- Returns
varchar- In this category
- 90 of 121
構文
DATE_FORMAT(date, '%Y-%m-01')
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | Different name or syntax | FORMAT(d, 'yyyy-MM-01') or DATETRUNC |
| PostgreSQL | Different name or syntax | to_char(d, 'YYYY-MM-01') or date_trunc |
| MySQL | はい | Supported under this name. |
| SQLite | Different name or syntax | strftime('%Y-%m-01', d) |
| Oracle | Different name or syntax | TRUNC(d, 'MM') keeps it a date |
例
MySQL
SELECT DATE_FORMAT(order_date, '%Y-%m') AS month, SUM(total) FROM orders GROUP BY month;
MySQL
SELECT DATE_FORMAT(order_date, '%Y-%m-01') AS month_start FROM orders;
SQLite
SELECT strftime('%Y-%m', order_date) AS month FROM orders;
知っておくと便利なこと
- The output is a string: GROUP BY DATE_FORMAT(d, '%Y-%m') sorts lexicographically (fine for ISO), but comparisons against dates fail; wrap with STR_TO_DATE or use the column range.
- Index use dies when you wrap the column in the WHERE clause; keep predicates raw (d >= '2026-08-01') and bucket only in SELECT/GROUP BY.
- Oracle's TRUNC(d, 'MM') and PostgreSQL's date_trunc return real dates, so the bucket still compares and joins as a date.
Questions about DATE_FORMAT bucketing
Why '%Y-%m-01' instead of '%Y-%m'?
Both group identically; the '-01' form produces a value you can feed to STR_TO_DATE or CAST back to a real date, which makes joins to a dates table possible.
Is DATE_FORMAT bucketing index-friendly?
As a WHERE predicate, never. Filter with d >= start AND d < end and use DATE_FORMAT only for output.
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.