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

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

Related

How to SELECT between two dates in SQL Server

I need to give a select count in a table using the range of two dates, however my dates are in "yyyy-MM-dd" format, and when I execute the select SQL it returns the following error:
Converting a varchar data type to a datetime data type resulted in a value out of range
Here is the query I'm using:
SELECT COUNT(*) AS score
FROM requests
WHERE date_em BETWEEN '2019-04-01' AND '2019-04-30'
Table structure
date_em = DATETIME
Can someone help me?
My preferred method is:
SELECT COUNT(*) AS score
FROM requests
WHERE date_em >= '2019-04-01' AND
date_em < '2019-05-01'
This handles the time component and will make use of an index.
The following also works well in SQL Server:
SELECT COUNT(*) AS score
FROM requests
WHERE CONVERT(date, date_em) BETWEEN '2019-04-01' AND '2019-04-30'
In SQL Server, this will also use an index (if available). However, normally functions on columns preclude the use of an index, so I'm more hesitant about this approach.
have you try this
SELECT COUNT(*) AS score FROM requests WHERE date_em BETWEEN '2019-04-01 00:00' AND '2019-04-30 23:59'
add 00:00 and 23:59 to make it look like a DateTime.

SQL WHERE clause to pick data for last 7 days

I want to build a view on the server with a SELECT statement and pick all records that are created at the last 7 days?
Original creation_date field is in varchar like '18/11/08' and I use the CONVERT(datetime, creation_date,11) to convert it into 2018-11-08 00:00:00.000, but I don't know how to do in the WHERE clause, so it only selects all records created for last 7 days.
use where clause like below
select t.* from your_table t
where CONVERT(datetime, creation_date,11)>= DATEADD(day,-7, GETDATE())
In order to get the best performance, you should keep the calculation away from the column:
SELECT *
FROM <YourTable>
WHERE creation_date >= CONVERT(char(8), DATEADD(day,-7, GETDATE()), 11)
This will handle it well because of the format of the varchar - yy/mm/dd. Would not have worked with all formats
The best thing to do is store dates properly to begin with - in a column with a Date data type.
Assuming you can't change the database structure, you can use DateDiff with GetDate():
SELECT <ColumnsList>
FROM <TableName>
WHERE DATEDIFF(DAY, CONVERT(datetime, creation_date,11), GETDATE()) <= 7
Of course, you need to replace the <ColumnsList> with the list of columns and <TableName> with the actual table name.

Parsing date in sql query

I am using SQL Server 2005.
My Trade_Date column is of datatype datetime.
It has values as: 2/12/2013 11:59:00 PM , 2/13/2013 11:59:00 PM
i.e. different dates with time.
I want to compare date [only date] in where clause.
I am trying with following query:
select *
from foclosing
where CONVERT(varchar(11), Trade_Date) like '2/12/2013 %'
or
select *
from foclosing
where Trade_Date = CONVERT(datetime, '2/12/2013')
but both of these queries are not working.
What can be the issue?
select * from foclosing
where Trade_Date >= '20130212' AND Trade_Date < '20130213'
Use yyyymmdd which is safe for SQL Server
Don't apply functions to columns, then compare (your 1st query)See mistake 2 here: https://www.simple-talk.com/sql/t-sql-programming/ten-common-sql-programming-mistakes/
Don't compare locale-based dates as varchar (your 1st query)
Trade_Date has a time element which is why your 2nd query fails
In summary, a date conversion should not be used for examples like this: datetime is a range

How to select rows by date in sqlite

I have to select all rows from database by just passing date. For example to get all rows that have date 10/23/2012
In sqlite db I store this in DATE column:
01/01/1900 11:00:00 AM
I have tried to get by using date() but I get nothing for date:
select itemId, date(dateColumn) from items
So all I need is to compare only dates but can't find how to do this in sqlite.
Firstly, format your dates to the ISO-8601 standard. Wrap it in Date() to ensure it gets processed as a DATE. Finally, construct your range so that it will include everything from 12:00am onwards until just before 12:00am the next day.
select itemId, dateColumn
from items
where dateColumn >= date('2012-10-23')
AND dateColumn < date('2012-10-23', '+1 day')
SQLite columns are not typed. However, if you compare the column to a DATE as shown, it is sufficient to coerced the column data into dates (null if not coercible) and the comparison will work properly.
Example on SQLFiddle:
create table items (
itemid, datecolumn);
insert into items select
1,'abc' union all select
2,null union all select
3,'10/23/2012 12:23' union all select
4,'10/23/2012' union all select
5,'2012-10-23 12:23' union all select
6,'2012-10-23' union all select
7,'2012-10-24 12:23' union all select
8,'2012-10-24' union all select
9,date('2012-10-24 12:23') union all select
10,date('2012-10-24');
Results:
itemid datecolumn
5 2012-10-23 12:23
6 2012-10-23
Note that although rows 3 and 4 appear to be dates, they are not, because they do not conform to ISO-8601 formatting which is the only format recognized by SQLite.
In SQLite, there is no datatype DATE, it's stored as strings. Therefor, the Strings have to match exactly to be equal.
Since we don't want that, you'll want to "cast" the values from the date-column to pseudo-date and also cast your argument to a pseudo-date, so they can be compared:
SELECT itemId FROM items WHERE date(dateColumn) = date("2012-10-22");
Note that the date-command takes dates formated as YYYY-MM-DD, as further explained in an answer to this older question. The question also shows that you can use the BETWEEN x AND y-command to get dates, matching a range.
SELECT itemId,dateColumn FROM items WHERE dateColumn=date('YYYY-MM-DD HH:MM:SS');
SQLite Reference
select itemId,dateColumn from items
where dateColumn = #date

SQL to Return Dates for Selected Week Only

I'm writing a SQL query on a timesheet report. I need the report to return only the details for the week of the selected date.
E.g., if I pick 02/01/2012 (dd/MM/yyyy), then it should only return results between 02/01/2012 and 08/01/2012.
Thanks
SELECT
*
FROM
yourTable
WHERE
dateField >= #yourDate
AND dateField < #yourDate + 7
Some variations of SQL may have specific ways of adding 7 days to a datevalue. Such as...
- DateAdd(Day, 7, #date)
- DATE_ADD(#date, INTERVAL 7 DAYS)
- etc, etc
This option is both index friendly, and is resilient to database fields that have time parts as well as date parts.
You easiest is the equivalent of WEEK_OF_YEAR function in your SQL engine
But you can also use DATE_ADD
WHERE table.date BETWEEN target_date AND DATE_ADD(target_date,INTERVAL 7 DAY)
That depends on the database system you're using. MySQL has a function calles WEEK(), SQL Server can do something like this with the DATEPART() function:
MySQL:
SELECT
*
FROM table
WHERE WEEK(date_col) = WEEK('02/01/2012');
SQL SERVER:
SELECT
*
FROM table
WHERE DATEPART(WEEK, datecol) = DATEPART(WEEK,'02/01/2012');
SELECT * FROM table_name
WHERE date BETWEEN '1/02/2012' AND '1/08/2012';
you can replace the example date with your date and yourdate + 6.
Look here for example: http://www.roseindia.net/sql/sql-between-datetime.shtml