-6

I want to know how to fetch data between two dates using SQL queries. In my table date format is dd/mm/yyyy hh:mm:ss am/pm.

According to these dates format I need to fetch data. Column is DATE type.

I tried with below query

select * from sales 
where to_char(txn_date, 'dd-mm-yyyy' ) 
between '10-09-2018' and '30-09-2018'

I am getting wrong records. Why?

APC
  • 144,005
  • 19
  • 170
  • 281

4 Answers4

2

It looks like you're saving the timestamps as TEXT or VARCHAR in the database. If that is the case, you can't. And it's a really bad approach. Please use type DATETIME instead, which enables you to use the BETWEEN operator.

When you're using the DATETIME type, you can do

SELECT *
FROM sales
WHERE txn_date BETWEEN '2018-01-01 00:00:00' AND '2018-12-31 23:59:59'

Which will give you all the data in the year of 2018 and still using your indexes

EDIT

Since you've now told that you're using DATE as data type, you can use the same solution, without the time.

SELECT *
FROM sales
WHERE txn_date BETWEEN '2018-01-01' AND '2018-12-31'
MicBehrens
  • 1,780
  • 8
  • 34
  • 57
0

You are getting wrong records because you are converting the dates into a string. That means the query uses string semantics when doing the comparison. As a string, '15-12-2999' and '15-05-2000 are between '10-09-2018' and '30-09-2018' because '15' has a higher ASCII value than '10' and a lower ASCII value than '30'.

The solution is quite simple: use date datatypes for the comparison.

select * from sales 
where txn_date between date '2018-09-10' and date '2018-09-30'

If TXN_DATE has a time element you may want to change the query to

select * from sales 
where txn_date >= date '2018-09-10' 
and txn_date < date '2018-10-01'

Otherwise you will not retrieve records for transactions made after midnight on 30th September.

Alternatively you could remove the time element by truncating the date:

select * from sales 
where trunc(txn_date) between date '2018-09-10' and date '2018-09-30'
APC
  • 144,005
  • 19
  • 170
  • 281
0

select * from sales where trunc(txn_date ) between '10-09-2018' and '30-09-2018' If you have the format date/time trunc would eliminate the time in the date

Himanshu
  • 3,830
  • 2
  • 10
  • 29
0

Finally I got answer for this question Select *from sales where txn_date between to_date('01-10-2018 00:00:00','DD-MM-YYYY HH24:MI:SS') And to_date('31-10-2018 23:59:59','DD-MM-YYYY HH24:MI:SS')