144

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.

Anonymous
  • 835
  • 1
  • 5
  • 21
Ronjon
  • 1,789
  • 4
  • 16
  • 26

19 Answers19

227

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)
Dmitry Lukichev
  • 2,519
  • 1
  • 16
  • 12
  • 82
    I just want to say I love that you drew this out on a white board to explain the answer. You have my respect and my admiration. – Ben Bynum Dec 20 '19 at 19:05
  • 8
    I know that this issue is pretty old but if you don't want or can't use this `WHERE NOT` condition, turning around the operators and adding an equal is also doing the job: `SELECT * FROM Product_sales WHERE From_date <= @RangeTill OR To_date >= @RangeFrom` – Laurenz Glück Jan 20 '20 at 01:04
  • 8
    @LaurenzGlück not `OR`, it should be `SELECT * FROM Product_sales WHERE From_date <= @RangeTill AND To_date >= @RangeFrom` – andyf Nov 09 '20 at 01:42
  • Note if To_date can be null and you want to include records not ended yet, you will want to do something like this: `NOT (From_date > @RangeTill OR ISNULL(To_date, '12/31/9999') < @RangeFrom)` – thecoolmacdude Dec 15 '21 at 13:50
  • One of the best posts ever in this site. Epic! Thanks. – Freddy Dec 09 '22 at 10:31
128
SELECT * from Product_sales where
(From_date BETWEEN '2013-01-03'AND '2013-01-09') OR 
(To_date BETWEEN '2013-01-03' AND '2013-01-09') OR 
(From_date <= '2013-01-03' AND To_date >= '2013-01-09')

You have to cover all possibilities. From_Date or To_Date could be between your date range or the record dates could cover the whole range.

If one of From_date or To_date is between the dates, or From_date is less than start date and To_date is greater than the end date; then this row should be returned.

Mp0int
  • 18,172
  • 15
  • 83
  • 114
  • How to return all data if both inputting date is null or empty? and also, if one of the date is null or empty should get result based on that criteria – Coding world Jan 22 '20 at 11:13
46

Try following query to get dates between the range:

SELECT  *
FROM    Product_sales 
WHERE   From_date >= '2013-01-03' AND
        To_date   <= '2013-01-09'
Siyavash Hamdi
  • 2,764
  • 2
  • 21
  • 32
jkmurphy1
  • 683
  • 5
  • 9
  • 12
    This does not cover all possibilities! – Mp0int Apr 01 '16 at 10:35
  • @FallenAngel , can you please explain me which are not covered? – Babblo May 19 '16 at 14:04
  • 4
    Check my [answer](http://stackoverflow.com/a/36354313/257972) please,you did not cover the sales that started before `start_date` but ended between `start_date` and `end_date`. On the other hand, the question is not clear enough I guess, we have no clue whether we should took sales that are strictly between given dates or dates that partially includes the date range, but may extend on one side or the other or both? So the basic problem is about the question being not clear I guess. – Mp0int May 20 '16 at 07:41
  • I know this post is old but for those reading: This is not between dates but is Inclusive of the dates. From and To. – Ken Dec 19 '16 at 17:23
26
SELECT * FROM Product_sales 
WHERE From_date between '2013-01-03'
AND '2013-01-09'
Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105
Berkay Turancı
  • 3,373
  • 4
  • 32
  • 45
  • Your select will be wrong for the example From_date: 2012-12-30 to To_Date: 2013-01-05. These dates are inside the desired range but in your SQL won't be returned because they start *before* the range, but they finish **inside** the range. – NetVicious Feb 22 '17 at 07:47
12

This covers all conditions that you are looking for.

SELECT * from Product_sales where (From_date <= '2013-01-09' AND To_date >= '2013-01-01')
Avinash
  • 790
  • 2
  • 11
  • 26
  • 2
    This should be the correct answer. You have to use from_date with <= the latest date with AND and the to_date >= the earliest date. All cases are covered this way doing a bit of boolean magic and it is simpler than the above answers. – Nicholas Stommel Aug 09 '21 at 19:31
8
SELECT *
FROM Product_sales
WHERE (
From_date >= '2013-08-19'
AND To_date <= '2013-08-23'
)
OR (
To_date >= '2013-08-19'
AND From_date <= '2013-08-23'
)
Community
  • 1
  • 1
Kiran K
  • 97
  • 1
  • 2
  • 1
    For inclusive intersection you will want to add one more OR clause to catch when the from_date is before the start and the to_date is after the end: OR ( To_date <= '2013-08-19' AND From_date >= '2013-08-23' ) – jhorback Apr 08 '14 at 12:40
6

Please try:

DECLARE @FrmDt DATETIME, @ToDt DATETIME
SELECT @FrmDt='2013-01-03', @ToDt='2013-01-09'

SELECT * 
FROM Product_sales 
WHERE (@FrmDt BETWEEN From_date AND To_date) OR 
    (@ToDt BETWEEN From_date AND To_date)
TechDo
  • 18,398
  • 3
  • 51
  • 64
5

This is easy, use this query to find select data from date range between two dates

select * from tabblename WHERE (datecolumn BETWEEN '2018-04-01' AND '2018-04-5')
F5 Buddy
  • 474
  • 4
  • 4
4

Just my 2 cents, I find using the "dd-MMM-yyyy" format safest as the db server will know what you want regardless of the regional settings on the server. Otherwise you could potentially run into issues on a server that has its date regional settings as yyyy-dd-mm (for whatsoever reason)

Thus:

SELECT * FROM Product_sales 
WHERE From_date >= '03-Jan-2013'
AND To_date <= '09-Jan-2013'

It's always worked well for me ;-)

KDT
  • 671
  • 1
  • 6
  • 15
4
select * 
from table 
where
( (table.EndDate > '2013-01-05') and (table.StartDate < '2013-01-07' )  )
Gestef
  • 128
  • 1
  • 8
3

This query will help you:

select * 
from XXXX
where datepart(YYYY,create_date)>=2013 
and DATEPART(YYYY,create_date)<=2014
consuela
  • 1,675
  • 6
  • 21
  • 24
Ritesh Yadav
  • 301
  • 1
  • 3
  • 8
3

Check this query, i created this query to check whether the check in date over lap with any reservation dates

SELECT * FROM tbl_ReservedRooms
WHERE NOT ('@checkindate' NOT BETWEEN fromdate AND todate
  AND '@checkoutdate'  NOT BETWEEN fromdate AND todate)

this will retrun the details which are overlaping , to get the not overlaping details then remove the 'NOT' from the query

anandd360
  • 298
  • 3
  • 14
2

This working on SQL_Server_2008 R2

Select * 
from Product_sales
where From_date 
between '2013-01-03' and '2013-01-09'
I_Valchev
  • 45
  • 3
2
SELECT NULL  
    FROM   HRMTable hm(NOLOCK)  
    WHERE  hm.EmployeeID = 123
        AND (  
                (  
                    CAST(@Fromdate AS date) BETWEEN CAST(hm.FromDate AS date)  
                        AND CAST(hm.ToDate AS date)  
                )  
                OR (  
                    CAST(@Todate AS date) BETWEEN CAST(hm.FromDate AS date)  
                        AND CAST(hm.ToDate AS date)  
                   )  
                ) 
         )
Yurets
  • 3,999
  • 17
  • 54
  • 74
2

You can also try using following fragments:

select  * from  Product_sales 
where  From_date  >= '2013-01-03' and game_date  <= '2013-01-09'
rashedcs
  • 3,588
  • 2
  • 39
  • 40
1

Here is a query to find all product sales that were running during the month of August

  • Find Product_sales there were active during the month of August
  • Include anything that started before the end of August
  • Exclude anything that ended before August 1st

Also adds a case statement to validate the query

SELECT start_date, 
       end_date, 
       CASE 
         WHEN start_date <= '2015-08-31' THEN 'true' 
         ELSE 'false' 
       END AS started_before_end_of_month, 
       CASE 
         WHEN NOT end_date <= '2015-08-01' THEN 'true' 
         ELSE 'false' 
       END AS did_not_end_before_begining_of_month 
FROM   product_sales 
WHERE  start_date <= '2015-08-31' 
       AND end_date >= '2015-08-01' 
ORDER  BY start_date; 
jspooner
  • 10,975
  • 11
  • 58
  • 81
1
DECLARE @monthfrom int=null,
@yearfrom int=null,
@monthto int=null,
@yearto int=null,
@firstdate DATE=null,
@lastdate DATE=null

SELECT @firstdate=DATEADD(month,@monthfrom-1,DATEADD(year,@yearfrom-1900,0)) /*Setting First Date using From Month & Year*/
SELECT @lastdate= DATEADD(day,-1,DATEADD(month,@monthto,DATEADD(year,@yearto-1900,0)))/*Setting Last Date using From Month & Year*/

SELECT *  FROM tbl_Record
WHERE  (DATEADD(yy, Year - 1900, DATEADD(m, Month - 1, 1 - 1)) BETWEEN CONVERT(DATETIME, @firstdate, 102) AND 
CONVERT(DATETIME, @lastdate, 102))
Code
  • 679
  • 5
  • 9
-1

You should compare dates in sql just like you compare number values,

SELECT * FROM Product_sales
WHERE From_date >= '2013-01-01' AND To_date <= '2013-01-20'
Adeel Ahmed
  • 1,591
  • 8
  • 10
-1

this is easy, use this query to find what you want.

select * from Product_Sales where From_date<='2018-04-11' and To_date>='2018-04-11'
Abdirazack
  • 43
  • 1
  • 2
  • 11