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

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

Related

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?
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();

Most optimal way to get all records IN previous month

In the past I have always used:
WHERE DATEDIFF(m, [DATE_COL], GETDATE()) = 1
which gets me ALL the record that occurred in the PREVIOUS month. For example if I ran this query, it will get me all records which occurred in January.
However I am currently working with a significantly bigger table and if I use the above query, it takes almost 30 minutes for it to load. However, if I use something like
WHERE [SettlementDate] >= DateAdd(DAY, -31, GETDATE())
it will usually run in under 10 seconds.
My question is:
How can I get the same result as WHERE DATEDIFF(m, [DATE_COL], GETDATE()) = 1 without the crazy increase in processing time?
Thank you!
Your query is slow because when you do DATEDIFF(m, [DATE_COL], GETDATE()) it can not use any indexes on the [Date_Col].
Anyway you can use the following where clause, this will use indexes on the [SettlementDate] and hopefully it should perform a lot better than the DATEDIFF() function.
WHERE [SettlementDate] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
AND [SettlementDate] < DATEADD(DAY,1,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1))
The problem is that you have a function call and the query optimizer cannot see inside functions. That means, it cannot decide if use an index or not. In that case it reads the whole table that can take very long time.
I suggest you to use variables and I believe your query will get better result:
declare #From datetime -- choose the same type as your SettlementDate column
set #From = DateAdd(DAY, -31, GETDATE()) -- compute the starting date
select * from yourTable where SettlementDate >= #From
In that case the sql server will know that you want to compare your SettlementDate value with a date and there is nothing other that has to compute. If you have index in that column, it will use that.
Additional information about SARGable queries: https://www.codeproject.com/Articles/827764/Sargable-query-in-SQL-server

Get all records that don't exist in a subquery

I'm trying to return all records that are not in the subquery (of which there should be a lot) but I get no results.
I want all of the records where the LastAccesstime (datetime) doesn't have an access time which is within 24hours of GETDATE(). Does that make sense? I tried WHERE NOT IN as well and got the same results.
SELECT Firstname, Surname, LastAccesstime
from Users
WHERE NOT EXISTS (
SELECT Firstname, Surname, LastAccesstime from Users
WHERE (LastAccesstime) >= DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
AND (LastAccesstime) < DATEADD(day, DATEDIFF(day, 0, GETDATE())+1, 0)
)
The table consists of many other fields including a UserID but this isn't important for my question as once I'm able to return the correct result set I should be able to do what I need to do.
Thanks
Assuming that lastaccesstime is always in the past then
SELECT * FROM Users WHERE DATEDIFF(HOUR, ISNULL(lastaccesstime, GETDATE() - 2), GETDATE()) > 24
Richard's answer is definitely on the right track. However, datediff() is not the right function to use. It counts the number of boundaries between two date/time values. So, "2016-01-01 23:59" and "2016-01-02 00:01" are one day apart (because of the midnight boundary).
In SQL Server, it is better to use direct comparisons on the dates:
SELECT u.*
FROM users u
WHERE u.lastaccesstime < DATEADD(day, -1, GETDATE());
This also has the advantage that it can take advantage of an index on lastaccesstime.
Note:
Your query suggests that you don't want to include the time component for GETDATE(). If so, just cast to a date data type:
SELECT u.*
FROM users u
WHERE u.lastaccesstime < DATEADD(day, -1, CAST(GETDATE() as DATE));

Is there an equivalent to sysdate-1/24 in SQL server?

I've tried looking around for this but I can't find an answer that seems to work with the code I'm using. Basically, the below query searches on any result from the current date. I'm trying to make it so it will search only on the last hour.
In oracle I could do this using sysdate-1/24, is there a simple equivalent within SQL server? Bearing in mind I'm already using cast to get the current sysdate.
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(convert(varchar(10), getdate(), 110) as datetime)
and m_record_server is not null
You can use:
getdate() - 1.0/24
SQL Server allows you to use such arithmetic on datetime.
The more common way would be:
dateadd(hour, -1, getdate())
In your query, you do not need to cast to a string at all:
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= getdate() - 1.0/24 and m_record_server is not null;
If you want the date that was there one hour ago (which seems to be the intent of the code, if not the rest of the question):
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(getdate() - 1.0/24 as date) and m_record_server is not null;

Best way to check for current date in where clause of sql query

I'm trying to find out the most efficient (best performance) way to check date field for current date. Currently we are using:
SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received BETWEEN DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0)
AND DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1))
WHERE
DateDiff(d, Received, GETDATE()) = 0
Edit: As lined out in the comments to this answer, that's not an ideal solution. Check the other answers in this thread, too.
If you just want to find all the records where the Received Date is today, and there are records with future Received dates, then what you're doing is (very very slightly) wrong... Because the Between operator allows values that are equal to the ending boundary, so you could get records with Received date = to midnight tomorrow...
If there is no need to use an index on Received, then all you need to do is check that the date diff with the current datetime is 0...
Where DateDiff(day, received, getdate()) = 0
This predicate is of course not SARGable so it cannot use an index...
If this is an issue for this query then, assuming you cannot have Received dates in the future, I would use this instead...
Where Received >= DateAdd(day, DateDiff(Day, 0, getDate()), 0)
If Received dates can be in the future, then you are probably as close to the most efficient as you can be... (Except change the Between to a >= AND < )
If you want performance, you want a direct hit on the index, without any CPU etc per row; as such, I would calculate the range first, and then use a simple WHERE query. I don't know what db you are using, but in SQL Server, the following works:
// ... where #When is the date-and-time we have (perhaps from GETDATE())
DECLARE #DayStart datetime, #DayEnd datetime
SET #DayStart = CAST(FLOOR(CAST(#When as float)) as datetime) -- get day only
SET #DayEnd = DATEADD(d, 1, #DayStart)
SELECT COUNT(Job) AS Jobs
FROM dbo.Job
WHERE (Received >= #DayStart AND Received < #DayEnd)
that's pretty much the best way to do it.
you could put the DATEADD(d, DATEDIFF(d, 0, GETDATE()), 0) and DATEADD(d, DATEDIFF(d, 0, GETDATE()), 1) into variables and use those instead but i don't think that this will improve performance.
I'm not sure how you're defining "best" but that will work fine.
However, if this query is something you're going to run repeatedly you should get rid of the get_date() function and just stick a literal date value in there via whatever programming language you're running this in. Despite their output changing only once every 24 hours, get_date(), current_date(), etc. are non-deterministic functions, which means that your RDMS will probably invalidate the query as a candidate for storing in its query cache if it has one.
How 'bout
WHERE
DATEDIFF(d, Received, GETDATE()) = 0
I would normally use the solution suggested by Tomalak, but if you are really desperate for performance the best option could be to add an extra indexed field ReceivedDataPartOnly - which would store data without the time part and then use the query
declare #today as datetime
set #today = datediff(d, 0, getdate())
select
count(job) as jobs
from
dbo.job
where
received_DatePartOnly = #today
Compare two dates after converting into same format like below.
where CONVERT(varchar, createddate, 1) = CONVERT(varchar, getdate(), 1);