I am pretty new to SQL and hope someone here can help me with this:
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
Many thanks for any help with this, Mike.
In MySQL, use the DATE() function to retrieve the date from a datetime or timestamp value. This function takes only one argument – either an expression which returns a date/datetime/ timestamp value or the name of a timestamp/datetime column. (In our example, we use a column of the timestamp data type.)
SELECT blah FROM tbl WHERE DATE(some_datetime_field) = '2012-04-02'; That will select any rows such that the date part of some_datetime_field is 4 Apr 2012.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With