TO_DATE or a date cast converts a text literal into a PostgreSQL date value.
PostgreSQL converts text to a DATE value with the TO_DATE(format_text, format_mask) function or a direct cast (::date). Choose TO_DATE when the input format is not ISO-8601.
Call TO_DATE(text, text)
when the source string is not in the default YYYY-MM-DD format. The first argument is the literal, the second argument is the format mask that tells PostgreSQL how to parse it.
Use CAST(text AS DATE)
or text::date
if the string already follows ISO-8601 (e.g., 2024-01-15). PostgreSQL parses this without an explicit mask.
The function signature is TO_DATE(string text, format text) RETURNS date
. The format mask uses the same template patterns as TO_CHAR
(e.g., YYYY, MM, DD, HH24).
TO_DATE
ignores time components. If you need both date and time, switch to TO_TIMESTAMP
or cast to timestamp with time zone
.
SELECT TO_DATE('03/15/2024', 'MM/DD/YYYY');
→ 2024-03-15
SELECT TO_DATE('15-Mar-2024', 'DD-Mon-YYYY');
→ 2024-03-15
SELECT '2024-03-15'::date;
→ 2024-03-15
Always supply an explicit format mask when the source string is not ISO-8601. Validate input with a regular expression in application code before sending it to the database.
PostgreSQL treats a two-digit year as 2000-2099. Provide the full four-digit year or use to_date('04', 'YY')
intentionally.
Use UPDATE
with TO_DATE
and create a new date column or replace the old text column: UPDATE orders SET order_date = TO_DATE(order_date_txt, 'DD/MM/YYYY');
Yes. Define the destination column as DATE
. PostgreSQL will attempt to cast each field during COPY. Provide the correct DATESTYLE
or preprocess data.
No. TO_DATE ignores hours and minutes. Use TO_TIMESTAMP for full datetime parsing.
TO_DATE returns an error. Wrap the call in a PL/pgSQL block with exception handling or validate input beforehand.
TO_DATE is written in C and is fast, but vectorized preprocessing in ETL tools or COPY with correct column types is usually faster.