Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select records for a certain year Oracle

Tags:

sql

oracle11g

I have an oracle table that store transaction and a date column. If I need to select records for one year say 2013 I do Like this:

select * 
  from sales_table
 where tran_date >= '01-JAN-2013'
   and tran_date <= '31-DEC-2013'

But I need a Straight-forward way of selecting records for one year say pass the Parameter '2013' from an Application to get results from records in that one year without giving a range. Is this Possible?

like image 928
Stanley Mungai Avatar asked Aug 15 '13 09:08

Stanley Mungai


People also ask

Is there a year function in Oracle?

The YEAR function returns the year part of a value. The argument must be a date, timestamp, or a valid character string representation of a date or timestamp.

What does %type do in Oracle?

The %TYPE attribute lets you declare a constant, variable, collection element, record field, or subprogram parameter to be of the same data type as a previously declared variable or column (without knowing what that type is).

Can you use Datepart in Oracle?

However, datepart() function works in SQL Server, Oracle, and Azure SQL databases only. For other database management servers such as PostgreSQL and MYSQL, we can use functions like EXTRACT().

Is year a data type in Oracle?

Using the DATE Datatype. Use the DATE datatype to store point-in-time values (dates and times) in a table. The DATE datatype stores the century, year, month, day, hours, minutes, and seconds. Oracle uses its own internal format to store dates.


1 Answers

You can use to_date function

http://psoug.org/reference/date_func.html

select *
  from sales_table
 where tran_date >= to_date('1.1.' || 2013, 'DD.MM.YYYY') and 
       tran_date < to_date('1.1.' || (2013 + 1), 'DD.MM.YYYY')

solution with explicit comparisons (tran_date >= ... and tran_date < ...) is able to use index(es) on tran_date field.

Think on borders: e.g. if tran_date = '31.12.2013 18:24:45.155' than your code tran_date <='31-DEC-2013' will miss it

like image 188
Dmitry Bychenko Avatar answered Oct 05 '22 12:10

Dmitry Bychenko