Get the first and last day of the month in SQL
Monthly reports and billing periods need clean month-start and month-end boundaries from any date.
The task
EOMONTH is purpose-built for month end; the first of the month comes from DATEFROMPARTS with day 1.
The snippet
Written for SQL Server. Versions for PostgreSQL, MySQL and Oracle are under Variations.
SELECT
DATEFROMPARTS(YEAR(d), MONTH(d), 1) AS month_start,
EOMONTH(d) AS month_end
FROM (SELECT CAST('2026-03-04' AS DATE) AS d) x;
So funktioniert es
DATEFROMPARTS rebuilds the date with day 1 to get the month start, and EOMONTH(d) returns the last day of d's month, leap years included. Both exist since SQL Server 2012 and avoid the old DATEADD/DAY arithmetic that is easy to get wrong.
Variations
PostgreSQL
PostgreSQLSELECT
date_trunc('month', d)::date AS month_start,
(date_trunc('month', d) + interval '1 month - 1 day')::date AS month_end
FROM (SELECT DATE '2026-03-04' AS d) x;
MySQL
MySQLSELECT
DATE_SUB(d, INTERVAL DAY(d) - 1 DAY) AS month_start,
LAST_DAY(d) AS month_end
FROM (SELECT CURDATE() AS d) x;
Oracle
OracleSELECT
TRUNC(d, 'MM') AS month_start,
LAST_DAY(d) AS month_end
FROM (SELECT DATE '2026-03-04' AS d FROM dual);
Questions that come up
How do I bucket a timestamp range by month?
Group by the month_start expression, or filter with ts >= month_start AND ts < next month's start. Do not filter a timestamp column with <= month_end: month_end is midnight at the start of the last day, so everything later that day is missed. Oracle's LAST_DAY also keeps the time part of its input.
Keep reading
Related on SQLly
- SQL LAST_DAY function Funktion
- SQL DATE_SUB function Funktion
- SQL DATEFROMPARTS function Funktion
- Get the last day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Get the first day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Get the first and last day of the year in SQL Snippet
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.