Datetime in where clause - sql

How can I select 12/20/2008 in where clause of sql?
The server is SQL server 2005.
select * from tblErrorLog
where errorDate = '12/20/2008'

WHERE datetime_column >= '20081220 00:00:00.000'
AND datetime_column < '20081221 00:00:00.000'

First of all, I'd recommend using the ISO-8601 standard format for date/time - it works regardless of the language and regional settings on your SQL Server. ISO-8601 is the YYYYMMDD format - no spaces, no dashes - just the data:
select * from tblErrorLog
where errorDate = '20081220'
Second of all, you need to be aware that SQL Server 2005 DATETIME always includes a time. If you check for exact match with just the date part, you'll get only rows that match with a time of 0:00:00 - nothing else.
You can either use any of the recommend range queries mentioned, or in SQL Server 2008, you could use the DATE only date time - or you could do a check something like:
select * from tblErrorLog
where DAY(errorDate) = 20 AND MONTH(errorDate) = 12 AND YEAR(errorDate) = 2008
Whichever works best for you.
If you need to do this query often, you could either try to normalize the DATETIME to include only the date, or you could add computed columns for DAY, MONTH and YEAR:
ALTER TABLE tblErrorLog
ADD ErrorDay AS DAY(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorMonth AS MONTH(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorYear AS YEAR(ErrorDate) PERSISTED
and then you could query more easily:
select * from tblErrorLog
where ErrorMonth = 5 AND ErrorYear = 2009
and so forth. Since those fields are computed and PERSISTED, they're always up to date and always current, and since they're peristed, you can even index them if needed.

You don't say which database you are using but in MS SQL Server it would be
WHERE DateField = {d '2008-12-20'}
If it is a timestamp field then you'll need a range:
WHERE DateField BETWEEN {ts '2008-12-20 00:00:00'} AND {ts '2008-12-20 23:59:59'}

Assuming we're talking SQL Server DateTime
Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:
errorDate BETWEEN '12/20/2008' AND '12/21/2008'
My preferred method for a time range like that is:
'20081220' <= errorDate AND errordate < '20081221'
Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)

Use a convert function to get all entries for a particular day.
Select * from tblErrorLog where convert(date,errorDate,101) = '12/20/2008'
See CAST and CONVERT for more info

select * from tblErrorLog
where errorDate BETWEEN '12/20/2008' AND DATEADD(DAY, 1, '12/20/2008')

Use below query for clear understanding
/****** Script for SelectTopNRows command from SSMS ******/
SELECT *
FROM [dbo].[PublishedInfo]
where PublishedDate >= '2022-02-14T11:31:16.5299166+00:00'

Related

SQL Server: how to select records with specific date from datetime column

I have a table with one column dateX formatted as datetime and containing standard dates.
How can I select all records from this table where this dateX equals a certain date, e.g. May 9, 2014 ?
I tried the following, but this returns nothing even if I have several records with this date.
SELECT *
FROM dbo.LogRequests
WHERE (CONVERT(VARCHAR(10), dateX, 101) = '09/05/14')
Edit: In the database the above example looks as follows, using SQL 2012: 2014-05-09 00:00:00.000
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
For Perfect DateTime Match in SQL Server
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
This will select all the data between the 2 dates

Informix SQL Compare DateTime value on Where Statement

I have a datetime field called entrytimestamp, with content of the field is for example: 2014-01-07 16:20:00. I would like to query all the data that has entrytimestamp after 09:00:00 o'clock, regardless what date it was.
I have a prototype query:
select *
from trading
where to_char(entrytimestamp, "%H%M%S") >= "090000"
But I think it is logically a mistake, because it will compare the text string, not the sequence value. What is the right way to do it?
Use the EXTEND() function to extract the time part:
select *
from mytable
where extend(entrytimestamp, hour to second) > '09:00:00'
I dont know if it performs well,
but you could compare directly with the time portion of the datetime,
i think a cast here should perform pretty fast (just cuts off the date)
select *
from (select getdate() as mydatetime) as data
where cast(mydatetime as time) > cast('09:00:00' as time)
EDIT, just noticed this was for Informix SQL, so not sure it works then, Sorry

filter DateTime field with now as reference in WHERE clause

I am trying to build a vb.net application with a where clause to filter data using a DateTime field.
My table contains 5 fields and more than 10000 rows. I wanna use a DateTime field to find all the rows older than 7 years from now.
But this script will be re-used many times. So I don't wanna use this kind of where clause cause I don't wanna need to modify the where clause every time I wanna run the application :
select * from myTable WHERE myDateTimeField < '2006-09-07 00:00:00.000'
I'd like to find a way to write a where clause like this :
select * from myTable WHERE myDateTimeField "is older than 7 years from NOW"
I don't use VB.net very often (as you can see), so this thing is really bugging me
Just make use of DateTime:
Dim dateTime As DateTime
dateTime = DateTime.Now.AddYears(-7);
When you're building your SQL string just call ToString on your date (you can obviously format it however you need):
dateTime.ToString("MM/dd/yyyy");
SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETDATE())
That is if the data in the myDateTimeField is in the same local time zone of the sql server.
If your data is in UTC (which it often should be), then use:
SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETUTCDATE())
i think better would be provided you have SQL Server
strQuery = "select * from myTable WHERE myDateTimeField
<= DATEADD(YEAR, -7, GETDATE())"
What you are looking for is a DSL for datetime. Check out this blog post to get some ideas.
http://leecampbell.blogspot.com/2008/11/how-c-30-helps-you-with-creating-dsl.html
Good Luck
P.S.
If you need help translating it into vb.net just submit a comment.

SQL Server DateTime and SQL

I am having trouble with the following simple query
SELECT * FROM users WHERE Created = '28/02/2013'
The issue is the column CREATED is a datetime datatype, so the query executes fine as long as the timestamp is 0:00:0, if the time stamp is set to say 12:00, then the query does not return a result set.
Any idea why?
Thanks
Because you are not specifying the time, so it assumes that you are doing:
SELECT * FROM users WHERE Created = '28/02/2013 00:00:00'
If you want the whole day, then you need a range of times:
SELECT *
FROM users
WHERE Created >= '20130228' AND Created < '20130301'
Also, please use non ambiguous format for dates ('YYYYMMDD') instead of other formats.
SELECT * FROM users WHERE CAST(Created AS DATE) = '28/02/2013'
will fix it, but be careful, it disables indexes
SELECT * FROM users WHERE Created BETWEEN '28/02/2013 00:00' AND '28/02/2013 23:59'
And this will use index
If you don't need to consider time: try to convert created field to date and then compare as;
SELECT * FROM users WHERE convert(date,Created) = '28/02/2013'
--this would be even better with iso date format (not culture specific)
SELECT * FROM users WHERE convert(date,Created) = '20130228' --yyyymmdd format
You have to convert the column into date and then compare
SELECT * FROM users WHERE CONVERT(VARCHAR(11), Created, 106) = '28 Feb 2013'

How to get one day ahead of a given date?

Suppose I have a date 2010-07-29. Now I would like to check the result of one day ahead. how to do that
For example,
SELECT *
from table
where date = date("2010-07-29")
How to do one day before without changing the string "2010-07-29"?
I searched and get some suggestion from web and I tried
SELECT *
from table
where date = (date("2010-07-29") - 1 Day)
but failed.
MySQL
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATE_SUB('2010-07-29', INTERVAL 1 DAY)
AND '2010-07-29'
Change DATE_SUB to DATE_ADD if you want to add a day (and reverse the BETWEEN parameters).
SQL Server
SELECT *
FROM TABLE t
WHERE t.date BETWEEN DATEADD(dd, -1, '2010-07-29')
AND '2010-07-29'
Oracle
SELECT *
FROM TABLE t
WHERE t.date BETWEEN TO_DATE('2010-07-29', 'YYYY-MM-DD') - 1
AND TO_DATE('2010-07-29', 'YYYY-MM-DD')
I used BETWEEN because the date column is likely DATETIME (on MySQL & SQL Server, vs DATE on Oracle), which includes the time portion so equals means the value has to equal exactly. These queries give you the span of a day.
If you're using Oracle, you can use the + and - operators to add a number of days to a date.
http://psoug.org/reference/date_func.html
Example:
SELECT SYSDATE + 1 FROM dual;
Will yield tomorrow's date.
If you're not using Oracle, please tell use what you ARE using so we can give better answers. This sort of thing depends on the database you are using. It will NOT be the same across different databases.
Depends of the DateTime Functions available on the RDBMS
For Mysql you can try:
mysql> SELECT DATE_ADD('1997-12-31',
-> INTERVAL 1 DAY);
mysql> SELECT DATE_SUB('1998-01-02', INTERVAL 31 DAY);
-> '1997-12-02'
If youre using MSSQL, you're looking for DateAdd() I'm a little fuzzy on the syntax, but its something like:
Select * //not really, call out your columns
From [table]
Where date = DateAdd(dd, -1, "2010-07-29",)
Edit: This syntax should be correct: it has been updated in response to a comment.
I may have the specific parameters in the wrong order, but that should get you there.
In PL SQL : select sysdate+1 from dual;