// dialect comparison

Get the last day of the month in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

Three engines have a named function; PostgreSQL and SQLite make you derive it.

Filed under Types & casting

The verdict

SQL Server, MySQL and Oracle all have a named function. In PostgreSQL you compose truncate plus an interval, and in SQLite a modifier chain, which is verbose but combines with every other modifier.

Where they differ

The last day of a month depends on the month: 28, 29, 30 or 31. SQL Server, MySQL and Oracle ship a dedicated function; PostgreSQL and SQLite compose one.

How each engine writes it

SQL Server

SELECT EOMONTH(GETDATE());

EOMONTH (2012+) returns a DATE and takes an optional month offset: EOMONTH(GETDATE(), 1) is next month's last day.

PostgreSQL

SELECT (DATE_TRUNC('month', NOW()) + INTERVAL '1 month - 1 day')::DATE;

Truncate, step one month forward, one day back; the composed interval '1 month - 1 day' is a single literal with two fields.

MySQL

SELECT LAST_DAY(CURDATE());

Dedicated LAST_DAY function, returns a DATE, and gracefully returns NULL for invalid input.

SQLite

SELECT DATE('now', 'start of month', '+1 month', '-1 day');

Chained modifiers read like a sentence: start of this month, forward one, back one day.

Oracle

SELECT LAST_DAY(SYSDATE) FROM dual;

Dedicated LAST_DAY, keeps the time-of-day of the input, and handles leap years correctly.

Questions that come up

How do I get the number of days in the month?

Take the last day's day-of-month: DAY(EOMONTH(d)) in SQL Server, EXTRACT(DAY FROM LAST_DAY(d)) in MySQL and Oracle, EXTRACT(DAY FROM DATE_TRUNC('month', d) + INTERVAL '1 month - 1 day') in PostgreSQL, and strftime('%d', DATE(d, 'start of month', '+1 month', '-1 day')) in SQLite.

Does EOMONTH keep the time part?

No, it returns a pure DATE. MySQL's LAST_DAY returns a DATE too, while Oracle's returns a DATE that keeps the input's time of day.

How do I test whether a date is the month's last day?

Compare directly: d = EOMONTH(d) in SQL Server, d = LAST_DAY(d) in MySQL and Oracle, d = (DATE_TRUNC('month', d) + INTERVAL '1 month - 1 day')::DATE in PostgreSQL.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.