PostgreSQL to_date Function: Usage and Formatting Guide
In this article
The to_date function in PostgreSQL converts a text string into a date data type based on a specific format mask. It is used primarily when importing data from CSVs or external APIs where dates are stored as strings in non-standard formats, allowing you to transform them into actual DATE objects for sorting, filtering, and date arithmetic. To use it, you provide two arguments: the string to be converted and the template that describes how that string is structured.
What You'll Need
- A running PostgreSQL database instance.
- Access to a SQL editor (such as pgAdmin, psql, or DBeaver).
- A text string containing date information (e.g., '2023-12-25' or '25/12/2023').
- Knowledge of the specific format the source date is currently using.
Step-by-Step
- Identify the source string format. Before writing the query, examine your raw data. Determine if the month is represented by a name (January), a three-letter abbreviation (Jan), or a number (01). Note the order of elements: is it Year-Month-Day (ISO), Day-Month-Year (European), or Month-Day-Year (US)?
-
Select the appropriate format tokens. PostgreSQL uses specific template patterns to interpret strings. Common tokens include:
YYYY: 4-digit year.YY: Last 2 digits of the year.MM: Month number (01-12).Month: Full capitalized month name.Mon: Abbreviated capitalized month name.DD: Day of the month (01-31).
-
Construct the basic function call. The syntax is
to_date('text_value', 'format_mask'). For example, if your date is '2025-05-15', your query would beSELECT to_date('2025-05-15', 'YYYY-MM-DD');. -
Handle delimiters correctly. The format mask must exactly match the characters used to separate the date parts in the string. If your date uses slashes (15/05/2025), the mask must use slashes (
'DD/MM/YYYY'). If it uses spaces or dashes, the mask must reflect that precisely. -
Execute the conversion in a SELECT statement. Test your logic on a single value before applying it to a whole table. Run a query like
SELECT to_date('12-Oct-2024', 'DD-Mon-YYYY');to ensure the output is a valid date type. -
Apply the function to a table column. Once the format is verified, use the function in a query against your data. For example:
SELECT to_date(created_at_string, 'MM/DD/YYYY') FROM users;. This converts the string column into a date on the fly. -
Persist the change (Optional). If you want to permanently change a column from text to date, use the
ALTER TABLEcommand with aUSINGclause:ALTER TABLE users ALTER COLUMN created_at_string TYPE DATE USING to_date(created_at_string, 'MM/DD/YYYY');.
Common Mistakes
One of the most frequent errors is mismatching the format mask with the input string. If the input string is '2023/01/01' but the mask is 'YYYY-MM-DD', PostgreSQL may throw an error or produce an unexpected result because the dashes do not match the slashes. Always ensure every non-numeric character in the string is mirrored in the mask.
Another common mistake is confusing to_date with to_timestamp. The to_date function returns a DATE type, which contains only the year, month, and day. If your input string contains hours, minutes, or seconds and you need to preserve them, to_date will truncate that information. In those cases, to_timestamp must be used instead to return a TIMESTAMP WITH TIME ZONE.
Case sensitivity in month names can also cause confusion. While PostgreSQL is generally flexible with Mon and Month, using the wrong case in the mask (like month instead of Month) can sometimes affect the capitalization of the output if you were converting a date back to a string, though for to_date (string to date), the primary concern is that the pattern matches the structure of the input.
Lastly, users often forget that to_date does not perform strict validation for all logical dates. In some versions and configurations, it may attempt to "roll over" invalid dates. For instance, providing a day of 32 might result in the date jumping to the 1st of the next month rather than failing immediately, which can lead to silent data corruption if the source data is dirty.
Tips
When dealing with large datasets, avoid using to_date in the WHERE clause of a query on a column that isn't already a date. For example, WHERE to_date(text_col, 'YYYY-MM-DD') = '2023-01-01' forces the database to run the function on every single row (a full table scan), which kills performance. Instead, convert your search term to a string or, better yet, convert the column to a proper DATE type permanently.
Use the CAST operator or the ::date shorthand when your strings are already in the ISO 8601 format ('YYYY-MM-DD'). If the string is already standard, '2023-01-01'::date is much faster and cleaner than calling to_date('2023-01-01', 'YYYY-MM-DD').
If you are importing data from a region with ambiguous dates (like 01/02/2023, which could be January 2nd or February 1st), always verify the source locale. There is no "auto-detect" for date formats in to_date; you must be explicit about whether MM or DD comes first.
For complex transformations, combine to_date with COALESCE. If some rows have empty strings or NULLs, COALESCE(to_date(col, 'YYYY-MM-DD'), '1900-01-01'::date) can provide a default fallback value to prevent your application from crashing on null date values.
Troubleshooting
If you encounter the error invalid value for "date", the first step is to check for hidden characters. Often, strings imported from Excel or CSVs contain leading or trailing spaces. Use the TRIM() function to clean the input: to_date(TRIM(column_name), 'YYYY-MM-DD').
If the function returns a date that is logically incorrect (e.g., the month and day are swapped), review your format mask. Double-check if you used MM-DD when the data was actually DD-MM. This is a silent failure where the query runs successfully but the data is wrong.
If you receive a syntax error, ensure that both the date string and the format mask are enclosed in single quotes. Double quotes are for identifiers (like table or column names) and will cause the query to fail if used for the format mask.
When dealing with dates that include the word "th", "st", or "rd" (e.g., "October 12th, 2023"), to_date will struggle because there is no token for ordinal suffixes. In this case, you must use regexp_replace to remove the suffixes before passing the string to to_date.
Frequently Asked Questions
Can to_date handle timestamps with time?
No, to_date only extracts the date portion. If you need the time, use to_timestamp.
What happens if the input string is empty?
If the input is NULL, the result is NULL. If the input is an empty string, it may result in an error depending on the format mask provided.
Is the format mask case-sensitive?
For to_date, the tokens like YYYY and MM are not case-sensitive, but the resulting output of date-to-string functions (like to_char) is influenced by the case of the mask.
Can I use to_date for dates in different languages?
to_date relies on the lc_time setting of the database. If you are parsing month names in French or Spanish, the database locale must be set to match that language for the Month token to work.
Does to_date work with the DATE type?
No, to_date is specifically for converting text to date. If the value is already a date, you should use to_char to format it as text or simply use it as is.