Often in PostgreSQL you may want to select rows from a table where a date column has a date in the current year.
You can use the following syntax to do so:
SELECT *
FROM emp
WHERE date_part('year', start_date) = date_part('year', CURRENT_DATE);
This particular example selects all rows from the table named emp where the year in the start_date column is equal to the current year.
Note that we use date_part(‘year’, start_date) to extract the year from each value in the start_date column.
We then check if this year value is equal to the year from the CURRENT_DATE function, which returns the current date.
The following example shows how to use this syntax in practice.
Example: How to Select Current Year in PostgreSQL
Suppose that we create the following table named emp that contains information about when various employees started working at some company:
-- 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
This article is currently being written in 2024.
Suppose that we would like to only select the rows from this table where the year in the start_date column is equal to 2024.
We can use the following syntax to do so:
SELECT *
FROM emp
WHERE date_part('year', start_date) = date_part('year', CURRENT_DATE);
empid | start_date | sales
-------+------------+-------
6 | 2024-02-20 | 52
7 | 2024-05-15 | 50
Notice that this returns the two rows from the table where the year in the start_date column is 2024.
You can use similar syntax to select rows from your own table where a year in a date column is equal to the current year.
Additional Resources
The following tutorials explain how to perform other common tasks in PostgreSQL:
PostgreSQL: How to Select All Records from Yesterday
PostgreSQL: How to Select All Records from Last 7 Days
PostgreSQL: How to Subtract Years from a Date
