Extracting Date Components from Dates

Often times when working with time series data for analysis, you may be required to extract information from dates such a the quarter, month, year or even day of the week. For example, analyzing weekend sales may be an interesting exercise to understand business performance behavior. This short snippet demonstrates how to extract such components from date.

enrollments table

For this exercise, I will use the enrollments table which looks like below

SELECT * FROM enrollments
enrollment_id | employee_id | session_id | enrollment_date | completion_status | score --------------+-------------+------------+-----------------+-------------------+------- 1 | 1 | 101 | 2023-01-20 | Completed | 88 2 | 3 | 101 | 2023-01-25 | Completed | 95 3 | 2 | 102 | 2023-02-15 | In Progress | 4 | 7 | 102 | 2023-02-20 | Completed | 76 5 | 1 | 103 | 2023-12-15 | Dropped | 6 | 4 | 103 | 2023-12-20 | Completed | 82 7 | 6 | 104 | 2023-03-10 | Completed | 91 8 | 2 | 105 | 2023-01-30 | Completed | 79 9 | 7 | 105 | 2023-02-10 | In Progress | (9 rows)

Extract() Function

Postgresql offers the Extract() function to help us deal with dates. We can simply extract the date by passing the Year from and the date column.

For example:

SELECT EXTRACT(year from '2025-04-01'::date)
extract --------- 2025 (1 row)

Extract Year from enrollments

Now let's put that together in a query on enrollments table

SELECT enrollment_date, 
        EXTRACT(year from enrollment_date) AS year, 
        completion_status 
FROM enrollments;
enrollment_date | year | completion_status ----------------+------+------------------- 2023-01-20 | 2023 | Completed 2023-01-25 | 2023 | Completed 2023-02-15 | 2023 | In Progress 2023-02-20 | 2023 | Completed 2023-12-15 | 2023 | Dropped 2023-12-20 | 2023 | Completed 2023-03-10 | 2023 | Completed 2023-01-30 | 2023 | Completed 2023-02-10 | 2023 | In Progress (9 rows)