STR_TO_DATE() converts a character string to a DATE, TIME, or DATETIME value using a format mask.
STR_TO_DATE() parses a text value according to a supplied format string and returns a DATE, TIME, or DATETIME. The function is ideal when raw data arrives as VARCHAR and you must store or filter by real date types.
Call STR_TO_DATE(string, format). MariaDB matches the format specifiers (e.g., %Y, %m, %d) to the string’s structure and returns a DATE. If the pattern or value is invalid, the result is NULL and the statement raises a warning.
Suppose Orders.order_date_raw
is VARCHAR(20) like ‘2024-06-15’. A nightly job can convert and store it in a proper DATE column so indexes and comparisons remain fast.
STR_TO_DATE(string
, format_mask
) → DATE | DATETIME | TIME
Common specifiers: %Y (4-digit year), %m (numeric month), %d (day), %H (24-hour), %i (minute), %s (second). Combine them to mirror the incoming text.
INSERT INTO Orders (customer_id, order_date, total_amount)SELECT id, STR_TO_DATE('15/06/2024', '%d/%m/%Y'), 199.99FROM Customers WHERE email = 'alice@example.com';
SELECT name, emailFROM CustomersWHERE created_at >= STR_TO_DATE('2024-01-01', '%Y-%m-%d');
Match format masks exactly, store converted values in DATE/DATETIME columns, and wrap conversion inside INSERT … SELECT or UPDATE so that data is normalized once, not at query time.
Mismatched format mask: Using ‘%Y-%d-%m’ for ‘2024-06-15’ swaps day and month, returning NULL. Align each specifier.
Ignoring time zones: STR_TO_DATE() returns naive DATETIME. Convert or store as UTC if the application is timezone-aware.
Yes, CAST('2024-06-15' AS DATE) works for ISO-formatted strings, but fails if the layout deviates. STR_TO_DATE() is safer for mixed formats.
No, the function relies solely on the explicit format string, ensuring predictable results across servers.
Enable STRICT mode to make conversion errors throw and capture bad data early; otherwise, check for NULL results during ETL.
Yes, include %H:%i:%s in the mask and store the result as DATETIME.
Yes, given the same inputs and SQL mode, the function always returns the same value, making it safe for generated columns.
In STRICT mode MariaDB raises an error; otherwise, the function returns NULL and sets a warning you can view with SHOW WARNINGS.