// dialect comparison

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

A staple of reporting SQL, computed five different ways.

Filed under Types & casting

The verdict

PostgreSQL's DATE_TRUNC, Oracle's TRUNC and SQL Server 2022's DATETRUNC take a unit argument, and SQLite's modifier chains with others. MySQL, and SQL Server before 2022, make you assemble the date by hand.

Where they differ

Rounding a date down to the first of its month is bread-and-butter reporting SQL. PostgreSQL, Oracle and SQL Server 2022+ have a truncation function; MySQL rebuilds the date and SQLite uses a modifier.

How each engine writes it

SQL Server

SELECT DATETRUNC(month, GETDATE()),
  DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1);

DATETRUNC (SQL Server 2022+) truncates to any datepart and keeps the input's type, datetime here. On older versions rebuild the date with DATEFROMPARTS, which returns a DATE.

PostgreSQL

SELECT DATE_TRUNC('month', NOW())::DATE;

DATE_TRUNC takes the unit as text ('day', 'month', 'year') and returns a timestamp; cast to DATE for a pure date.

MySQL

SELECT DATE_FORMAT(CURDATE(), '%Y-%m-01');

Formats the day as literal 01, returning text; wrap in CAST(... AS DATE) if you need a date type.

SQLite

SELECT DATE('now', 'start of month');

The start of month modifier does exactly this and chains with others, e.g. DATE('now', 'start of month', '-1 day').

Oracle

SELECT TRUNC(SYSDATE, 'MM') FROM dual;

TRUNC with 'MM' truncates to the month; 'DD' (the default) truncates the time, 'YYYY' to the year.

Questions that come up

Which form should I use on SQL Server?

DATETRUNC(month, d) on 2022 and later. Before that, DATEFROMPARTS(YEAR(d), MONTH(d), 1) reads clearly; DATEADD(DAY, 1, EOMONTH(d, -1)) also works but reads backwards.

How do I get the first day of last month?

Chain one step back: PostgreSQL DATE_TRUNC('month', NOW()) - INTERVAL '1 month'; SQLite DATE('now', 'start of month', '-1 month'); Oracle TRUNC(ADD_MONTHS(SYSDATE, -1), 'MM').

Does this preserve the time part?

No. TRUNC, DATE_TRUNC and DATETRUNC set the time to midnight, DATEFROMPARTS returns a DATE with no time part, and MySQL's DATE_FORMAT returns the text '2026-11-01', which becomes midnight once cast to DATETIME.

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.