简体   繁体   中英

SQL - Select all rows which is >= and <=

i trying to do a sql query which i combine de compare operators with substring.

in my column date i have the following value inside : 09-01-2014 12:02:55

what i try to now is to select all rows which is >= 09-01-2014 and for example <=22-01-2014

how can i do it?

i have trying for example with this code:

SELECT * From table Where Name= 'Something'  
AND  SUBSTRING(date,1,10) = '09-01-2014'
AND SUBSTRING(date,1,10) < '22-01-2014'

The BETWEEN operator will work, like this:

SELECT * 
From table 
Where Name= 'Something'  
AND  `date` BETWEEN '2014-01-09' AND '2014-01-23'

Working Demo: http://sqlfiddle.com/#!2/b4d7e

You can use the BETWEEN operator

SELECT * FROM table 
WHERE Name = 'Something'
AND SUBSTRING(date, 1, 10) BETWEEN '09-01-2014' AND '22-01-2014'

EDIT: I'm still leaving this here, but it is not an error proof solution (as pointed out by oerkelens down in the comments)

Try this:

SELECT * 
FROM tableA a 
WHERE a.nme= 'Something' AND 
      DATE(STR_TO_DATE(a.date, '%d-%m-%Y %H:%i:%s')) >= '2014-01-09' AND 
      DATE(STR_TO_DATE(a.date, '%d-%m-%Y %H:%i:%s')) <= '2014-01-22';

OR

SELECT * 
FROM tableA a 
WHERE a.nme= 'Something' AND 
      DATE(STR_TO_DATE(a.date, '%d-%m-%Y %H:%i:%s')) BETWEEN '2014-01-09' AND '2014-01-22';

Using the following syntax makes your query sargable. It allows query to use any Indexes defined on the date column. for more information SARGable Queries with Datetime Datatype

SELECT * From table 
Where Name= 'Something'  
AND [DateColumn] >= '20140109'
AND [DateColumn] <= '20140122'

You are converting the date from the table row into a string before comparing to the bookend dates. You need to do the opposite. Convert the bookend dates from strings to dates, then compare each test date.

Some form of the CONVERT or CAST function should do that for you.

The reason your approach won't work is that when SQL server compares strings, it uses alphabetical order. You want ascending date order, which is a different order.

Which Database do you use? Oracle:

SELECT *
  FROM table tbl
 WHERE 1=1
   AND name = 'Something'
   AND trim(tbl.column) >= to_date('2014-01-09','DD-MM-YYYY')
   AND trim(tbl.column) <= to_date('2014-01-22','DD-MM-YYYY')

or you just convert it into a number/integer like YYYYMMDD then the >= =< operators will work too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM