BBampaa

Lessons › SQL › Chapter 4: Shaping data

SQL lesson

EXTRACT DATE

EXTRACT pulls one part out of a date, as a number. EXTRACT(MONTH FROM order_date) gives 3 for March. You can pick YEAR, MONTH, DAY, or DOW for the day of the week (0 is Sunday).

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

One part of a date

SELECT order_id,
       order_date,
       EXTRACT(MONTH FROM order_date) AS order_month
FROM orders

Result:

order_idorder_dateorder_month
O20012024-03-143
O20022024-03-223
O20032024-07-057
O20042024-07-197
O20052024-11-3011

Step by step

  1. Pulls out just the month, as a number.
    SELECT order_id, order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders
  2. Choose the part you need. DOW is the day of the week.
    SELECT order_id, order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders
  3. Filter or group by it, like any column.
    SELECT order_id, order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders

Practice

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

1. Using orders, show order_date, and next to it just the month from order_date. Name the second column order_month.
SELECT order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders
2. Using shipments, show ship_date, and next to it just the month from ship_date. Name the second column ship_month.
SELECT ship_date, EXTRACT(MONTH FROM ship_date) AS ship_month FROM shipments
3. Using promotions, show start_date, and next to it the day of the week each promotion started, as a number (DOW: 0 is Sunday, 6 is Saturday). Name the second column start_dow.
SELECT start_date, EXTRACT(DOW FROM start_date) AS start_dow FROM promotions
4. Using store_sales, show sale_date, and next to it just the day from sale_date. Name the second column sale_day.
SELECT sale_date, EXTRACT(DAY FROM sale_date) AS sale_day FROM store_sales
5. Using returns, show return_date, and next to it just the year from return_date. Name the second column return_year.
SELECT return_date, EXTRACT(YEAR FROM return_date) AS return_year FROM returns

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