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 →Example
One part of a date
SELECT order_id,
order_date,
EXTRACT(MONTH FROM order_date) AS order_month
FROM orders| order_id | order_date | order_month |
|---|---|---|
| O2001 | 2024-03-14 | 3 |
| O2002 | 2024-03-22 | 3 |
| O2003 | 2024-07-05 | 7 |
| O2004 | 2024-07-19 | 7 |
| O2005 | 2024-11-30 | 11 |
Step by step
- Pulls out just the month, as a number.
SELECT order_id, order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders - 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 - Filter or group by it, like any column.
SELECT order_id, order_date, EXTRACT(MONTH FROM order_date) AS order_month FROM orders
Practice
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 orders2. 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 shipments3. 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 promotions4. 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_sales5. 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 returnsLearn 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 →