Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle comparing timestamp with date

Tags:

oracle

I have a timestamp field and I just want to compare the date part of it in my query in Oracle

How do I do that,

SELECT * FROM Table1 WHERE date(field1) = '2012-01-01'  
like image 338
user1050619 Avatar asked Sep 26 '12 20:09

user1050619


People also ask

Can Oracle timestamp compare with date?

Answers. You can use the TO_DATE function. Convert both to timestamp and compare.

How can I compare two timestamps in Oracle?

To calculate the difference between the timestamps in Oracle, simply subtract the start timestamp from the end timestamp (here: arrival - departure ). The resulting column will be in INTERVAL DAY TO SECOND . The first number you see is the number of whole days that passed from departure to arrival .

Can you compare SQL date and timestamp?

A date, time, or timestamp value can be compared with another value of the same data type, a datetime constant of the same data type, or with a string representation of a value of that data type. Additionally, a TIMESTAMP WITHOUT TIME ZONE value can be compared with a TIMESTAMP WITH TIME ZONE value.

How do I get a dual timestamp?

In order to get the system date and time returned in a TIMESTAMP datatype, you can use the SYSTIMESTAMP function such as: SQL> SELECT SYSTIMESTAMP FROM DUAL; You can set the initialization parameter FIXED_DATE to return a constant value for what is returned from the SYSDATE function.


2 Answers

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD') 

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1   where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD')     and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD') 
like image 130
beny23 Avatar answered Oct 01 '22 10:10

beny23


You can truncate the date

SELECT * FROM Table1 WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD') 

Look at the SQL Fiddle for more examples.

like image 22
hol Avatar answered Oct 01 '22 12:10

hol