// dates & times reference

SQL DATE() function

Returns the date component with the time removed, the standard form for grouping timestamps by day and for date-only joins.

Categoria
Dates & times
Returns
date
In this category
49 of 121

Sintaxe

DATE(ts)  -- MySQL, SQLite
CAST(ts AS date)  -- SQL Server
ts::date  -- PostgreSQL
TRUNC(d)  -- Oracle

Each block is a separate form. The support table and the examples show which engine takes which.

Suporte a mecanismos

MotorSupportNotas
SQL Server Different name or syntax CAST(ts AS date); no DATE() function
PostgreSQL Sim date(ts) works as function-style cast syntax; ts::date is the usual spelling
MySQL Sim Supported under this name.
SQLite Sim Supported under this name.
Oracle Different name or syntax TRUNC(d); Oracle's DATE type already holds a time

Exemplos

MySQL

SELECT DATE(created_at) AS day, COUNT(*) FROM orders GROUP BY day;

PostgreSQL

SELECT created_at::date AS day, COUNT(*) FROM orders GROUP BY 1;

SQL Server

SELECT CAST(created_at AS date) AS day, COUNT(*) FROM orders GROUP BY CAST(created_at AS date);

Oracle

SELECT TRUNC(created_at) AS day, COUNT(*) FROM orders GROUP BY TRUNC(created_at);

Bom saber

  • Oracle's DATE type has a time inside: TRUNC(d) is not cosmetic, it is what makes equality comparisons hit midnight matches.
  • On a timestamptz, PostgreSQL's ::date uses the session time zone, so the same instant can fall on different dates in different sessions.
  • Filtering on DATE(created_at) = '2024-01-15' blocks a plain index on most engines; created_at >= '2024-01-15' AND created_at < '2024-01-16' keeps it. SQL Server is an exception: CAST(col AS date) stays seekable.

Questions about DATE()

Is DATE() the same as CAST AS date?

Same result, engine spelling differs. MySQL and SQLite call it DATE(); SQL Server casts; PostgreSQL casts (date_trunc('day', ts) keeps the timestamp type instead). SQLite's DATE() returns 'YYYY-MM-DD' text.

Why is my date-equality join missing rows?

The column still has a time: 2024-01-15 09:30 is not equal to 2024-01-15. Compare DATE(ts) = DATE(d2) or use half-open ranges.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.