Skip to content
Advertisement

SQL: Trying to select records 7 days before date

I have a table with a date field called oppo_installdate. This is a date in the future, and I basically want to select records where this date is 7 or fewer days from the current date. I have tried to do this with the query below but it is older returning dates from 2019 as well, and I’m not sure why that’s happening.

select * from [CRM_Test].[dbo].[Opportunity]
where (GETDATE() >= DATEADD(day,-7, oppo_installdate))

Could anyone suggest a better way of doing this?

Advertisement

Answer

Whenever you’re using a WHERE always try to apply any functions to constants, or other functions, never your columns. DATEADD(day,-7, oppo_installdate) will make the query non-SARGable, and could slow it down as any indexes won’t be able to be used.

It seems like what you simply want is:

SELECT *
FROM [dbo].[Opportunity]
WHERE oppo_installdate >= DATEADD(DAY, 7, GETDATE());

Note that GETDATE returns a datetime, so if you want from midnight 7 days ago, you would use CONVERT(date,GETDATE()) (or CAST(GETDATE() AS date)).

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement