Question

Here is my table

enter image description here

I am executing a query that give me result of fields whose item_valid_from must be greater than today's date and item_valid_to must be less than today.

My query is

select * 
  from tbl1 
 where item_valid_from >= CurDate() 
       and item_valid_to < CurDate()

Any Solution?

Was it helpful?

Solution

I would advise you to change item_valid_* field formats to DATE field format. You will save you a lot of trouble in the future.

But ok, if you don't want to do that, then you can use STR_TO_DATE() function:

SELECT *
FROM `table`
WHERE CURDATE() BETWEEN STR_TO_DATE(`from_field`, '%d-%m-%Y') AND STR_TO_DATE(`to_field`, '%d-%m-%Y')

demo

OTHER TIPS

Assuming the datatype item_valid_from and item_valid_to is DATE, TIMESTAMP, etc, then you have your operators backwards. Think of the time as seconds since 1970, since this is how it is stored in unix time. That means that item_valid_from is going to be smaller than item_valid_to, and you want it to display when today is somewhere between them. You want the item_valid_from to be less than or equal to now, and the item_valid_to to be greater than now (not in the past).

SELECT * 
FROM tbl1 
WHERE item_valid_from <= CURDATE() AND item_valid_to > CURDATE()

See this SQL Fiddle for an example, only 2-4 are valid and show up in the results being valid from a date in the past and expiring on a date in the future.

You have to use following query which change current date format then compare date and fetch result :

SELECT *
FROM tbl1
WHERE date_format(item_valid_from,'%d-%m-%Y') >= date_format(CurDate( ),'%d-%m-%Y')
AND date_format(item_valid_to,'%d-%m-%Y') < date_format(CurDate( ),'%d-%m-%Y')

Please Check this :http://sqlfiddle.com/#!2/561d0/2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top