SQL query to return the rows between two dates - sql

I am using this query to get the rows between two dates but I don't get the rows from the database, it returns an empty set (in db I have rows for that day)
Query:
select email
from users
where date_email_sent between '17-May-12' AND '17-May-12'
When I try the query below I am getting 17th row alone
Query:
select email
from users
where date_email_sent between '17-May-12' AND '18-May-12'
Can any one plz suggest me how to get 17th records alone if start date and end date as same.
Thanks in advance.

Does the date_email_sent have a datetime value? If the column value like 2012-05-17 09:30:00.000 has both date and time, then you may need to put the time together with your date value in the where clause,
e.g.
where date_email_sent between '17-May-12 00:00:00.000' AND '17-May-12 23:59:59.000'
or you can look at the date value only for the field
where DATEADD(dd, 0, DATEDIFF(dd, 0, date_email_sent )) between '17-May-12' AND '17-May-12'
SQL always consider as 12am if you put date only, so there will be a problem if you want to compare a date with datetime value

When you specify a date without a time portion, the time is automatically assumed as 12:00 am. So when you write
date_email_sent between '17-May-12' AND '17-May-12'
This is effectively the same as
date_email_sent between '17-May-12 12:00AM' AND '17-May-12 12:00AM'
So as you can see, the two times are identical and naturally there are no records in the specified interval.
If you want all the records on one day, you need to measure from midnight until midnight the next day:
date_email_sent >= '17-May-12 12:00AM' and date_email_sent < '18-May-12 12:00AM'
or just:
date_email_sent >= '17-May-12' and date_email_sent < '18-May-12'
Alternatively, you can extract the day portion of the date and check that for the correct value. The specific date handling functions vary depending on your dbms.

In SQL Server you should do it like this.
select email
from users
where date_email_sent >= '20120517' and
date_email_sent < dateadd(day, 1, '20120517')
If you use something else you have to replace dateadd with something else.

select email
from users
where date_email_sent >= '17-May-12' AND date_email_sent < '18-May-12'

when you write
BETWEEN '17-May-12' AND '17-May-12'
so you haven't mentioned the time so in Date datatype it considered as
'17-May-12 00:00:00' AND '17-May-12 00:00:00'
so your range is limited that's why you didn't get records.
you should mention time also to get the record with same date .
In oracle you can write like this
BETWEEN to_date('dd-mm-yyyy hh24:mi','17-05-12 00:00') AND to_date('dd-mm-yyyy hh24:mi','17-05-12 23:59')

Related

Changing date to day before for certain daily time ranges in SQL

We have a table with a datetime field and need to get it to work properly with other tables that have date fields that work on system date, not calendar date.
Our system day runs until 1:59 AM, so anything after midnight until then is considered the day before in all of these tables (which don't actually show datetime, just date).
I am trying to figure out how I can create a date field where '2019-01-01 01:45:00.111' would read as '2018-12-31', but '2019-01-01 2:00:00.111' would read as '2019-01-01'.
Any ideas would be much appreciated.
Try this simple logic below by removing 120 minutes from your each datetime value and then cast the datetime value as date.
SELECT CAST(DATEADD(MINUTE,-120,<your_date_time_column>) AS DATE)
FROM <Your_Table>
You can make use of CASE WHEN.. clause to increment or decrement dates by 1 like below sample
SELECT CASE WHEN TO_CHAR(DATE,
'HH:MM') BETWEEN '00:00' AND
'01:45' THEN DATE-1 ELSE
DATE END FROM TABLE

Picking any date from datetime SQl [duplicate]

I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.
select Date,TotalAllowance
from Calculation
where EmployeeId=1
and Date between 2011/02/25 and 2011/02/27
Here Date is a datetime variable.
you should put those two dates between single quotes like..
select Date, TotalAllowance from Calculation where EmployeeId = 1
and Date between '2011/02/25' and '2011/02/27'
or can use
select Date, TotalAllowance from Calculation where EmployeeId = 1
and Date >= '2011/02/25' and Date <= '2011/02/27'
keep in mind that the first date is inclusive, but the second is exclusive, as it effectively is '2011/02/27 00:00:00'
Since a datetime without a specified time segment will have a value of date 00:00:00.000, if you want to be sure you get all the dates in your range, you must either supply the time for your ending date or increase your ending date and use <.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date < '2011/02/28'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
DO NOT use the following, as it could return some records from 2011/02/28 if their times are 00:00:00.000.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/28'
Try this:
select Date,TotalAllowance from Calculation where EmployeeId=1
and [Date] between '2011/02/25' and '2011/02/27'
The date values need to be typed as strings.
To ensure future-proofing your query for SQL Server 2008 and higher, Date should be escaped because it's a reserved word in later versions.
Bear in mind that the dates without times take midnight as their defaults, so you may not have the correct value there.
select * from table_name where col_Date between '2011/02/25'
AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))
Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.
output:
2011/02/25
2011/02/26
2011/02/27
select * from test
where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'
-- if data type is different
This query stands good for fetching the values between current date and its next 3 dates
SELECT * FROM tableName WHERE columName
BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
This will eventually add extra 3 days of buffer to the current date.
This is very old, but given a lot of experiences I have had with dates, you might want to consider this: People use different regional settings, as such, some people (and some databases/computers, depending on regional settings) may read this date 11/12/2016 as 11th Dec 2016 or Nov 12, 2016. Even more, 16/11/12 supplied to MySQL database will be internally converted to 12 Nov 2016, while Access database running on a UK regional setting computer will interpret and store it as 16th Nov 2012.
Therefore, I made it my policy to be explicit whenever I am going to interact with dates and databases. So I always supply my queries and programming codes as follows:
SELECT FirstName FROM Students WHERE DoB >= '11 Dec 2016';
Note also that Access will accept the #, thus:
SELECT FirstName FROM Students WHERE DoB >= #11 Dec 2016#;
but MS SQL server will not, so I always use " ' " as above, which both databases accept.
And when getting that date from a variable in code, I always convert the result to string as follows:
"SELECT FirstName FROM Students WHERE DoB >= " & myDate.ToString("d MMM yyyy")
I am writing this because I know sometimes some programmers may not be keen enough to detect the inherent conversion. There will be no error for dates < 13, just different results!
As for the question asked, add one day to the last date and make the comparison as follows:
dated >= '11 Nov 2016' AND dated < '15 Nov 2016'
Try putting the dates between # #
for example:
#2013/4/4# and #2013/4/20#
It worked for me.
select Date,TotalAllowance
from Calculation
where EmployeeId=1
and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'
if its date in 24 hours and start in morning and end in the night should add something like :
declare #Approval_date datetime
set #Approval_date =getdate()
Approval_date between #Approval_date +' 00:00:00.000' and #Approval_date +' 23:59:59.999'
SELECT CITY, COUNT(EID) OCCURENCES FROM EMP
WHERE DOB BETWEEN '31-JAN-1900' AND '31-JAN-2900'
GROUP BY CITY
HAVING COUNT(EID) > 2;
This query will find Cities with more than 2 occurrences where their DOB is in a specified time range for employees.
I would go for
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date < DATEADD(d, 1, '2011/02/27')
The logic being that >= includes the whole start date and < excludes the end date, so we add one unit to the end date. This can adapted for months, for instance:
select Date, ... from ...
where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)
best query for the select date between current date and back three days:
select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN
DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND CURDATE()
best query for the select date between current date and next three days:
select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN
CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
Check below Examples: Both working and Non-Working.
select * from tblUser Where
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**
OR
select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**
OR
select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30'))
//--**Working**
AND below is not working:
select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >= Convert(Varchar(10),'01-01-2015',111) and Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**
select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**
You ca try this SQL
select * from employee where rec_date between '2017-09-01' and '2017-09-11'
I like to use the syntax 1 MonthName 2015 for dates ex:
WHERE aa.AuditDate>='1 September 2015'
AND aa.AuditDate<='30 September 2015'
for dates
Select
*
from
Calculation
where
EmployeeId=1 and Date between #2011/02/25# and #2011/02/27#;
we can use between to show two dates data but this will search the whole data and compare so it will make our process slow for huge data, so i suggest everyone to use datediff:
qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
here calender is the Table, dt as the starting date variable and dt2 is the finishing date variable.
There are a lot of bad answers and habits in this thread, when it comes to selecting based on a date range where the records might have non-zero time values - including the second highest answer at time of writing.
Never use code like this: Date between '2011/02/25' and '2011/02/27 23:59:59.999'
Or this: Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
To see why, try it yourself:
DECLARE #DatetimeValues TABLE
(MyDatetime datetime);
INSERT INTO #DatetimeValues VALUES
('2011-02-27T23:59:59.997')
,('2011-02-28T00:00:00');
SELECT MyDatetime
FROM #DatetimeValues
WHERE MyDatetime BETWEEN '2020-01-01T00:00:00' AND '2020-01-01T23:59:59.999';
SELECT MyDatetime
FROM #DatetimeValues
WHERE MyDatetime >= '2011-02-25T00:00:00' AND MyDatetime <= '2011-02-27T23:59:59.999';
In both cases, you'll get both rows back. Assuming the date values you're looking at are in the old datetime type, a date literal with a millisecond value of 999 used in a comparison with those dates will be rounded to millisecond 000 of the next second, as datetime isn't precise to the nearest millisecond. You can have 997 or 000, but nothing in between.
You could use the millisecond value of 997, and that would work - assuming you only ever need to work with datetime values, and not datetime2 values, as these can be far more precise. In that scenario, you would then miss records with a time value 23:59:59.99872, for example. The code originally suggested would also miss records with a time value of 23:59:59.9995, for example.
Far better is the other solution offered in the same answer - Date >= '2011/02/25' and Date < '2011/02/28'. Here, it doesn't matter whether you're looking at datetime or datetime2 columns, this will work regardless.
The other key point I'd like to raise is date and time literals. '2011/02/25' is not a good idea - depending on the settings of the system you're working in this could throw an error, as there's no 25th month. Use a literal format that works for all locality and language settings, e.g. '2011-02-25T00:00:00'.
Really all sql dates should be in yyyy-MM-dd format for the most accurate results.
Two things:
use quotes
make sure to include the last day (ending at 24)
select Date, TotalAllowance
from Calculation
where EmployeeId=1
and "2011/02/25" <= Date and Date <= "2011/02/27"
If Date is a DateTime.
I tend to do range checks in this way as it clearly shows lower and upper boundaries. Keep in mind that date formatting varies wildly in different cultures. So you might want to make sure it is interpreted as a date. Use DATE_FORMAT( Date, 'Y/m/d').
(hint: use STR_TO_DATE and DATE_FORMAT to switch paradigms.)
It worked for me
SELECT
*
FROM
`request_logs`
WHERE
created_at >= "2022-11-30 00:00:00"
AND created_at <= "2022-11-30 20:04:50"
ORDER BY
`request_logs`.`id` DESC
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 10 [Id]
,[Id_parvandeh]
,[FirstName]
,[LastName]
,[RegDate]
,[Gilder]
,[Nationality]
,[Educ]
,[PhoneNumber]
,[DueInMashhad]
,[EzdevajDate]
,[MarriageStatus]
,[Gender]
,[Photo]
,[ModifiedOn]
,[CreatorIp]
From
[dbo].[Socials] where educ >= 3 or EzdevajDate >= '1992/03/31' and EzdevajDate <= '2019/03/09' and MarriageStatus = 1
SELECT Date, TotalAllowance
FROM Calculation
WHERE EmployeeId = 1
AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd')
AND to_date ('2011/02/27','yyyy-mm-dd');

How to compare current time to retrieve record stored in SQL

I have a database in which one of the column name is 'date' I need to count the number of entries that have been added with today's date after 09.00.00
So far I have done this..I am wondering where do I specify the time '09.00.00'
SELECT COUNT(*) AS total from DATABASENAME
WHERE date >= Convert(datetime, Convert(int, GetDate()))
Here's code that should work. You're essentially converting a datetime to a date to remove the time, then back to a datetime and adding in the hour that you want.
SELECT COUNT(*) AS Total
FROM TableName
WHERE Date >= DATEADD(HOUR, 9, CONVERT(DATETIME, CONVERT(DATE, GETDATE())))
Well is the date column store date and time or date only, if it is date only you need to add the time also in the column and also avoid converting data type in where condition try the above query with a parameter variable

SQL Server 2008 DateTime range query

I have a table called Users:
CreateTime UserName
========================================
2012-08-30 14:23:12:000 zhang
2012-08-30 15:11:13:000 li
2012-08-30 16:32:22:000 wang
2012-08-31 11:23:12:000 steven
2012-08-31 12:05:14:000 zhao
2012-08-31 08:23:12:000 ddd
and a query:
select UserName
from Users
where CreateTime >= '2012-08-30' and CreateTime <= '2012-08-31'
So, the results should be 6 rows, but it does not.
How to solve this?
Using SQL Server Convert function CONVERT(VARCHAR(23), CreateTime, 121) ?
It is not showing 6 rows because 2012-08-31 is received by the interpreter as 2012-08-31 00:00:00 AM. Since you want to see data up to and including the 31st, you can either explicitly mention the time or query the next day's date.
Example Using the Next Day's Date
SELECT UserName
FROM Users
WHERE CreateTime >= '2012-08-30' AND CreateTime < '2012-09-01'
Example with Time Explicitly Mentioned
SELECT UserName
FROM Users
WHERE CreateTime >= '2012-08-30 00:00:00' AND CreateTime < '2012-09-31 23:59:59'
All you need is to CAST your CreateTime from Datetime to Date like this:
SELECT UserName FROM Users
WHERE CAST(CreateTime as date)>='2012-08-30'
AND CAST(CreateTime as date)<= '2012-08-31';
You can also use BETWEEN instead of <= and >= like this:
SELECT UserName FROM Users
WHERE CAST(CreateTime as date) BETWEEN
'2012-08-30' AND '2012-08-31';
See this SQLFiddle
The basic problem is that, when you simply enter a date, SQL Server interprets that date as midnight on that date. So, when you ask for '2012-08-31', it really means '2012-08-31 12:00AM'.
The best solution is to go one day beyond the day you want and use less than, rather than less than or equal.
select UserName from Users where CreateTime>='2012-08-30' and CreateTime < '2012-09-01'
Try this
select UserName
from Users
where CreateTime>='2012-08-30' and CreateTime<'2012-09-01'
CreateTime<='2012-08-31' is never true for last three dates, as their time stamps are after midnight. 2012-08-31 is short for 2012-08-31 00:00:00, so only the first three lines are returned.
You should always include a timestamp - also: using BETWEEN as suggested in the other answers is a good idea.
select UserName from Users where CreateTime>='2012-08-30' and CreateTime < '2012-09-01'
You should use something like below:
SELECT UserName
FROM Users
WHERE DATEDIFF(d, '2012-08-30', CreateTime) >= 0
AND DATEDIFF(d, #ToDate, '2012-09-01') <=0
You will not need to pass hours and minutes with this query.

SQL query to select dates between two dates

I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.
select Date,TotalAllowance
from Calculation
where EmployeeId=1
and Date between 2011/02/25 and 2011/02/27
Here Date is a datetime variable.
you should put those two dates between single quotes like..
select Date, TotalAllowance from Calculation where EmployeeId = 1
and Date between '2011/02/25' and '2011/02/27'
or can use
select Date, TotalAllowance from Calculation where EmployeeId = 1
and Date >= '2011/02/25' and Date <= '2011/02/27'
keep in mind that the first date is inclusive, but the second is exclusive, as it effectively is '2011/02/27 00:00:00'
Since a datetime without a specified time segment will have a value of date 00:00:00.000, if you want to be sure you get all the dates in your range, you must either supply the time for your ending date or increase your ending date and use <.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/27 23:59:59.999'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date < '2011/02/28'
OR
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
DO NOT use the following, as it could return some records from 2011/02/28 if their times are 00:00:00.000.
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date between '2011/02/25' and '2011/02/28'
Try this:
select Date,TotalAllowance from Calculation where EmployeeId=1
and [Date] between '2011/02/25' and '2011/02/27'
The date values need to be typed as strings.
To ensure future-proofing your query for SQL Server 2008 and higher, Date should be escaped because it's a reserved word in later versions.
Bear in mind that the dates without times take midnight as their defaults, so you may not have the correct value there.
select * from table_name where col_Date between '2011/02/25'
AND DATEADD(s,-1,DATEADD(d,1,'2011/02/27'))
Here, first add a day to the current endDate, it will be 2011-02-28 00:00:00, then you subtract one second to make the end date 2011-02-27 23:59:59. By doing this, you can get all the dates between the given intervals.
output:
2011/02/25
2011/02/26
2011/02/27
select * from test
where CAST(AddTime as datetime) between '2013/4/4' and '2014/4/4'
-- if data type is different
This query stands good for fetching the values between current date and its next 3 dates
SELECT * FROM tableName WHERE columName
BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
This will eventually add extra 3 days of buffer to the current date.
This is very old, but given a lot of experiences I have had with dates, you might want to consider this: People use different regional settings, as such, some people (and some databases/computers, depending on regional settings) may read this date 11/12/2016 as 11th Dec 2016 or Nov 12, 2016. Even more, 16/11/12 supplied to MySQL database will be internally converted to 12 Nov 2016, while Access database running on a UK regional setting computer will interpret and store it as 16th Nov 2012.
Therefore, I made it my policy to be explicit whenever I am going to interact with dates and databases. So I always supply my queries and programming codes as follows:
SELECT FirstName FROM Students WHERE DoB >= '11 Dec 2016';
Note also that Access will accept the #, thus:
SELECT FirstName FROM Students WHERE DoB >= #11 Dec 2016#;
but MS SQL server will not, so I always use " ' " as above, which both databases accept.
And when getting that date from a variable in code, I always convert the result to string as follows:
"SELECT FirstName FROM Students WHERE DoB >= " & myDate.ToString("d MMM yyyy")
I am writing this because I know sometimes some programmers may not be keen enough to detect the inherent conversion. There will be no error for dates < 13, just different results!
As for the question asked, add one day to the last date and make the comparison as follows:
dated >= '11 Nov 2016' AND dated < '15 Nov 2016'
Try putting the dates between # #
for example:
#2013/4/4# and #2013/4/20#
It worked for me.
select Date,TotalAllowance
from Calculation
where EmployeeId=1
and convert(varchar(10),Date,111) between '2011/02/25' and '2011/02/27'
if its date in 24 hours and start in morning and end in the night should add something like :
declare #Approval_date datetime
set #Approval_date =getdate()
Approval_date between #Approval_date +' 00:00:00.000' and #Approval_date +' 23:59:59.999'
SELECT CITY, COUNT(EID) OCCURENCES FROM EMP
WHERE DOB BETWEEN '31-JAN-1900' AND '31-JAN-2900'
GROUP BY CITY
HAVING COUNT(EID) > 2;
This query will find Cities with more than 2 occurrences where their DOB is in a specified time range for employees.
I would go for
select Date,TotalAllowance from Calculation where EmployeeId=1
and Date >= '2011/02/25' and Date < DATEADD(d, 1, '2011/02/27')
The logic being that >= includes the whole start date and < excludes the end date, so we add one unit to the end date. This can adapted for months, for instance:
select Date, ... from ...
where Date >= $start_month_day_1 and Date < DATEADD(m, 1, $end_month_day_1)
best query for the select date between current date and back three days:
select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN
DATE_SUB(CURDATE(), INTERVAL 3 DAY) AND CURDATE()
best query for the select date between current date and next three days:
select Date,TotalAllowance from Calculation where EmployeeId=1 and Date BETWEEN
CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
Check below Examples: Both working and Non-Working.
select * from tblUser Where
convert(varchar(10),CreatedDate,111) between '2015/04/01' and '2016/04/01' //--**Working**
OR
select * from tblUser Where
(CAST(CreatedDate AS DATETIME) between CAST('2015/04/01' AS DATETIME) And CAST('2016/4/30'AS DATETIME)) //--**Working**
OR
select * from tblUser Where
(YEAR(CreatedDate) between YEAR('2015/04/01') And YEAR('2016/4/30'))
//--**Working**
AND below is not working:
select * from tblUser Where
Convert(Varchar(10),CreatedDate,111) >= Convert(Varchar(10),'01-01-2015',111) and Convert(Varchar(10),CreatedDate,111) <= Convert(Varchar(10),'31-12-2015',111) //--**Not Working**
select * from tblUser Where
(Convert(Varchar(10),CreatedDate,111) between Convert(Varchar(10),'01-01-2015',111) And Convert(Varchar(10),'31-12-2015',111)) //--**Not Working**
You ca try this SQL
select * from employee where rec_date between '2017-09-01' and '2017-09-11'
I like to use the syntax 1 MonthName 2015 for dates ex:
WHERE aa.AuditDate>='1 September 2015'
AND aa.AuditDate<='30 September 2015'
for dates
Select
*
from
Calculation
where
EmployeeId=1 and Date between #2011/02/25# and #2011/02/27#;
we can use between to show two dates data but this will search the whole data and compare so it will make our process slow for huge data, so i suggest everyone to use datediff:
qry = "SELECT * FROM [calender] WHERE datediff(day,'" & dt & "',[date])>=0 and datediff(day,'" & dt2 & "',[date])<=0 "
here calender is the Table, dt as the starting date variable and dt2 is the finishing date variable.
There are a lot of bad answers and habits in this thread, when it comes to selecting based on a date range where the records might have non-zero time values - including the second highest answer at time of writing.
Never use code like this: Date between '2011/02/25' and '2011/02/27 23:59:59.999'
Or this: Date >= '2011/02/25' and Date <= '2011/02/27 23:59:59.999'
To see why, try it yourself:
DECLARE #DatetimeValues TABLE
(MyDatetime datetime);
INSERT INTO #DatetimeValues VALUES
('2011-02-27T23:59:59.997')
,('2011-02-28T00:00:00');
SELECT MyDatetime
FROM #DatetimeValues
WHERE MyDatetime BETWEEN '2020-01-01T00:00:00' AND '2020-01-01T23:59:59.999';
SELECT MyDatetime
FROM #DatetimeValues
WHERE MyDatetime >= '2011-02-25T00:00:00' AND MyDatetime <= '2011-02-27T23:59:59.999';
In both cases, you'll get both rows back. Assuming the date values you're looking at are in the old datetime type, a date literal with a millisecond value of 999 used in a comparison with those dates will be rounded to millisecond 000 of the next second, as datetime isn't precise to the nearest millisecond. You can have 997 or 000, but nothing in between.
You could use the millisecond value of 997, and that would work - assuming you only ever need to work with datetime values, and not datetime2 values, as these can be far more precise. In that scenario, you would then miss records with a time value 23:59:59.99872, for example. The code originally suggested would also miss records with a time value of 23:59:59.9995, for example.
Far better is the other solution offered in the same answer - Date >= '2011/02/25' and Date < '2011/02/28'. Here, it doesn't matter whether you're looking at datetime or datetime2 columns, this will work regardless.
The other key point I'd like to raise is date and time literals. '2011/02/25' is not a good idea - depending on the settings of the system you're working in this could throw an error, as there's no 25th month. Use a literal format that works for all locality and language settings, e.g. '2011-02-25T00:00:00'.
Really all sql dates should be in yyyy-MM-dd format for the most accurate results.
Two things:
use quotes
make sure to include the last day (ending at 24)
select Date, TotalAllowance
from Calculation
where EmployeeId=1
and "2011/02/25" <= Date and Date <= "2011/02/27"
If Date is a DateTime.
I tend to do range checks in this way as it clearly shows lower and upper boundaries. Keep in mind that date formatting varies wildly in different cultures. So you might want to make sure it is interpreted as a date. Use DATE_FORMAT( Date, 'Y/m/d').
(hint: use STR_TO_DATE and DATE_FORMAT to switch paradigms.)
It worked for me
SELECT
*
FROM
`request_logs`
WHERE
created_at >= "2022-11-30 00:00:00"
AND created_at <= "2022-11-30 20:04:50"
ORDER BY
`request_logs`.`id` DESC
/****** Script for SelectTopNRows command from SSMS ******/
SELECT TOP 10 [Id]
,[Id_parvandeh]
,[FirstName]
,[LastName]
,[RegDate]
,[Gilder]
,[Nationality]
,[Educ]
,[PhoneNumber]
,[DueInMashhad]
,[EzdevajDate]
,[MarriageStatus]
,[Gender]
,[Photo]
,[ModifiedOn]
,[CreatorIp]
From
[dbo].[Socials] where educ >= 3 or EzdevajDate >= '1992/03/31' and EzdevajDate <= '2019/03/09' and MarriageStatus = 1
SELECT Date, TotalAllowance
FROM Calculation
WHERE EmployeeId = 1
AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd')
AND to_date ('2011/02/27','yyyy-mm-dd');