Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 800
Mike Avatar asked Jun 12 '14 19:06

Mike


People also ask

How do I select a date from a timestamp in SQL?

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

How can I separate date and datetime in SQL?

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.


2 Answers

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';
like image 171
Gordon Linoff Avatar answered Oct 18 '22 05:10

Gordon Linoff


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
like image 34
Ravi Shrimali Avatar answered Oct 18 '22 06:10

Ravi Shrimali