// SQL snippet

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.

Main statement
SQL Server
Couvre également
PostgreSQL MySQL Oracle

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.

SQL Server
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;

Fonctionnement

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

PostgreSQL
SELECT
    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

MySQL
SELECT
    DATE_SUB(d, INTERVAL DAY(d) - 1 DAY) AS month_start,
    LAST_DAY(d) AS month_end
FROM (SELECT CURDATE() AS d) x;

Oracle

Oracle
SELECT
    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

// snippets are better with a schema brain

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.