-1

I have the following data in the table

from_date    to_date
2015-05-12    2015-10-20
2015-10-21    2016-02-02
2016-02-03    NULL

Where NULL value in to_date denotes that this record is valid until this time.

The records I want to retrieve is between '2015-10-30' and '2016-08-08'. How do I get the second and third rows based on my search criteria?

6
  • 2015-10-21 isn't between 2015-10-30 and 2016-08-08. Commented Aug 11, 2016 at 4:00
  • 2015-10-30 is between 2015-10-21 and 2016-02-02 Commented Aug 11, 2016 at 4:04
  • Probably you are confusing yourself @SumanBhandari Commented Aug 11, 2016 at 4:05
  • Then what about 2016-08-08? Commented Aug 11, 2016 at 4:06
  • to_date - NULL mean, this record is valid until today. since 2015-10-30 lies between second row. and '2016-08-08' lies in the third row, I need to be able to retrieve both these rows. Am I clearing myself @AlokPatel ? Commented Aug 11, 2016 at 4:09

2 Answers 2

1

I am confused why are you expecting the second row in the result set. Is it something loose range searching (either by from_date or by to_date)?

You can try something like that:

SELECT 
*
FROM your_table
WHERE from_date >= startDate
AND IF(to_date IS NULL, TRUE, to_date <= endDate);

Note: Here startDate and endDate are the dates in your given range.

EDIT:

SELECT 
 *
FROM your_table
WHERE 
'2015-10-30' BETWEEN from_date AND COALESCE(to_date,CURDATE())
OR 
'2016-08-08' BETWEEN from_date AND COALESCE(to_date,CURDATE())
Sign up to request clarification or add additional context in comments.

2 Comments

to_date - NULL means, this record is valid until today. since '2015-10-30' lies between second row. and '2016-08-08' lies between third row, I need to be able to retrieve both these rows
One of the weird date range searches I've ever seen. No problem. Just tell me ` '2015-10-30' and '2016-08-08'` here are two dates you want to search with them. Is it always fixed to two?
0

Finally, I found out what I was looking for.

select * from table where
end_date >= start_search && start_date <= end_search

More detailed answer in the link below. Answered by pacerier

mysql-query-for-certain-date-range

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.