Select data from date range between two dates

Ronjon picture Ronjon · Jan 8, 2013 · Viewed 813k times · Source

I have a table Named Product_Sales and it holds data like this

Product_ID | Sold_by | Qty | From_date  | To_date
-----------+---------+-----+------------+-----------
3          | 12      | 7   | 2013-01-05 | 2013-01-07
6          | 22      | 14  | 2013-01-06 | 2013-01-10
8          | 11      | 9   | 2013-02-05 | 2013-02-11

Now what is the query if I want to select sales data between two dates from a date range?

For example, I want to select sales data from 2013-01-03 to 2013-01-09.

Answer

Dmitry Lukichev picture Dmitry Lukichev · Jul 27, 2014

interval intersection description

As you can see, there are two ways to get things done:

  • enlist all acceptable options
  • exclude all wrong options

Obviously, second way is much more simple (only two cases against four).

Your SQL will look like:

SELECT * FROM Product_sales 
WHERE NOT (From_date > @RangeTill OR To_date < @RangeFrom)