Extracting Month 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 Month from and the date column.

For example:

SELECT EXTRACT(month from '2025-04-01'::date);
extract --------- 4 (1 row)

Extract Month from enrollments

Let's put that together in a query on enrollments table.

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