MySQL
string conversion
date formatting
SQL tutorial
database management

How to convert a string to date in MySQL?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

Date strings arrive in many formats from CSV files, APIs, and legacy systems, while MySQL date columns need typed values for reliable filtering and indexing. Converting strings correctly is essential to avoid silent nulls and broken reports. The main tool is STR_TO_DATE, paired with validation and cleanup queries.

Convert Date Strings With STR_TO_DATE

STR_TO_DATE parses a string according to a format pattern and returns a temporal value. If parsing fails, MySQL returns NULL, which is useful for quality checks.

Basic conversion:

sql
SELECT
  STR_TO_DATE('2026-03-04', '%Y-%m-%d') AS parsed_date,
  STR_TO_DATE('03/04/2026 14:30:00', '%m/%d/%Y %H:%i:%s') AS parsed_datetime;

Common format tokens:

  • %Y four-digit year
  • %m month number
  • %d day of month
  • %H hour in twenty-four format
  • %i minutes
  • %s seconds

Always match the exact input format. Even small mismatches, such as swapped day and month positions, produce incorrect values or null output.

Clean and Insert Converted Data

When importing text-heavy sources, stage raw strings first, then convert into typed columns. This separates parsing from ingestion and makes error handling easier.

sql
1CREATE TABLE staging_orders (
2  order_id BIGINT PRIMARY KEY,
3  order_date_text VARCHAR(50) NOT NULL
4);
5
6CREATE TABLE orders (
7  order_id BIGINT PRIMARY KEY,
8  order_date DATE NOT NULL
9);
10
11INSERT INTO orders (order_id, order_date)
12SELECT
13  order_id,
14  STR_TO_DATE(order_date_text, '%d-%m-%Y')
15FROM staging_orders
16WHERE STR_TO_DATE(order_date_text, '%d-%m-%Y') IS NOT NULL;

This pattern inserts only valid rows. Invalid records remain in staging for audit and remediation.

Detect Invalid or Ambiguous Inputs

Some string formats are ambiguous across locales. For example, 04-05-2026 can mean two different dates depending on convention. Use strict import contracts and explicit format patterns per source.

Find invalid rows:

sql
SELECT order_id, order_date_text
FROM staging_orders
WHERE STR_TO_DATE(order_date_text, '%d-%m-%Y') IS NULL;

If data has mixed formats, normalize upstream before database insertion. Attempting many format fallbacks inside one SQL statement quickly becomes brittle and hard to maintain.

Convert Existing Text Columns In Place

If a production table stores dates as text, migrate carefully with a new typed column first. This reduces risk and allows phased validation.

sql
1ALTER TABLE customer_events
2ADD COLUMN event_date DATE NULL;
3
4UPDATE customer_events
5SET event_date = STR_TO_DATE(event_date_text, '%Y/%m/%d')
6WHERE event_date IS NULL;
7
8SELECT COUNT(*) AS invalid_rows
9FROM customer_events
10WHERE event_date_text IS NOT NULL
11  AND event_date IS NULL;

After validation, update application code to read event_date, then remove the old text column in a controlled deployment.

Index and Query Typed Dates Correctly

Once converted, typed date columns support efficient range queries and date functions. Avoid converting string values on every query, which blocks index usage and increases latency.

Good query pattern:

sql
1SELECT order_id, order_date
2FROM orders
3WHERE order_date BETWEEN '2026-03-01' AND '2026-03-31'
4ORDER BY order_date;

For reports requiring display formatting, keep raw typed storage and format only at query output or application layer.

sql
1SELECT
2  order_id,
3  DATE_FORMAT(order_date, '%b %d, %Y') AS display_date
4FROM orders;

Storage should stay typed and canonical, while display can be localized as needed.

Common Pitfalls

  • Using the wrong format mask with STR_TO_DATE, causing nulls or swapped values.
  • Storing dates as text long-term, which hurts indexing and consistency.
  • Ignoring invalid parse results instead of explicitly filtering or logging them.
  • Mixing locale-specific formats in one source pipeline without normalization.
  • Running conversion logic inside every analytical query instead of one-time migration.

Summary

  • Use STR_TO_DATE with exact format strings to parse date text safely.
  • Stage raw strings before inserting into typed date columns.
  • Treat null parse results as data quality signals, not harmless noise.
  • Migrate legacy text columns through phased typed-column backfills.
  • Keep storage typed and apply display formatting only at output time.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.