Picking any date from datetime SQl [duplicate] - sql

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');

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

Get rows having a datetime less than or equal to today ignoring time

I have a datetime field and would like to select the records having a date less than or equal to today but ignoring the time part of it.
My datetime field is as below:
2019-05-17 13:31:15.900, 2019-05-16 13:32:17.277, 2019-05-24 15:20:03.823
I would like to fetch only the rows with datetime 2019-05-17 13:31:15.900 and 2019-05-16 13:32:17.277 ignoring the time part.
Any idea of how to do that in sql server?
Simply, just cast both, your column and todays date to DATE:
SELECT * FROM MyTable
WHERE CAST(dt AS DATE) <= CAST(GETDATE() AS DATE)
You may try casting GETDATE() to a date type, to compare against tomorrow at midnight:
SELECT *
FROM yourTable
WHERE dt < CAST(DATEADD(day, 1, GETDATE()) AS date);
-- earlier than tomorrow at midnight
The date when this answer was written was 17-June-2019, so the above query would return any record whose datetime is strictly less than 18-June-2019 at midnight. The latest record would therefore be '2019-06-17 23:59:59'.

SQL "between" not inclusive

I have a query like this:
SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'
But this gives no results even though there is data on the 1st.
created_at looks like 2013-05-01 22:25:19, I suspect it has to do with the time? How could this be resolved?
It works just fine if I do larger date ranges, but it should (inclusive) work with a single date too.
It is inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight when the day starts.
One way to fix this is:
SELECT *
FROM Cases
WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'
Another way to fix it is with explicit binary comparisons
SELECT *
FROM Cases
WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'
Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.
It has been assumed that the second date reference in the BETWEEN syntax is magically considered to be the "end of the day" but this is untrue.
i.e. this was expected:
SELECT * FROM Cases
WHERE created_at BETWEEN the beginning of '2013-05-01' AND the end of '2013-05-01'
but what really happen is this:
SELECT * FROM Cases
WHERE created_at BETWEEN '2013-05-01 00:00:00+00000' AND '2013-05-01 00:00:00+00000'
Which becomes the equivalent of:
SELECT * FROM Cases WHERE created_at = '2013-05-01 00:00:00+00000'
The problem is one of perceptions/expectations about BETWEEN which does include BOTH the lower value and the upper values in the range, but does not magically make a date the "beginning of" or "the end of".
BETWEEN should be avoided when filtering by date ranges.
Always use the >= AND < instead
SELECT * FROM Cases
WHERE (created_at >= '20130501' AND created_at < '20130502')
the parentheses are optional here but can be important in more complex queries.
You need to do one of these two options:
Include the time component in your between condition: ... where created_at between '2013-05-01 00:00:00' and '2013-05-01 23:59:59' (not recommended... see the last paragraph)
Use inequalities instead of between. Notice that then you'll have to add one day to the second value: ... where (created_at >= '2013-05-01' and created_at < '2013-05-02')
My personal preference is the second option. Also, Aaron Bertrand has a very clear explanation on why it should be used.
Just use the time stamp as date:
SELECT * FROM Cases WHERE date(created_at)='2013-05-01'
I find that the best solution to comparing a datetime field to a date field is the following:
DECLARE #StartDate DATE = '5/1/2013',
#EndDate DATE = '5/1/2013'
SELECT *
FROM cases
WHERE Datediff(day, created_at, #StartDate) <= 0
AND Datediff(day, created_at, #EndDate) >= 0
This is equivalent to an inclusive between statement as it includes both the start and end date as well as those that fall between.
cast(created_at as date)
That will work only in 2008 and newer versions of SQL Server
If you are using older version then use
convert(varchar, created_at, 101)
You can use the date() function which will extract the date from a datetime and give you the result as inclusive date:
SELECT * FROM Cases WHERE date(created_at)='2013-05-01' AND '2013-05-01'
your code
SELECT * FROM Cases WHERE created_at BETWEEN '2013-05-01' AND '2013-05-01'
how SQL reading it
SELECT * FROM Cases WHERE '2013-05-01 22:25:19' BETWEEN '2013-05-01 00:00:00' AND '2013-05-01 00:00:00'
if you don't mention time while comparing DateTime and Date by default hours:minutes:seconds will be zero in your case dates are the same but if you compare time created_at is 22 hours ahead from your end date range
if the above is clear you fix this in many ways like putting ending hours in your end date eg BETWEEN '2013-05-01' AND ''2013-05-01 23:59:59''
OR
simply cast create_at as date like cast(created_at as date) after casting as date '2013-05-01 22:25:19' will be equal to '2013-05-01 00:00:00'
Dyamic date BETWEEN sql query
var startDate = '2019-08-22';
var Enddate = '2019-10-22'
let sql = "SELECT * FROM Cases WHERE created_at BETWEEN '?' AND '?'";
const users = await mysql.query( sql, [startDate, Enddate]);
Even though it is inclusive, as per Aaron Bertrand suggestion (read more about it here)
don't use BETWEEN for date/time ranges.
Apart from other good answers around here, one can also use DATEADD (to add a number of days to a given date) as follows
SELECT * FROM Cases WHERE created_at >= '2013-05-01' AND created_at < DATEADD(day, 1, '2013-05-01')

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');

MySQL "between" clause not inclusive?

If I run a query with a between clause, it seems to exclude the ending value.
For example:
select * from person where dob between '2011-01-01' and '2011-01-31'
This gets all results with dob from '2011-01-01' till '2011-01-30'; skipping records where dob is '2011-01-31'. Can anyone explain why this query behaves this way, and how I could modify it to include records where dob is '2011-01-31'? (without adding 1 to the ending date because its been selected by the users.)
From the MySQL-manual:
This is equivalent to the expression
(min <= expr AND expr <= max)
The field dob probably has a time component.
To truncate it out:
select * from person
where CAST(dob AS DATE) between '2011-01-01' and '2011-01-31'
The problem is that 2011-01-31 really is 2011-01-31 00:00:00. That is the beginning of the day. Everything during the day is not included.
select * from person where dob between '2011-01-01 00:00:00' and '2011-01-31 23:59:59'
Is the field you are referencing in your query a Date type or a DateTime type?
A common cause of the behavior you describe is when you use a DateTime type where you really should be using a Date type. That is, unless you really need to know what time someone was born, just use the Date type.
The reason the final day is not being included in your results is the way that the query is assuming the time portion of the dates that you did not specify in your query.
That is: Your query is being interpreted as up to Midnight between 2011-01-30 and 2011-01-31, but the data may have a value sometime later in the day on 2011-01-31.
Suggestion: Change the field to the Date type if it is a DateTime type.
Hi this query works for me,
select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'
select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'
Surprisingly such conversions are solutions to many problems in MySQL.
In MySql between the values are inclusive therefore when you give try to get between '2011-01-01' and '2011-01-31'
it will include from 2011-01-01 00:00:00 upto 2011-01-31 00:00:00
therefore nothing actually in 2011-01-31 since its time should go from 2011-01-31 00:00:00 ~ 2011-01-31 23:59:59
For the upper bound you can change to 2011-02-01 then it will get all data upto 2011-01-31 23:59:59
You can run the query as:
select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'
like others pointed out, if your dates are hardcoded.
On the other hand, if the date is in another table, you can add a day and subtract a second (if the dates are saved without the second/time), like:
select * from person JOIN some_table ... where dob between some_table.initial_date and (some_table.final_date + INTERVAL 1 DAY - INTERVAL 1 SECOND)
Avoid doing casts on the dob fiels (like in the accepted answer), because that can cause huge performance problems (like not being able to use an index in the dob field, assuming there is one). The execution plan may change from using index condition to using where if you make something like DATE(dob) or CAST(dob AS DATE), so be careful!
Set the upper date to date + 1 day, so in your case, set it to 2011-02-01.
select * from person where dob between '2011-01-01' and '2011-01-31' or dob like' 2011-01-31%'
Just add or <<column>> like "date%".