Lessons › SQL › Chapter 9: Data Cleaning
SQL lesson
Cleaning date formats with TO_DATE() and TO_CHAR()
Dates stored as text, like '15/01/2024', can't be sorted or compared properly. TO_DATE reads them as real dates: you give it the pattern, DD for the day, MM for the month and YYYY for the year. TO_CHAR goes the other way: from a real date it gives the month's or the day's name, like March or Monday.
Try this lesson free →Example
Turn text into real dates
SELECT order_id, TO_DATE(order_date_text, 'DD/MM/YYYY') AS order_date
FROM orders_raw| order_id | order_date |
|---|---|
| O2001 | 2024-03-01 |
| O2002 | 2024-03-02 |
| O2003 | 2024-03-03 |
| O2004 | 2024-03-04 |
| O2005 | 2024-03-05 |
Step by step
- Reads text as a real date. The pattern matches how the text is written: here day, month, year.
SELECT order_id, TO_DATE(order_date_text, 'DD/MM/YYYY') AS order_date FROM orders_raw - 'FMMonth' gives the month's name, 'FMDay' the day's. PostgreSQL only.
SELECT order_id, order_date, TO_CHAR(order_date, 'FMMonth') AS month_name FROM orders
Practice
1. In orders_raw, order_date_text stores dates as text like '01/03/2024' (day first: 1 March 2024). Convert it to a real date called order_date. Show order_id next to it.
SELECT order_id, TO_DATE(order_date_text, 'DD/MM/YYYY') AS order_date FROM orders_raw2. In customers_raw, signup_text stores dates like '2024/01/15'. Convert it to a real date called signup_date. Show customer_id next to it.
SELECT customer_id, TO_DATE(signup_text, 'YYYY/MM/DD') AS signup_date FROM customers_raw3. In store_sales_raw, sale_text stores dates as text like '01-03-2024' (day first: 1 March 2024). Convert it to a real date called sale_date. Show sale_id next to it.
SELECT sale_id, TO_DATE(sale_text, 'DD-MM-YYYY') AS sale_date FROM store_sales_rawLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →