// SQL snippet

Get the number of days in a month in SQL

Prorated billing and daily-rate math need the real length of each month, including leap-year February.

Main statement
SQL Server
Also covers
PostgreSQL MySQL Oracle

The task

EOMONTH returns the month's last date; DAY of that is the length.

The snippet

Written for SQL Server. Versions for PostgreSQL, MySQL and Oracle are under Variations.

SQL Server
SELECT DAY(EOMONTH(d)) AS days_in_month
FROM (SELECT CAST('2026-02-01' AS DATE) AS d) x;

How it works

EOMONTH(d) lands on the final calendar day of d's month, so DAY() of it is the month's length. This sidesteps hand-rolled leap-year CASE logic entirely: the engine owns the calendar.

Variations

MySQL

MySQL
SELECT DAY(LAST_DAY(d)) AS days_in_month
FROM (SELECT CURDATE() AS d) x;

PostgreSQL

PostgreSQL
SELECT EXTRACT(DAY FROM (date_trunc('month', d) + interval '1 month - 1 day'))::int AS days_in_month
FROM (SELECT DATE '2026-02-01' AS d) x;

Oracle

Oracle
SELECT EXTRACT(DAY FROM LAST_DAY(d)) AS days_in_month
FROM (SELECT DATE '2026-02-01' AS d FROM dual);

Questions that come up

Can I get days remaining in the month?

Yes: subtract today from the month end. On SQL Server, DATEDIFF(DAY, GETDATE(), EOMONTH(GETDATE())); on PostgreSQL, (date_trunc('month', CURRENT_DATE) + interval '1 month - 1 day' - CURRENT_DATE).

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.