1

Query 1 :

select count(*) from CI_TXN_HEADER where TXN_HEADER_DTTM = '25-JAN-13';

Result: 1

Query 2 :

select count(*) from CI_TXN_HEADER where TXN_HEADER_DTTM like '25-JAN-13';

Result: 19

In my DB I have 19 rows with TXN_HEADER_DTTM as 25-JAN-13. Data Type of TXN_HEADER_DTTM is DATE.

Can someone please explain the difference in output?

AbsoluteƵERØ
  • 7,816
  • 2
  • 24
  • 35
Curious Techie
  • 185
  • 2
  • 15

3 Answers3

4

An Oracle DATE column contains a date and a time. The LIKE condition is only for VARCHAR columns. If applied to other data types Oracle implicitly converts that to a varchar (using rules depending on the current client settings).

So you might have rows with e.g. 2013-01-25 17:42:01, however the string constant '25-JAN-13' is (most probably) converted to: 2013-01-25 00:00:00 and thus the = comparison doesn't work.

To find all rows for a specific day use trunc() and a proper date literal. Don't rely on the evil implicit data type conversion to specify date values.

Use trunc() to set the time part of a DATE value to 00:00:00:

I prefer ANSI SQL date literals:

select count(*) 
from CI_TXN_HEADER 
where trunc(TXN_HEADER_DTTM) = DATE '2013-01-25';

You can also use Oracle's to_date:

select count(*) 
from CI_TXN_HEADER 
where trunc(TXN_HEADER_DTTM) = to_date('2013-01-25', 'yyyy-mm-dd');

Note that Oracle can't use an index on TXN_HEADER_DTT, so if performance is critical use a range query:

select count(*) 
from CI_TXN_HEADER 
where TXN_HEADER_DTTM >= DATE '2013-01-25'
  and TXN_HEADER_DTTM < DATE '2013-01-25' + 1;
2

The difference between like and equal is explained in this link very good https://stackoverflow.com/a/2336940/4506285

I checked your problem on my table and I get the same results.

This link helps also to understand how to compare dates in sql https://stackoverflow.com/a/18505739/4506285

pwain
  • 279
  • 2
  • 7
1

Maybe your data consists of space, it is not exactly '25-JAN-13' but ' 25-JAN-13';

Please refer this two link:

  1. Equals(=) vs. LIKE

  2. What's the difference between "LIKE" and "=" in SQL?

Alden Ken
  • 142
  • 8