Lessons › SQL › Deep Dive: Data Cleaning
SQL lesson
Cleaning date formats with TO_DATE() and TO_CHAR()
TO_DATE() converts a date stored as plain text into a real date the database can sort, filter, and do math on.
Try this lesson free →Example
Cleaning Retail Date Formats with TO_DATE() and TO_CHAR()
SELECT order_id,
TO_DATE(raw_order_date, 'DD-Mon-YYYY') AS clean_order_date,
TO_CHAR(TO_DATE(raw_order_date, 'DD-Mon-YYYY'), 'YYYY-MM-DD') AS iso_order_date
FROM orders
WHERE order_id = 'O2001'| order_id | clean_order_date | iso_order_date |
|---|---|---|
| O2001 | 2024-01-15 | 2024-01-15 |
Step by step
- AS gives a column a friendlier name in the result.
SELECT order_id, TO_DATE(raw_order_date, 'DD-Mon-YYYY') AS clean_order_date, TO_CHAR(TO_DATE(raw_order_date, 'DD-Mon-YYYY'), 'YYYY-MM-DD') AS iso_order_date - FROM tells SQL which table to pull the data from.
SELECT order_id, TO_DATE(raw_order_date, 'DD-Mon-YYYY') AS clean_order_date, TO_CHAR(TO_DATE(raw_order_date, 'DD-Mon-YYYY'), 'YYYY-MM-DD') AS iso_order_date FROM orders - WHERE keeps only the rows that match your condition.
SELECT order_id, TO_DATE(raw_order_date, 'DD-Mon-YYYY') AS clean_order_date, TO_CHAR(TO_DATE(raw_order_date, 'DD-Mon-YYYY'), 'YYYY-MM-DD') AS iso_order_date FROM orders WHERE order_id = 'O2001';
Practice
1. In orders_raw, order_date_text stores dates as text like '01/03/2024' (DD/MM/YYYY). Convert it to a real date called order_date with TO_DATE.
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.
SELECT customer_id, TO_DATE(signup_text, 'YYYY/MM/DD') AS signup_date FROM customers_raw3. In store_sales_raw, sale_text stores dates like '01-03-2024' (DD-MM-YYYY). Convert it to a real date called sale_date.
SELECT sale_id, TO_DATE(sale_text, 'DD-MM-YYYY') AS sale_date FROM store_sales_raw4. Using orders, show order_id and order_date formatted as 'DD/MM/YYYY' text, named order_date_text.
SELECT order_id, TO_CHAR(order_date, 'DD/MM/YYYY') AS order_date_text FROM orders5. Using shipments, show shipment_id and ship_date formatted as 'YYYY-MM' text, named ship_month.
SELECT shipment_id, TO_CHAR(ship_date, 'YYYY-MM') AS ship_month FROM shipmentsLearn 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 →