SQL Server - Check date field between two dates in where clause - sql-server

In the following query the date returned is 2019-07-12 14:12:58.253
SELECT MAX(fileDate) AS maxdate FROM filetable
This query returns the following value 2019-07-11 23:46:20.317
SELECT MAX(fileDate) AS maxdate FROM filetable WHERE fileDate BETWEEN '2019-01-18' AND '2019-07-12'
I have tried using >= and <= instead of BETWEEN with the same results.
Why is this happening?

'2019-07-12' against a datetime will be implicitly converted to the datetime 2019-07-12T00:00:00.000. For your query with the WHERE clause fileDate BETWEEN '2019-01-18' AND '2019-07-12' that means that a value like 2019-07-12T14:12:58.253 is outside of the range, as it's larger than 2019-07-12T00:00:00.000.
The common way is to use >= and < where the value for the < is the day after the day you need. Therefore you end up with the below:
SELECT MAX(fileDate) AS maxdate
FROM filetable
WHERE fileDate >= '2019-01-18'
AND fileDate < '2019-07-13';

Related

SQL Server Finding date in between

I have table like below,
In Realtime scenario I have more rows for testing purpose I am attaching only two rows.
[Table]
Value
Start Date
End Date
10
30-Jun-15
30-Jun-16
20
30-Jun-16
31-Oct-16
If I requested start date as ' 31-JUL-2016' and end date as '31-AUG-2016',
I need to get only row 2(Second row from table) in above table.
If I requested start date as ' 31-AUG-2015' and end date as '31-AUG-2016',
I need get all two rows (All row from table) in above table.
How I can achieve this in SQL Server?
SELECT * FROM your_table
WHERE '20160731' <= EndDate
AND '20160831' >= StartDate;
SELECT * FROM your_table
WHERE '20150831' <= EndDate
AND '20160831' >= StartDate;

How to check date time column value equals to current date in sql where clause

I have a date time column in sql DB - named check_time. I want to write a select query where this check_time should be equals to today's date (no need to consider what time is. Only need to check current date).
For example check_time in table is inserted as 03/08/2017 12:00:00.000 AM.
I have written like below
SELECT * FROM time_details
WHERE check_time = DATEADD(day, DATEDIFF(day,0,GETDATE()),0)
But it returns nothing.
This is the correct syntax:
SELECT * FROM time_details where (DATEDIFF(d, check_time, GETDATE()) = 0)
Just CAST the today's date to DATE.
Query
select * from time_details
where check_time = cast(getdate() as date);
Try with
SELECT * FROM time_details where DATE(check_time) =CURDATE()
The DATE function is going to extract just the date from you datetime field while the CURDATE is returning the current date.
Check with the sql query
SELECT * FROM time_details where DATE(check_time)=DATE(NOW())
this should work
SELECT * FROM time_details where check_time =convert(varchar, getdate(), 101)

Query using a date range but end date may be null

sql server 2014
I am trying to query data using a date range. Data in the table is datetime datatype.
so I want to use as parameters #IncidentDate and #IncidentEndDate.
Issues are that the #IncidentEndDate may be null. Also each row in the data may or may not have an end_datetime (null if no date)
In my where clause I have
(end_datetime IS NULL) AND (#IncidentDate >= CAST(start_datetime AS DATE) AND #IncidentDate <= DATEADD(d,0,DATEDIFF(d,0,start_datetime)))
OR
(#IncidentDate <= end_datetime) AND (#IncidentEndDate >= start_datetime)
However I am not sure if this si working properly. I would expect rows that have no end_datetime to appear in the results but they don't seem to be .
EDIT: In the end I came up with the following after reading everybody's replies...
WHERE (
#IncidentDate <= isnull(end_datetime, dateadd(day,1,start_datetime))
)
AND (
isnull(#IncidentEndDate,dateadd(day,1,#IncidentDate)) >= start_datetime
)
This seems to me to be a tidier way to satisfy my requirements - it looks after the possiblity of both end_datetime being null and #IncdidentEndDate being Null
Also, you can use the ISNULL() function to help handle NULL values. The ISNULL() function checks the value and, if it's NULL, replaces it with a supplied value. So if you wanted the NULLs, you could put in a value that would match or, if not, something that would definitely be outside your range like 01/01/1900 or the MIN Date (varies depending on DATETIME or DATETIME2).
To exclude:
SELECT * FROM mySweetTable WHERE ISNULL(createdDate, '01-JAN-1900') >= '01-JAN-2015'
To include:
SELECT * FROM mySweetTable WHERE ISNULL(createdDate, GETDATE()) >= '01-JAN-2015'
Although, I don't recommend ACTUALLY leaving GETDATE() in the WHERE clause, that's bad news bears; replace it with a variable or specific value.
--This should get you what you want
start_datetime >= #IncidentDate and (#IncidentEndDate is null or end_datetime is null or end_datetime < dateadd(day,1,#IncidentEndDate))
Unless, of course, you want to exclude ones where the end_datetime is null and if that's the case just let me know!

How to query DATETIME field using only date in Microsoft SQL Server?

I have a table TEST with a DATETIME field, like this:
ID NAME DATE
1 TESTING 2014-03-19 20:05:20.000
What I need a query returning this row and every row with date 03/19/2014, no matter what the time is. I tried using
select * from test where date = '03/19/2014';
But it returns no rows. The only way to make it work that I found is to also provide the time portion of the date:
select * from test where date = '03/19/2014 20:03:02.000';
use range, or DateDiff function
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
or
select * from test
where datediff(day, date, '03/19/2014') = 0
Other options are:
If you have control over the database schema, and you don't need the
time data, take it out.
or, if you must keep it, add a computed column attribute that has the time portion of the date value stripped off...
Alter table Test
Add DateOnly As
DateAdd(day, datediff(day, 0, date), 0)
or, in more recent versions of SQL Server...
Alter table Test
Add DateOnly As
Cast(DateAdd(day, datediff(day, 0, date), 0) as Date)
then, you can write your query as simply:
select * from test
where DateOnly = '03/19/2014'
Simple answer;
select * from test where cast ([date] as date) = '03/19/2014';
I am using MySQL 5.6 and there is a DATE function to extract only the date part from date time. So the simple solution to the question is -
select * from test where DATE(date) = '2014-03-19';
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html
This works for me for MS SQL server:
select * from test
where
year(date) = 2015
and month(date) = 10
and day(date)= 28 ;
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'
This is a realy bad answer. For two reasons.
1.
What happens with times like 23.59.59.700 etc.
There are times larger than 23:59:59 and the next day.
2.
The behaviour depends on the datatype.
The query behaves differently for datetime/date/datetime2 types.
Testing with 23:59:59.999 makes it even worse because depending on the datetype you get different roundings.
select convert (varchar(40),convert(date , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime , '2014-03-19 23:59:59.999'))
select convert (varchar(40),convert(datetime2 , '2014-03-19 23:59:59.999'))
-- For date the value is 'chopped'.
-- For datetime the value is rounded up to the next date. (Nearest value).
-- For datetime2 the value is precise.
use this
select * from TableName where DateTimeField > date() and DateTimeField < date() + 1
Try this
select * from test where Convert(varchar, date,111)= '03/19/2014'
you can try this
select * from test where DATEADD(dd, 0, DATEDIFF(dd, 0, date)) = '03/19/2014';
There is a problem with dates and languages and the way to avoid it is asking for dates with this format YYYYMMDD.
This way below should be the fastest according to the link below. I checked in SQL Server 2012 and I agree with the link.
select * from test where date >= '20141903' AND date < DATEADD(DAY, 1, '20141903');
Bad habits to kick : mis-handling date / range queries
You can use this approach which truncates the time part:
select * from test
where convert(datetime,'03/19/2014',102) = DATEADD(dd, DATEDIFF(dd, 0, date), 0)
-- Reverse the date format
-- this false:
select * from test where date = '28/10/2015'
-- this true:
select * from test where date = '2015/10/28'
Simply use this in your WHERE clause.
The "SubmitDate" portion below is the column name, so insert your own.
This will return only the "Year" portion of the results, omitting the mins etc.
Where datepart(year, SubmitDate) = '2017'
select *, cast ([col1] as date) <name of the column> from test where date = 'mm/dd/yyyy'
"col1" is name of the column with date and time
<name of the column> here you can change name as desired
select *
from invoice
where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));
Test this query.
SELECT *,DATE(chat_reg_date) AS is_date,TIME(chat_reg_time) AS is_time FROM chat WHERE chat_inbox_key='$chat_key'
ORDER BY is_date DESC, is_time DESC
select * from invoice where TRANS_DATE_D>= to_date ('20170831115959','YYYYMMDDHH24MISS')
and TRANS_DATE_D<= to_date ('20171031115959','YYYYMMDDHH24MISS');
SELECT * FROM test where DATEPART(year,[TIMESTAMP]) = '2018' and DATEPART(day,[TIMESTAMP]) = '16' and DATEPART(month,[TIMESTAMP]) = '11'
use trunc(column).
select * from test t where trunc(t.date) = TO_DATE('2018/06/08', 'YYYY/MM/DD')

how to use combine date part in search statement of sql server?

select *
from employee
where DATEPART(MM ,empDOJ) + DATEPART(yy,empDOJ) < 2013 + 5
I want employee detail from table "employee" where date of join of employee is less than may 2013 but above query is not working properly and "empdoj" is date in sql
correct way of doing this would be
select *
from employee
where empDOJ < convert(date, '20130501', 112)
But you can use string '20130501' or '2013-05-01' because when you compare it to date column, SQL Server will convert data types according to data type priorities. Since date type is higher priority than varchar type, SQL will convert varchar to date implicitly:
select *
from employee
where empDOJ < '20130501'
Note that using functions on your column prevent from using indexes on this column, so when you're writing where datepart(MM ,empDOJ) = 5 index (if you have index on empDOJ column) will not be used.
SELECT *
FROM EMPLOYEE
WHERE EMPDOJ < '2013-05-01'

Resources