Query data from previous day when month/year changes - sql

In a SQL Server query, I am currently using the clause
WHERE
DAY(trade_date) = DAY(GETDATE()) - 1
AND MONTH(trade_date) = MONTH(GETDATE())
AND YEAR(trade_date) = YEAR(GETDATE())
to query my data from the previous day.
It is working fine right now but my question is if, for example, on 8/1/2021, SQL Server will try to get data from 8/0/2021 or if it will know to get data from 7/31/2021.
If this query won't work what could I use instead? Thanks!

I would recommend using proper date comparison logic - instead of breaking it down to day, month and year. Also, it is recommended to use proper date arithmetic functions like DATEADD instead of just - 1 on your date values (never sure what that -1 stands for: minus one day? Week? Month? Hour?).
And lastly - I would also recommend using SYSDATETIME() instead of GETDATE() since the latter always returns a DATETIME datatype - which should be on its way out, and you should use DATE (if you don't need to time portion), or DATETIME2(n) (if you do need the time portion) since those are more efficient and have fewer limitations compared to DATETIME.
If your trade_date is a DATE column (as it probably should be), just use:
WHERE
trade_date = DATEADD(DAY, -1, SYSDATETIME())
and if it's not a DATE - just cast it to a date as needed:
WHERE
CAST(trade_date AS DATE) = DATEADD(DAY, -1, CAST(SYSDATETIME() AS DATE))

Related

SQL Server : Comparing Time

I am trying to compare time in my SQL query. However, when I run the query, I get zero result but I can see that in the table, there are records that should appear.
The query is as such:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '26/08/2015'
AND StartTime <= CONVERT(varchar(5), GETDATE(), 108)
The StartDate is stored in the database as YYYY-MM-DD and it seems to work fine when I query only with the date.
However, when I add the StartTime is when things don't work. StartTime stores the value in the 24 hour clock format.
What am not doing right?
Thanks
Use a correct datetime format:
SELECT *
FROM dbo.Alarms
WHERE StartDate <= '2015-08-26' AND StartTime <= cast(GETDATE() as date)
Don't compare date/time values as strings. The data types are built into the language. Use them.
I have not explicitly used this scenario but comparing dates can be a problem depending on how the fields are compared.
eg: '28/07/2015' is not less than your startdate as 28 > 26.
You could try comparing dates reformatted into a YYYYMMDD format.
Cheers.

query to select data from this day [duplicate]

This question already has answers here:
In SQL Server, what is the best way to filter items for an entire day
(3 answers)
Closed 8 years ago.
I have a database table that has Datelogged columns from type Datetime (Sql server 2008 r2)
The Datelogged value is like this 2014-10-22 12:57:36.583
I want to do a query to select all the rows that its date is today (I care about year, month, and day) but not (hour, second.)
This is my query
string query = "SELECT * FROM Orders WHERE PrintTime is NULL WHERE Datelogged = #Datelogged";
but I didn't know what should I do to tell the query to compare just on year-month-day
Based on #Aaron Bertrand comment
It appears that it is better to use a Date Range from current day midnight (00:00:00) to < tomorrow at midnight.
Query copied from his comment.
DateLogged >= CONVERT(DATE, #DateLogged) AND
DateLogged < DATEADD(DAY, 1, CONVERT(DATE, #DateLogged))
Also see: Bad habits to kick : mis-handling date / range queries By Aaron Bertrand
(Old Answer)
You can use CONVERT(DATE, Datelogged) to get Date part without time.
"SELECT * FROM Orders WHERE PrintTime is NULL AND CONVERT(DATE, Datelogged) = #Datelogged"
Make sure you pass the parameter value using Date property in C# like:
cmd.Paramaters.AddWithValue("#Datelogged", DateTime.Today);// or DateTime.Now.Date
Also make sure to remove multiple WHERE from your query and use AND or OR to combine two conditions depending on your requirement.
Get the minimum date time range for current date and maximum date time range for today. Then, compare it with the logged date value.
Conversion operator on any table column adds extra conversion overhead and leads to inefficient use of index. Should be avoided when possible.
SELECT * FROM Orders
WHERE PrintTime is NULL
AND (Datelogged > dateadd(DD, -1, cast( GETDATE() as date)) AND Datelogged < dateadd(DD, 1, cast( GETDATE() as date)));

SQL automatic date range using DateSerial function

We've been using MS Access, with the following syntax for MTD Data that works for us:
Between DateSerial(Year(Date()),Month(Date()),1)
And DateSerial(Year(Date()),Month(Date())+1,0)
We need to transition the above logic to SQL/SSRS for automatic emailed reports, but I cannot get this DateSerial logic to work with SQL.
In the Filter field of the SQL query, I can successfully use BETWEEN '8/1/2014' AND '8/31/2014' for MTD data, but would like to have a DateSerial logic applied so that reports don't need to be created for every month, quarter, year, etc.
When trying to use the DateSerial function, we get the error "Invalid or missing Expression". I've seen a few topics on this that Parameters are required, but really believe that this is a simple syntax issue for the filter field, since actual dates work with the BETWEEN command.
There are several different ways to get this. Here is just one way.
Get todays date. In this case 8/27/2014
Declare #Today date = cast(getdate() as date)
Get the first of the month, 26 days in the past
Declare #StartDate date = dateadd(d, -1 * (day(#Today) - 1), #Today)
select #Today, #StartDate
You can use the function CONVERT:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Or the function DATEFROMPARTS if you are using SQL Server 2012:
http://msdn.microsoft.com/en-us/library/hh213228.aspx
Or DATEADD:
select DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0); -- first day of current month
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE()), -1) -- last day of current month
This last one I took from: https://stackoverflow.com/a/11746042/1274092
See mine at:
http://sqlfiddle.com/#!3/d41d8/38333
This has been resolved. The ODBC driver does not apparently play well with SSRS. The DateSerial command would not work within the query itself. The workaround was to add the filter to the Dataset. This syntax is what works, but again only in the Dataset filter: [expression] Between [first value box] =DateSerial(Year(Now()),1,1) [second value box] =DateSerial(Year(Now()),12,31)
This gives us the YTD reporting data that we require.

How do you extract just date from datetime in T-Sql?

I am running a select against a datetime column in SQL Server 2005. I can select only the date from this datetime column?
Best way is:
SELECT DATEADD(day, DATEDIFF(Day, 0, #ADate), 0)
This is because internally, SQL Server stores all dates as two integers, of which the first one is the ****number of days*** since 1 Jan 1900. (the second one is the time portion, stored as the number of seconds since Midnight. (seconds for SmallDateTimes, or milleseconds for DateTimes)
Using the above expression is better because it avoids all conversions, directly reading and accessing that first integer in a dates internal representation without having to perform any processing... the two zeroes in the above expression (which represent 1 Jan 1900), are also directly utilized w/o processing or conversion, because they match the SQL server internal representation of the date 1 jan 1900 exactly as presented (as an integer)..
*NOTE. Actually, the number of date boundaries (midnights) you have to cross to get from the one date to the other.
Yes, by using the convert function. For example:
select getdate(), convert(varchar(10),getdate(),120)
RESULTS:
----------------------- ----------
2010-05-21 13:43:23.117 2010-05-21
You can use the functions:
day(date)
month(date)
year(date)
Also the Datepart() function might be of some use:
http://msdn.microsoft.com/en-us/library/ms174420(SQL.90).aspx
DECLARE #dToday DATETIME
SET #dToday = CONVERT(nvarchar(20), GETDATE(), 101)
SELECT #dToday AS Today
This returns today's date at 12:00am : '2010-05-21 00:00:00.000'
Then you can use the #dToday variable in a query as needed
CONVERT (date, GETUTCDATE())
CONVERT (date, GETDATE())
CONVERT (date, '2022-18-01')
I don't know why the others recommend it with varchar(x) tbh.
https://learn.microsoft.com/de-de/sql/t-sql/functions/getdate-transact-sql

Compare DATETIME and DATE ignoring time portion

I have two tables where column [date] is type of DATETIME2(0).
I have to compare two records only by theirs Date parts (day+month+year), discarding Time parts (hours+minutes+seconds).
How can I do that?
Use the CAST to the new DATE data type in SQL Server 2008 to compare just the date portion:
IF CAST(DateField1 AS DATE) = CAST(DateField2 AS DATE)
A small drawback in Marc's answer is that both datefields have been typecast, meaning you'll be unable to leverage any indexes.
So, if there is a need to write a query that can benefit from an index on a date field, then the following (rather convoluted) approach is necessary.
The indexed datefield (call it DF1) must be untouched by any kind of function.
So you have to compare DF1 to the full range of datetime values for the day of DF2.
That is from the date-part of DF2, to the date-part of the day after DF2.
I.e. (DF1 >= CAST(DF2 AS DATE)) AND (DF1 < DATEADD(dd, 1, CAST(DF2 AS DATE)))
NOTE: It is very important that the comparison is >= (equality allowed) to the date of DF2, and (strictly) < the day after DF2. Also the BETWEEN operator doesn't work because it permits equality on both sides.
PS: Another means of extracting the date only (in older versions of SQL Server) is to use a trick of how the date is represented internally.
Cast the date as a float.
Truncate the fractional part
Cast the value back to a datetime
I.e. CAST(FLOOR(CAST(DF2 AS FLOAT)) AS DATETIME)
Though I upvoted the answer marked as correct. I wanted to touch on a few things for anyone stumbling upon this.
In general, if you're filtering specifically on Date values alone. Microsoft recommends using the language neutral format of ymd or y-m-d.
Note that the form '2007-02-12' is considered language-neutral only
for the data types DATE, DATETIME2, and DATETIMEOFFSET.
To do a date comparison using the aforementioned approach is simple. Consider the following, contrived example.
--112 is ISO format 'YYYYMMDD'
declare #filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
CONVERT(char(8), OrderDate, 112) = #filterDate
In a perfect world, performing any manipulation to the filtered column should be avoided because this can prevent SQL Server from using indexes efficiently. That said, if the data you're storing is only ever concerned with the date and not time, consider storing as DATETIME with midnight as the time. Because:
When SQL Server converts the literal to the filtered column’s type, it
assumes midnight when a time part isn’t indicated. If you want such a
filter to return all rows from the specified date, you need to ensure
that you store all values with midnight as the time.
Thus, assuming you are only concerned with date, and store your data as such. The above query can be simplified to:
--112 is ISO format 'YYYYMMDD'
declare #filterDate char(8) = CONVERT(char(8), GETDATE(), 112)
select
*
from
Sales.Orders
where
OrderDate = #filterDate
You can try this one
CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000')
I test that for MS SQL 2014 by following code
select case when CONVERT(DATE, GETDATE()) = CONVERT(DATE,'2017-11-16 21:57:20.000') then 'ok'
else '' end
You may use DateDiff and compare by day.
DateDiff(dd,#date1,#date2) > 0
It means #date2 > #date1
For example :
select DateDiff(dd, '01/01/2021 10:20:00', '02/01/2021 10:20:00')
has the result : 1
For Compare two date like MM/DD/YYYY to MM/DD/YYYY .
Remember First thing column type of Field must be dateTime.
Example : columnName : payment_date dataType : DateTime .
after that you can easily compare it.
Query is :
select * from demo_date where date >= '3/1/2015' and date <= '3/31/2015'.
It very simple ......
It tested it.....