0

I have a table like this one:

Items    start_datatime         end_datatime
A1       2015-01-31 10:00:00    2015-02-02 20:30:00
A2       2015-02-04 16:00:00    2015-02-04 16:30:00

And i want to select items for a given datetime (ex: 2015-02-02).

So, i'm trying this query:

SELECT Items FROM table WHERE start_datatime >= 2015-02-02 00:00:00
AND end_datatime < 2015-02-03 00:00:00

In this example, i want to select item A1 when date is 2015-01-31, 2015-02-01 and 2015-02-02. And A2 when date is 2015-02-04.

1
  • @MKhalidJunaid, yeah. I've just corrected the question. Commented Feb 2, 2015 at 19:36

2 Answers 2

1

If you want any records that overlap on that date, the logic would be:

SELECT Items
FROM table
WHERE start_datatime <= '2015-02-03 00:00:00' AND
      end_datatime >= '2015-02-02 00:00:00';

If you want full overlap so the entire period includes the day:

SELECT Items
FROM table
WHERE start_datatime <= '2015-02-02 00:00:00' AND
      end_datatime >= '2015-02-03 00:00:00';

And, if you only care about midnight when the day starts:

SELECT Items
FROM table
WHERE start_datatime <= '2015-02-02 00:00:00' AND
      end_datatime >= '2015-02-02 00:00:00';
Sign up to request clarification or add additional context in comments.

2 Comments

i got what i want with WHERE start_datatime <= '2015-02-02 23:59:59' AND end_datatime >= '2015-02-02 00:00:00'
It is better to use start_datatime < '2015-02-03' rather than start_datatime <= '2015-02-02 23:59:59'.
0

Remove the second WHERE and it should work:

SELECT Items FROM table WHERE start_datatime >= 2015-02-02 00:00:00 AND end_datatime <= 2015-02-02 00:00:00

To improve it, i would change end_datatime <= 2015-02-02 00:00:00 to end_datatime < 2015-02-02 00:00:00, because your solution would include all Items which end at the next day.

Also consider items which start before that day and end after it. Should they be excluded? In your solution, this would happen.

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.