Dagoosh!

Randomsauce

SQL DATEDIFF Magic: Yesterday, This Week, This Month and More

Posted Thu, Jun 25, 2009

I have never claimed to be a SQL magician.  I say that I have functional SQL skills.  If I need to make something happen, I can make it happen.  It may not always be the best solution up front, but it works.  From there, I improve on it as I go.  Which, really, is why I love what I do.  There is always a better way to do it.  Up until today, to select results based on a date or date range I used something along the lines of

 

 WHERE CreateDate >= DATEADD( d-1GETDATE() ) AND CreateDate < GETDATE()
 

Which, again, functions but as I learned today, may not be the best way to get a result set from yesterday or the last x amount of days.  Using DATEDIFF we can make some magic happen:

 

EDIT: The much more brilliant folks than me over at reddit have pointed out that I am an idiot and this is far less efficient. So, even though its fun and different, I am clearly in the wrong.

 

Limit results to yesterday:

 

 WHERE DATEDIFF( dCreateDateGETDATE() ) = 1
 

Esentially this is saying that if the CreateDate is one day before the current date (GETDATE()) than give me that result set.  

 

Using this same logic we can say last 7 days:

 

 WHERE DATEDIFF( dCreateDateGETDATE() ) < 7
 

Last 30 Days:

 

 WHERE DATEDIFF( dCreateDateGETDATE() ) < 30 
 

Or, to be more exact we can say this month, this week, this year:

 

 WHERE DATEDIFF( mCreateDateGETDATE() ) = 0
 WHERE DATEDIFF( wwCreateDateGETDATE() ) = 0
 WHERE DATEDIFF( yyCreateDateGETDATE() ) = 0 

 

Let's add one more yet: last month, last week, last year:

 

 WHERE DATEDIFF( mCreateDateGETDATE() ) = 1
 WHERE DATEDIFF( wwCreateDateGETDATE() ) = 1

 WHERE DATEDIFF( yyCreateDateGETDATE() ) = 1  
 

Tagged datediff dateadd date range sql

More from Dagoosh!
Shakira

Midway's The GRID: What You Get

Ode to the McGriddle

Pears Before Twitter

Google: Press Enter to Search

© 1999 - 2024 Dagoosh! LLC