views:

43

answers:

2

hi,

in my web application i am displaying videos of user, I want to display the videos which are between 30 days only. Videos that are uploaded last 30 days only. i write query like this but it is not working fine..

  select * 
    from videos 
   where posteddate between getdate()-30 and getdate()  
order by posteddate desc

can u help me

+2  A: 

Use the DATEADD function:

WHERE posteddate BETWEEN DATEADD(dd, -30, GETDATE())
                     AND GETDATE()

You are aware that GETDATE() includes the time portion?

OMG Ponies
You could still do WHERE posteddate >= DATEADD(dd, -30, GETDATE()) which reduces the extra call to GETDATE() and be slightly more efficient
Justin King
How is what you wrote semantically different from the OP's query?
Gabe
A: 

In this scenario you could just do

where posteddate >= getdate()-30

Justin King
Also in SQL 2008 you could do this cast(GETDATE() - 30 as date) to remove the time as getdate() will return the timeofdayor even in SQL 2005 you could do cast(GETDATE() - 30 as varchar(12)) and that would still do a correct compare from midnight onwards
Justin King
`getdate` doesn't return a number; it returns a date/time. At that point you have to ask "minus 30 what?"
cHao
@cHao: Standard SQL says (and SQL Server agrees) that it's "minus 30 days". It *should* work.
Dean Harding
the - 30 is days. You could use DateAdd if you like but I've never had a problem with this before.If you are unsure what it would return you can always do SELECT Getdate() - 30
Justin King
@Dean Harding: At first glance, i don't see anything saying that. *Everything* i find says "Use `DATEADD`".
cHao
@all: Why + and - are bad for date math: http://www.xaprb.com/blog/2006/12/20/why-i-use-explicit-date-math-in-sql/
cHao
You are talking about MySQL in that link which is totally different to SQL Server. Apples and Oranges. Go with what you feel comfortable with as there are always more than one way to skin a cat.
Justin King
cHao: I don't know about the SQL standard, but in SQL Server you're adding days. `GETDATE() + 1` is a day from now; `GETDATE() - .25` is 6 hours ago; and so on. I use this all the time.
Gabe