Explain Codes LogoExplain Codes Logo

How do I get the current year using SQL on Oracle?

sql
date-manipulation
oracle-sql
database-queries
Alex KataevbyAlex Kataev·Dec 26, 2024
TLDR

To get the current year in Oracle, you can use the EXTRACT function:

-- When you need the year so desperately that you extract it. SELECT EXTRACT(YEAR FROM SYSDATE) FROM dual;

You can also get a string representation of the current year using the TO_CHAR function:

-- Because sometimes you want text. Even in databases. SELECT TO_CHAR(SYSDATE, 'YYYY') FROM dual;

Spotlight on alternate strategies

Starting and ending: the year's boundary

To obtain the first day of the current year, you use this:

-- New Year Celebration SQL Style! SELECT TRUNC(SYSDATE, 'YEAR') FROM dual;

To find the last second of the current year:

-- Because we all love countdowns to the new year! SELECT ADD_MONTHS(TRUNC(SYSDATE, 'YEAR'), 12) - 1/24/60/60 FROM dual;

Filtering your data: current year edition

When it's time to filter data based on the current year:

-- When the SQL knows when you are working SELECT * FROM your_table WHERE date_column BETWEEN TRUNC(SYSDATE, 'YEAR') AND ADD_MONTHS(TRUNC(SYSDATE, 'YEAR'), 12) - 1/24/60/60;

Dealing with dynamic year comparisons

For dynamic SQL comparison that changes with the year:

-- SQL always stays current! SELECT * FROM your_table WHERE EXTRACT(YEAR FROM date_column) = EXTRACT(YEAR FROM SYSDATE);

Extra insights: master the dates

More than years: Exploring date components

You might also need other components of the date for complex filterings, like the month or day:

-- February is too cold, let's get to March! SELECT EXTRACT(MONTH FROM SYSDATE) FROM dual;

The power of dual table

Oracle's magic table dual comes to aid for these operations:

-- My instant magic mirror for SQL SELECT SYSDATE FROM dual;

Community wisdom

Community feedback in terms of vote counts and acceptance status is definitely of help!