// dates & times reference

SQL TO_DATE function

Converts a text value into a real date using a format mask. The inverse of TO_CHAR, with the same per-engine format codes plus locale and ambiguity traps.

Catégorie
Dates & times
Returns
date
In this category
9 of 121

Syntaxe

TO_DATE('2026-08-01', 'YYYY-MM-DD')
STR_TO_DATE('2026-08-01', '%Y-%m-%d')

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

Prise en charge des moteurs

MoteurSupportNotes
SQL Server Different name or syntax CAST('2026-08-01' AS date) or TRY_CONVERT with style
PostgreSQL Oui Supported under this name.
MySQL Different name or syntax STR_TO_DATE(text, '%Y-%m-%d')
SQLite Not built in date(text) understands ISO 8601 only
Oracle Oui Supported under this name.

Exemples

PostgreSQL

SELECT TO_DATE('01/08/2026', 'DD/MM/YYYY') AS d;  -- 2026-08-01

MySQL

SELECT STR_TO_DATE('01/08/2026', '%d/%m/%Y') AS d;

SQL Server

SELECT TRY_CONVERT(date, '01/08/2026', 103) AS d;  -- British style

Oracle

SELECT TO_DATE('01/08/2026', 'DD/MM/YYYY') AS d FROM dual;

Bon à savoir

  • Oracle's TO_DATE without a mask falls back to NLS_DATE_FORMAT, so code that works in one session breaks in another. Always pass the mask. Oracle DATEs also keep the time: TO_DATE('2026-08-01 14:30', 'YYYY-MM-DD HH24:MI') stores 14:30.
  • Two-digit years and day/month order are locale traps: '03/04/2026' is March 4 or April 3 depending on settings. ISO 8601 (YYYY-MM-DD) avoids the guesswork, with one SQL Server exception: the old datetime type can read '2026-08-01' as year-day-month under some session languages, while date and datetime2 never do.
  • SQLite's date() accepts ISO 8601 strings only; anything else needs text surgery first.

Questions about TO_DATE / STR_TO_DATE

What happens if the text is not a valid date?

PostgreSQL and Oracle raise an error, which fails the whole query. SQL Server's TRY_CONVERT and TRY_CAST return NULL instead. MySQL's STR_TO_DATE returns NULL with a warning. Oracle 12.2+ accepts TO_DATE(s DEFAULT NULL ON CONVERSION ERROR, 'YYYY-MM-DD'), and PostgreSQL 16+ can test first with pg_input_is_valid(s, 'date').

Which date format should I always use?

ISO 8601, YYYY-MM-DD. All five engines parse it the same way, apart from SQL Server's legacy datetime type described above; for that type, '20260801' without dashes is always safe.

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.