views:

5216

answers:

2

I need to add the current year as a variable in an SQL statement, how can I retrieve the current year using SQL?

i.e.

  BETWEEN 
    TO_DATE('01/01/**currentYear** 00:00:00', 'DD/MM/YYYY HH24:MI:SS')
    AND
    TO_DATE('31/12/**currentYear** 23:59:59', 'DD/MM/YYYY HH24:MI:SS')
+9  A: 

With to_char:

select to_char(sysdate, 'YYYY') from dual;

In your example you can use something like:

BETWEEN trunc(sysdate, 'YEAR') 
    AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;

The comparision values are exactly what you request:

select trunc(sysdate, 'YEAR') begin_year
     , add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;

BEGIN_YEAR  LAST_SECOND_YEAR
----------- ----------------
01/01/2009  31/12/2009
FerranB
Thanks, through your answer i was able to create the SQL I needed for several different queries!
Craig Angus
+7  A: 

Another option is:

SELECT *
  FROM TABLE
 WHERE EXTRACT( YEAR FROM date_field) = EXTRACT(YEAR FROM sysdate)
borjab
This, combined with a function based index would make the query quite fast.
DrJokepu
Function based index would add unneeded complexity here. Why use FBI when you can do with a simple index?
jva
A simple index on date_field will not be used if a function (like EXTRACT) is applied to the column (tested on Oracle 11g) - would be nice if it did though. A function-based index on EXTRACT(YEAR FROM date_field) can be used, however.
Jeffrey Kemp
Another advantage of using a FBI in this case is that a histogram may provide the optimiser with more accurate statistics on the spread of years in the table.
Jeffrey Kemp