CAST vs TO_DATE: Fixing String Dates
It's **Day 79**, and we're fixing data types. Often, lazy developers store dates as strings (`VARCHAR`) instead of the `DATE` type. This means you can't use `ORDER BY` or find the "Last 30 days."
The Simple Fix: CAST
If the string is already in a standard format (YYYY-MM-DD), use `CAST`.
SELECT CAST(date_string AS DATE) FROM orders;
-- Or Postgres shorthand:
SELECT date_string::DATE FROM orders;
The Complex Fix: TO_DATE
What if the date is formatted like "01-Jan-2024"? `CAST` will fail. You need to tell SQL exactly how to read it.
SELECT TO_DATE(date_string, 'DD-Mon-YYYY') FROM orders;
Why this is critical
Once your column is a "True Date," you unlock all the powerful time-series functions we learned in Phase 2 and 5. You can calculate growth, week-over-week changes, and more!
Your Task for Today
Check your database. Are your dates stored as `DATE`, `TIMESTAMP`, or `VARCHAR`? If they are `VARCHAR`, practice casting them.
*Day 80: Deduplication with DISTINCT ON (Postgres Specialty).*