Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use like and between in where clause in same statement?

Im trying to find a set of results in a database based on dates. The dates are stored as varchars in the format dd/mm/yyyy hh:mm:ss.

What i would like to do is search for all dates within a range of specified dates.

For example i tried:

SELECT * FROM table_name
WHERE fromDate BETWEEN LIKE '%12/06/2012%' AND LIKE '%16/06/2012%'

Is something like this possible or is there a better way of doing this type of statement, because so far i have had little success?

I'm using Microsoft SQL server 2008.

Peter

like image 330
Peter Avatar asked Dec 27 '22 22:12

Peter


1 Answers

Since your date values also include time, you can't use BETWEEN. The only safe way to do this is:

SELECT <cols> FROM dbo.table_name
WHERE CONVERT(DATE, fromDate, 103) >= '20120612' 
AND CONVERT(DATE, fromDate, 103) < '20120617';

But as Martin noticed, you'll never be able to use an index on that column, so this will always perform a full table scan.

If you really, really want to use BETWEEN, converting to DATE is the only safe way to do so (well, or trimming the time off in other, less efficient ways):

SELECT <cols> FROM dbo.table_name
WHERE CONVERT(DATE, fromDate, 103) BETWEEN '20120612' AND '20120616';

But for consistency reasons I recommend against between even in that case.

like image 101
Aaron Bertrand Avatar answered Feb 23 '23 13:02

Aaron Bertrand