SQL MONTH function
Returns the month number from a date, the grouping key for monthly reporting, before you reach for TO_CHAR or DATE_FORMAT for names.
- Categoría
- Dates & times
- Returns
integer- In this category
- 38 of 121
Sintaxis
MONTH(d)
EXTRACT(month FROM d)
strftime('%m', d) -- SQLite, zero-padded text
Each block is a separate form. The support table and the examples show which engine takes which.
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Different name or syntax | EXTRACT(month FROM d) |
| MySQL | Sí | Supported under this name. |
| SQLite | Different name or syntax | strftime('%m', d) returns '01'-'12' text |
| Oracle | Different name or syntax | EXTRACT(month FROM d); there is no MONTH() function |
Ejemplos
PostgreSQL
SELECT EXTRACT(year FROM created_at) AS yr,
EXTRACT(month FROM created_at) AS mon,
COUNT(*) FROM orders GROUP BY 1, 2;
SQL Server
SELECT YEAR(created_at) AS yr, MONTH(created_at) AS mon, COUNT(*) FROM orders GROUP BY YEAR(created_at), MONTH(created_at);
MySQL
SELECT MONTH(created_at) AS mon FROM orders;
Conviene saberlo
- SQLite's zero-padded text sorts fine but compares as text: strftime('%m', d) = 1 is never true. CAST to INTEGER first.
- Month numbers are calendar months: grouping by MONTH on data spanning years mixes Januaries of 2023 and 2024 into one bucket; group by year and month together.
- Oracle has no MONTH() function; EXTRACT(month FROM d) works on DATE and TIMESTAMP, and TO_CHAR(d, 'MM') returns the zero-padded text form.
Questions about MONTH
How do I get the month name instead?
DATENAME(month, d) on SQL Server, MONTHNAME(d) on MySQL, TO_CHAR(d, 'FMMonth') on PostgreSQL and Oracle; SQLite has no month-name format.
Why do my monthly totals look too big?
You grouped by month without year, so Januarys from every year collapse together. Group by the year-month pair or a date-truncated column.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Count rows bucketed by time period Snippet
- Map a calendar date to a fiscal year in SQL Snippet
- Cumulative total by month Snippet
- Get the first and last day of the month in SQL Snippet
- Get the first and last day of the quarter in SQL Snippet
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.