// dialect comparison

Truncate a date to day, month or year in SQL Server, PostgreSQL, MySQL, SQLite and Oracle

Grouping by month starts with truncation; MySQL and pre-2022 SQL Server make you build the result by hand.

Filed under Types & casting

The verdict

PostgreSQL, Oracle and SQL Server 2022+ take a unit argument. Elsewhere day truncation is easy and month or year truncation is assembly work, and that difference shapes every GROUP BY on a time bucket.

Where they differ

Truncation zeroes the sub-unit fields: truncate to month and you get the first of the month at midnight. It is the standard GROUP BY building block, and the engines split between one general function and hand-assembly.

How each engine writes it

SQL Server

SELECT DATETRUNC(month, GETDATE()), CAST(GETDATE() AS DATE);

DATETRUNC (2022+) takes year, quarter, month, week, day, hour and finer parts. Before 2022, day truncation is a CAST to DATE and month or year needs a DATEFROMPARTS(YEAR(d), MONTH(d), 1) rebuild.

PostgreSQL

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

One function for every unit: 'day', 'week' (Monday-start), 'month', 'quarter', 'year', plus finer ones like 'hour'.

MySQL

SELECT DATE(NOW());

DATE() truncates to day only; month and year are DATE_FORMAT(d, '%Y-%m-01') rebuilds, or DATE_FORMAT(d, '%Y-01-01') for years.

SQLite

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

Modifiers 'start of day', 'start of month', 'start of year' cover the common units; the result is TEXT in ISO form.

Oracle

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

TRUNC mirrors PostgreSQL's generality: 'DD' (day, the default), 'MM', 'YYYY', 'IW' (ISO week) and more.

Questions that come up

How do I group rows by month?

Group on the truncation: DATE_TRUNC('month', created_at) in PostgreSQL, TRUNC(created_at, 'MM') in Oracle, DATE_FORMAT(created_at, '%Y-%m') in MySQL, strftime('%Y-%m', created_at) in SQLite, and DATETRUNC(month, created_at) in SQL Server 2022+ (YEAR(created_at), MONTH(created_at) before that).

Does truncation hurt index use?

Yes. Wrapping the column in a function makes the predicate non-sargable. For range scans, compare created_at >= first-of-month AND < first-of-next-month instead of truncating the column.

What does 'week' truncate to?

In PostgreSQL, Monday. In Oracle, TRUNC(d, 'IW') is the ISO Monday, while 'WW' counts weeks from January 1, whatever weekday that is. SQL Server's DATETRUNC(week, d) follows SET DATEFIRST, which is Sunday under us_english.

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.