SQL "between" not inclusive - sql

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

Related

Within "Where" Clause filter the same time period between two different days

To clarify the title:
I've got two columns:
VisitationDate: The date that someone visited a store. ex.) '2020-01-01'
VisitationDateTime: A DateTime object. ex.) '2020-01-01 00:00:00'
Within a where clause, I'm trying to select/filter a date range that is between '2020-01-01 00:00:00' to '2020-01-01 12:00:00' and the same exact time frame but on 01/03.
Other way of writing it:
I want the select these date/time ranges:
2020-01-01: Midnight to 12PM
2020-01-03: Midnight to 12PM
select * from myTable
where (visitationDateTime >= '20200101' and visitationDateTime < '20200101 12:00') or
(visitationDateTime >= '20200103' and visitationDateTime < '20200103 12:00');
Note that using BETWEEN for datetime range checks in MS SQL server is not a good idea. The better way is to use upper boundary exclusive using <.

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

SQL query selecting between two dates

I want to select records between two dates - a startDate and endDate (they are date/time format in sql). I have the following sql query but it does not work, could someone tell me what I'm doing wrong?
SELECT *
FROM house
WHERE startDate >= '2012/02/22 00:00:00' AND endDate <= '2012-02-25 00:00:00'
I would suggest converting the dates to a datetime and comparing them as well as keeping the date standard and consistent. Something like:
"SELECT *
FROM house
WHERE DATE(startDate) >= DATE('2012-02-22 00:00:00')
AND DATE(endDate) <= DATE('2012-02-25 00:00:00')"
NOTE: I assumed your startDate and endDate were of the same format as the strings your provided.
Do you want all rows that startDate is '2012-02-22' or later and endDate is '2012-02-22' or previous? Then, use this:
SELECT *
FROM house
WHERE startDate >= '2012-02-22'
AND endDate < '2012-02-26' --- notice the `<`, not `<=`
--- and the `day+1`
When using dates with SQL products, better use this format in queries and statements: '20120222' or this (which I find easier to read: '2012-02-22'.
Using slashes like '2012/02/22' or any other order than Year-Month-Day is not recommended.
There's no need to include the time part. '2012-02-22 00:00:00' is the same as '2012-02-22'.
Using endDate <= '2012-02-25 00:00:00' means that any row with date 25nd of Feb. 2012 but time after midnight ('00:00:00') will not match the condition. If you want those rows, too, use endDate < '2012-02-26' instead.
You could use DATE(endDate) <= DATE('2012-02-25 00:00:00') or DATE(endDate) <= '2012-02-25' but these conditions are "un-sargable", so your queries will not be able to use an index on endDate.
There is the builtin STR_TO_DATE function in MySql that takes same format mask as date_format.
start_date >= str_to_date('2012/02/22 00:00:00','%Y/%m/%d %h:%i:%s)
I guess thats type casting issue the reason why it din work because the input you are matching in the where clause is different that is the column is of date or datetime type and you are matching with a manual string format either use to_char on the left side of where to match the format on the right side or use to_date() on right side.
SELECT *
FROM house
WHERE
to_char(startDate, 'YYYY/MM/DD
24hh:mm:ss')>=
'2012/02/22 00:00:00'
AND to_char(endDate,
'YYYY/MM/DD
24hh:mm:ss') <= '2012-02-25
00:00:00'

Select a date range from a timestamp column

Currently my table has a column to store date and time. The data type of that column is timestamp without time zone. So it has values in the format '2011-09-13 11:03:44.537'.
I need to retrieve rows with respect to the date. If I use:
select * from table where mdate >= '2011-09-13 11:03:44.537'
and mdate <= '2011-09-12 11:03:44.537'
it will provide the values which are in between '2011-09-13 11:03:44.537' and '2011-09-12 11:03:44.537'.
But if I am going with:
select * from table where mdate >= '2011-09-13 00:00:00.0'
and mdate <= '2011-09-12 00:00:00.0'
without date, month and seconds, It is not displaying any rows.
How to fetch values from this table with respect to the date (only with date, ignoring hour, minutes and seconds)?
Even, the column has date with timestamp, I need to search them only with date (ignoring timestamp or making the hour, minutes and seconds to 0 such as '2011-09-13 00:00:00.0').
If you are going to cast the timestamp values of the field to date, as suggested in another answer, performance will degrade because every single value in the column needs to be cast for comparison and simple indexes cannot be used. You would have to create a special index on the expression, like so:
CREATE INDEX some_idx ON tbl (cast(mdate AS date));
In this case the query should also be simplified to:
SELECT * FROM tbl
WHERE mdate::date = '2011-09-12'::date; -- 2nd cast optional
However, as far as I can see, your problem is a simple typo / thinko in your query:
You switched upper & lower boundaries. Try:
SELECT * FROM tbl
WHERE mdate >= '2011-09-12 00:00:00.0'
AND mdate <= '2011-09-13 00:00:00.0';
Or, to simplify your syntax and be more precise:
SELECT * FROM tbl
WHERE mdate >= '2011-09-12 00:00'
AND mdate < '2011-09-13 00:00';
There is no need to spell out seconds and fractions that are 0.
You don't want to include 2011-09-13 00:00, so use < instead of <=.
Don't use BETWEEN here, for the same reason:
WHERE mdate BETWEEN '2011-09-12 00:00' AND '2011-09-13 00:00'
This would include 00:00 of the next day.
Also be aware that a column of type timestamp [without time zone] is interpreted according to your current time zone setting. The date part depends on that setting, which should generally work as expected. More details:
Ignoring time zones altogether in Rails and PostgreSQL
Just treat the timestamp as a date:
select *
from table
where mdate::date >= DATE '2011-09-12'
and mdate::date <= DATE '2011-09-13'
The expression mdate::date will cast the timestamp to a date type which will remove the time part from the value.
DATE '2011-09-13' is a (standard) DATE literal which is a bit more robust than simply writing '2011-09-13' as it isn't affected by any language settings.

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