Often in PostgreSQL you may want to extract a quarter from a date column.
You can use the following basic syntax to do so:
SELECT extract(quarter FROM start_date) AS quarter
FROM emp;
This particular example will extract the quarter from the date in the start_date column of the table named emp and save the results to a new column named quarter.
Note that the quarter command will return one of the following values:
- 1 if the date falls in January, February or March.
- 2 if the date falls in April, May or June.
- 3 if the date falls in July, August or September.
- 4 if the date falls in October, November or December.
The following example shows how to use this syntax in practice.
Example: How to Extract Quarter from Date in PostgreSQL
Suppose that we create the following table named emp that contains information about various employees at some company including their starting date and their total sales made:
-- create table named 'emp'
CREATE TABLE emp (
empID INT PRIMARY KEY,
start_date DATE,
sales INT
);
-- add rows to the table
INSERT INTO emp VALUES (0001, '2021-04-01', 134);
INSERT INTO emp VALUES (0002, '2022-07-01', 201);
INSERT INTO emp VALUES (0003, '2022-08-15', 155);
INSERT INTO emp VALUES (0004, '2022-09-01', 98);
INSERT INTO emp VALUES (0005, '2023-11-23', 65);
INSERT INTO emp VALUES (0006, '2024-02-20', 52);
INSERT INTO emp VALUES (0007, '2024-05-15', 50);
-- view all rows in table
SELECT * FROM emp;
empid | start_date | sales
-------+------------+-------
1 | 2021-04-01 | 134
2 | 2022-07-01 | 201
3 | 2022-08-15 | 155
4 | 2022-09-01 | 98
5 | 2023-11-23 | 65
6 | 2024-02-20 | 52
7 | 2024-05-15 | 50
Suppose that we would like to extract the quarter from each date in the start_date column.
We can use the following syntax to do so:
SELECT empID,
start_date,
extract(quarter FROM start_date) AS quarter
FROM emp;
empid | start_date | quarter
-------+------------+---------
1 | 2021-04-01 | 2
2 | 2022-07-01 | 3
3 | 2022-08-15 | 3
4 | 2022-09-01 | 3
5 | 2023-11-23 | 4
6 | 2024-02-20 | 1
7 | 2024-05-15 | 2
The new column named quarter contains the quarter from the date in the start_date column.
For example, we can see:
- The date 2021-04-01 belongs to quarter 2.
- The date 2022-07-01 belongs to quarter 3.
- The date 2022-08-15 belongs to quarter 3.
And so on.
You can use similar syntax to extract the quarter from a date column in your own table.
Additional Resources
The following tutorials explain how to perform other common tasks in PostgreSQL:
PostgreSQL: How to Select Rows in Date Range
PostgreSQL: How to Extract Date from a Timestamp
PostgreSQL: How to Extract Month from Date
