SQL LAST_DAY function
Returns the last day of the month containing the input: billing periods, month-end cutoffs, expiry dates. Leap years are handled for you.
- Returns
date- In this category
- 11 of 121
語法
LAST_DAY(d) -- MySQL, Oracle
EOMONTH(d [, months]) -- SQL Server
Each block is a separate form. The support table and the examples show which engine takes which.
引擎支援
| 引擎 | Support | 備註 |
|---|---|---|
| SQL Server | Different name or syntax | EOMONTH(d) since 2012, with an optional month offset |
| PostgreSQL | Not built in | no LAST_DAY; (date_trunc('month', d) + interval '1 month - 1 day')::date |
| MySQL | 是 | Supported under this name. |
| SQLite | Not built in | date(d, 'start of month', '+1 month', '-1 day') |
| Oracle | 是 | Supported under this name. |
範例
MySQL
SELECT LAST_DAY(order_date) AS cutoff FROM orders;
SQL Server
SELECT EOMONTH(order_date) AS cutoff FROM orders;
PostgreSQL
SELECT (date_trunc('month', order_date) + interval '1 month - 1 day')::date AS cutoff
FROM orders;
小知識
- EOMONTH takes a month offset: EOMONTH(d, -1) is the end of the previous month.
- The PostgreSQL idiom needs the cast: (date_trunc('month', d) + interval '1 month - 1 day')::date, or the result is a timestamp.
- Oracle's LAST_DAY keeps the time of day: LAST_DAY of 2026-02-10 13:00 is 2026-02-28 13:00. TRUNC it before comparing.
- WHERE ts <= LAST_DAY(d) misses everything after midnight on the last day when ts is a timestamp. Use ts < the first day of the next month instead.
- In SQLite, the modifier order matters: 'start of month' must come before '+1 month'. Written the other way, January 31 plus a month overflows to March 3 and the result is February 28.
Questions about LAST_DAY / EOMONTH
What is the PostgreSQL equivalent of LAST_DAY?
There is none; the idiom is (date_trunc('month', d) + interval '1 month - 1 day')::date. Wrap it in an IMMUTABLE SQL function if you use it everywhere.
Does EOMONTH handle leap years?
Yes. EOMONTH('2028-02-10') is 2028-02-29, and the other engines' versions get leap years right too.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Get the last day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Get the first and last day of the month in SQL Snippet
- Get the first and last day of the week in SQL Snippet
- Get the first and last day of the year in SQL Snippet
- Get the same day in the previous month in SQL Snippet
- Get the number of days in a month in SQL Snippet
Cheat sheets for the engines that have it: SQL Server, MySQL, 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.