BBampaa

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 →
About 5–10 minutes · no sign-up needed

Example

Turn text into real dates

SELECT order_id, TO_DATE(order_date_text, 'DD/MM/YYYY') AS order_date
FROM orders_raw

Result:

order_idorder_date
O20012024-03-01
O20022024-03-02
O20032024-03-03
O20042024-03-04
O20052024-03-05

Step by step

  1. 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
  2. '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

Try each one in your head first, then open the answer.

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_raw
2. 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_raw
3. 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_raw

Learn 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 →
About 5–10 minutes · no sign-up needed