Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle date comparison in where clause

Tags:

date

oracle

For eg I have a student table with a DOJ(date of joining) column with its type set as DATE now in that I have stored records in dd-mon-yy format.

I have an IN param at runtime with date passed as string and its in dd/mm/yyyy format. How do I compare and fetch results on date?

I want to fetch count of records of students who have DOJ of 25-AUG-92 per my database table student, but I am getting date as varchar in dd/mm/yyyy format in an IN param, kindly please guide.

I have tried multiple options such as trunc, to_date, to_char but, unfortunately nothing seems to work.

like image 859
Hitesh Joshi Avatar asked Feb 05 '23 15:02

Hitesh Joshi


1 Answers

I have a student table with a DOJ(date of joining) column with its type set as DATE now in that I have stored records in dd-mon-yy format.

Not quite, the DATE data-type does not have a format; it is stored internally in tables as 7-bytes (year is 2 bytes and month, day, hour, minute and second are 1-byte each). The user interface you are using (i.e. SQL/PLUS, SQL Developer, Toad, etc.) will handle the formatting of a DATE from its binary format to a human readable format. In SQL/Plus (or SQL Developer) this format is based on the NLS_DATE_FORMAT session parameter.

If the DATE is input using only the day, month and year then the time component is (probably) going to be set to 00:00:00 (midnight).

I have an IN param at runtime with date passed as string or say varchar and its in dd/mm/yyyy format. How do I compare and fetch results on date.?

Assuming the time component for you DOJ column is always midnight then:

SELECT COUNT(*)
FROM   students
WHERE  doj = TO_DATE( your_param, 'dd/mm/yyyy' )

If it isn't always midnight then:

SELECT COUNT(*)
FROM   students
WHERE  TRUNC( doj ) = TO_DATE( your_param, 'dd/mm/yyyy' )

or:

SELECT COUNT(*)
FROM   students
WHERE  doj >= TO_DATE( your_param, 'dd/mm/yyyy' )
AND    doj <  TO_DATE( your_param, 'dd/mm/yyyy' ) + INTERVAL '1' DAY
like image 198
MT0 Avatar answered Feb 11 '23 18:02

MT0