In Microsoft SQL Server, the DATETRUNC function (available since SQL Server 2022) truncates a datetime value to the specified unit.
In PostgreSQL, you can use the DATE_TRUNC function but note that the corresponding unit can be different and specified as a string literal.
SQL Server:
-- Truncate to the start of month SELECT DATETRUNC(month, '2025-04-05'); /* 2025-04-01 00:00:00.0000000 */
PostgreSQL:
-- Truncate to the start of month SELECT DATE_TRUNC('month', '2025-04-05'::TIMESTAMP); /* 2025-04-01 00:00:00 */
You can map SQL Server DATETRUNC units to the corresponding DATE_TRUNC units in PostgreSQL as follows:
SQL Server | PostgreSQL | ||
yy | year | DATETRUNC(yy, GETDATE()) | DATE_TRUNC('year', NOW()) |
quarter | DATETRUNC(qq, GETDATE()) | DATE_TRUNC('quarter', NOW()) | |
mm | month | DATETRUNC(mm, GETDATE()) | DATE_TRUNC('month', NOW()) |
wk | week | DATETRUNC(wk, GETDATE()) | DATE_TRUNC('week', NOW()) |
dd | day | DATETRUNC(dd, GETDATE()) | DATE_TRUNC('day', NOW()) |
hh | hour | DATETRUNC(hh, GETDATE()) | DATE_TRUNC('hour', NOW()) |
mi | minute | DATETRUNC(mi, GETDATE()) | DATE_TRUNC('minute', NOW()) |
ss | second | DATETRUNC(ss, GETDATE()) | DATE_TRUNC('second', NOW()) |
ms | millisecond | DATETRUNC(ms, GETDATE()) | DATE_TRUNC('milliseconds', NOW()) |
For more information, see SQL Server to PostgreSQL Migration.