SQL: Trying to select records 7 days before date - sql

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?

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)).

Use below condition-
select * from [CRM_Test].[dbo].[Opportunity]
where oppo_installdate>= DATEADD(day,-7, GETDATE()) and oppo_installdate<=getdate()

This should give you the records where oppo_installdate is 7 or fewer days away from now:
SELECT *
FROM [dbo].[Opportunity]
WHERE oppo_installdate <= DATEADD(DAY, 7, GETDATE())
and oppo_installdate > getdate();

Related

Date difference, two variables in SQL

The problem: I am writing a query to check if the date from a given column is 6 weeks from another column.
I have tried DATEDIFF for other date checks, but that has been with a fixed date as one of the variables. I have two different variables in this case.
My code attempt:
SELECT *
DATEDIFF(d, ifc_forecast, date_complete)
FROM ifc_file
ORDER BY
ifc_forecast DESC
This could be as simple as:
SELECT DATEDIFF(wk, date1, date2) FROM table...
provided that your fields/variables are proper datetime columns.
Reference: DATEDIFF (Transact-SQL)
But probably you'll get a more accurate result by counting the number of days instead, so:
SELECT DATEDIFF(day, date1, date2) FROM table...
6 weeks = 42 days.

SQL WHERE clause to pick data for last 7 days

I want to build a view on the server with a SELECT statement and pick all records that are created at the last 7 days?
Original creation_date field is in varchar like '18/11/08' and I use the CONVERT(datetime, creation_date,11) to convert it into 2018-11-08 00:00:00.000, but I don't know how to do in the WHERE clause, so it only selects all records created for last 7 days.
use where clause like below
select t.* from your_table t
where CONVERT(datetime, creation_date,11)>= DATEADD(day,-7, GETDATE())
In order to get the best performance, you should keep the calculation away from the column:
SELECT *
FROM <YourTable>
WHERE creation_date >= CONVERT(char(8), DATEADD(day,-7, GETDATE()), 11)
This will handle it well because of the format of the varchar - yy/mm/dd. Would not have worked with all formats
The best thing to do is store dates properly to begin with - in a column with a Date data type.
Assuming you can't change the database structure, you can use DateDiff with GetDate():
SELECT <ColumnsList>
FROM <TableName>
WHERE DATEDIFF(DAY, CONVERT(datetime, creation_date,11), GETDATE()) <= 7
Of course, you need to replace the <ColumnsList> with the list of columns and <TableName> with the actual table name.

Recover data only from the previous day in a table in SQL Server

I need to retrieve data from a table that has date referenced only the previous day, I am trying to do with the query below but I am not getting:
SELECT
Log.ValorEntrada, Log.DataHoraEvento, Log.NumeroEntrada
FROM
Log
WHERE
Log.DataHoraEvento = (GETDATE()-1)
How can I get this result?
In SQL Server, GETDATE() has a time component. I would recommend:
WHERE Log.DataHoraEvento >= CAST(GETDATE()-1 as DATE) AND
Log.DataHoraEvento < CAST(GETDATE() as DATE)
This condition is "sargable", meaning that an index can be used. The following also is:
WHERE CONVERT(DATE, Log.DataHoraEvento) >= CONVERT(DATE, GETDATE())
Almost all functions prevent the use of indexes, but conversion/casting to a date is an exception.
Finally, if you don't care about indexes, you can also write this as:
WHERE DATEDIFF(day, Log.DataHoraEvento, GETDATE()) = 1
DATEDIFF() with day as the first argument counts the number of "day" boundaries between the two date/times. Everything that happened yesterday has exactly one date boundary.
If DataHoraEvento is a DATETIME, its likely that it has the full time, hence GETDATE()-1 isn't getting any matches. You should search for a range like this:
SELECT L.ValorEntrada, L.DataHoraEvento, L.NumeroEntrada
FROM dbo.[Log] L
WHERE L.DataHoraEvento >= CONVERT(DATE,DATEADD(DAY,-1,GETDATE()))
AND L.DataHoraEvento < CONVERT(DATE,GETDATE());
SELECT Log.ValorEntrada, Log.DataHoraEvento, Log.NumeroEntrada
FROM Log
WHERE Log.DataHoraEvento >= DATEADD(dd,DATEDIFF(dd,1,GETDATE()),0)
AND Log.DataHoraEvento < DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0)
You should also use SYSDATETIME() (if you on SQL Server 2008+) instead of GETDATE() as this gives you datetime2(7) precision.
You can try this :
MEMBER BETWEEN DATEADD(day, -2, GETDATE()) AND DATEADD(day, -1, GETDATE())

check if date time is of today after 8 am server

I have the following table
ID UpdatedDate
--- ------------
1 2013-03-04 08:05:07.203
2 2013-03-04 07:05:07.203
3 2013-03-05 10:05:07.203
Now I want to show records only which occur after 8.oo AM today only.
for that I am doing as following
select * from tab
where
LastUpdatedDate > GETDATE()
and datepart(hh, LastUpdatedDate) >= 8
the issue occurs if I run this query after the time mentioned in the updatedDate.
in that case LastUpdatedDate > GETDATE() fails and returns nothing.
Any idea on how to go about this issue?
select * from tab
where
convert(varchar(11),LastUpdatedDate,101) > convert(varchar(11),getdate(),101)
and
convert(varchar(11),LastUpdatedDate,108) >= '08:00:000'
101 - extract date part
108 - extract time part ( 24 hour clock format)
I know you've already accepted an answer, but doing this using string comparisons is a really bad idea - it precludes any possibility of using an index.
Instead, why not round the return value from GETDATE() to 08:00 today, and directly compare the LastUpdatedDate column to that:
select * from tab
where
LastUpdatedDate >=
DATEADD(day,DATEDIFF(day,'20010101',GETDATE()),'2001-01-01T08:00:00')
The DATEADD/DATEDIFF pair are used to do the rounding I've described. They work because of the fixed relationship between the two dates I'm using.
dateadd(day, datediff(day, 0, getdate()), 0) will give you the date of today with time part 00:00:00. Useut that the third parameter in dateadd(hour, 8, ... and you have a datetime value where the time is 08:00:00 that you can use to compare against your column.
Applying functions to columns should if possible always be avoided because that will make your query Non-Sargable.
select *
from tab
where UpdatedDate >= dateadd(hour, 8, dateadd(day, datediff(day, 0, getdate()), 0))

sql compare datetime today

I hope anyone can translate my abstract query.
I want to select * from TABLE where ( [MYDATETIMEROW] < (TODAY - 3 Days)).
Does I have to Convert, cast or use datepart or anything else?.. im confused.
Are there simple rules? I would'nt have problems to do that with linq but simple sql I learned just hardly.
Thank you and best regards.
In simple terms:
Select * from Table where MyDateTimeRow < dateadd(dd,-3,getdate())
But using getdate() will provide both a date and a time, experience says that this is unlikely to be exactly what you want - you might want to strip the time down and just consider the date portion
Select * From Table where MyDateTimeRow < dateadd(dd, datediff(dd, 0, getdate()) - 3, 0)
You want the DateAdd function to manipulate dates and the GetDate function to get the current date:
SELECT * FROM MyTable WHERE [MyDateTimeRow] < DateAdd(dd, -3, GetDate())