MySQL "between" clause not inclusive? - sql

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%".

Related

Query with CASE WHEN / LAST_DAY is not giving any output

Running below query and not getting the output. Can someone please tell whats wrong in it?
Select distinct (table.datex)
from table
where table.datex =
(
CASE when extract( day from sysdate) >=19
then last_day(add_months(sysdate, -1))
else last_day(add_months(sysdate, -2))
END
)
Sample data
Datex
ID
30-JUN-21
A
31-MAY-21
B
29-JUN-21
C
Expected result
Datex
30-JUN-21
When I am passing the value hard-coded(calculated by the case) to where clause it's working fine, but when I apply the case it's not working. No error. No output is coming.
Date or datetime?
Oracle's LAST_DAY doesn't do what the name suggests, and the docs (https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/LAST_DAY.html#GUID-296C7C02-7FB9-4AAC-8927-6A79320CE0C6) fail to explain that, too.
Unlike several other DBMS Oracle doesn't have a date type. It only has a datetime type and they even call that inappropriately DATE. This means that a "date" in Oracle always has a time part. A date with its time part set to 00:00:00 can be considered a day's midnight (i.e. the very beginning of the day) or the whole day.
The function SYSDATE gives us a date in the sense of the DATE datatype, not in the sense of a real day, i.e. it gives us the datetime of "now", e.g. 2021-07-20 14:38:00. ADD_MONTHS changes the month in that datetime (and sometimes the year and sometimes even the day), i.e. leaves the time part untouched. LAST_DAY, too, changes the date part to get to the last day of the month, but leaves the time part untouched.
Your CASE expression hence results in something like TIMESTAMP '2021-07-20 14:38:00' and not in DATE '2021-07-20' as one might expect.
You say that you tried your query with the date you computed wth your case expression, and it worked. Did you compute the resulting day in your head or with a query? If the latter: The tool you are using may be set to only display a datetime's date part and omit the time part. This would explain why you only saw 30-JUN-21 when checking the CASE expression.
Solution
Truncate the datetime down to a whole day
Select distinct datex
from mytable
where (extract(day from sysdate) >=19 and datex = trunc(last_day(add_months(sysdate, -1))))
or (extract(day from sysdate) < 19 and datex = trunc(last_day(add_months(sysdate, -2))))
It doesn't matter whether you apply TRUNC late as in my example or right away on SYSDATE (with TRUNC(SYSDATE)) by the way. The only aim is to get rid of the time part at some point in the expression.
Don't use case in where clauses. Boolean logic can handle that.
And take a look if it is really the condition you want
Select distinct datex
from your_table
where
(
extract(day from sysdate) >=19
and datex = last_day(add_months(sysdate,-1))
)
or
(
extract(day from sysdate) < 19
and datex = last_day(add_months(sysdate,-2))
)

Best way to handle between in two dates in postgresql on timestamp

i am having date field in my table in the format of yyyy-mm-dd HH:MM:SS wanted to get records between 11-july-2020 inclusive 14-july-2020 but records are missing on 14th. Tries >= && < SYMMETRIC but non of them is working.
currently using select .... from employee where ... and created_on in between ?1 and ?2 . It is excluding record created on 14th.
I think you want:
where col >= '2020-07-11' and col < '2020-7-15'
Or, to express this using timestamps:
where col::timestamp >= '2020-07-11'::timestamp and
col::timestamp < '2020-07-14'::timestamp + interval '1 day'
Note that the higher end is one day later than 2020-07-14, so you can get all times on that day.
You can also use between as:
where col::date between '2020-07-11'::date and '2020-07-14'::date
But I discourage the use of between with date/time data types -- precisely because of the problem that you are having with the time component.
If your field has format yyyy-mm-dd HH:MM:SS it is a timestamp field not a date field. That makes a big difference in the comparison that needs to be done as #Gordon shows. If you compare a timestamp to a date(14-july-2020) the date will be turned into a timestamp with a time of 00:00:00:
select '07/14/2020'::timestamp;
timestamp
---------------------
2020-07-14 00:00:00
That means you will miss the timestamps on the 14th that fall after Midnight of 13/14th.

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

Date range in select

I have this table
CREATE TABLE Table1 (
MY_ID INTEGER NOT NULL,
SCAN_TIME TIMESTAMP NOT NULL,
WORKCELL_ID SMALLINT
);
My problem when I use select SQL to get records between two dates I get empty result if the user select the same date for the two dates
For ex:
Select * from Table1
where SCAN_TIME between '20.9.2014' and '20.9.2014'
Although there are records in that date '20.9.2014' but I get empty result and I get results only if I increase the second date by one day to be '21.9.2014' !! why is that and how I should fix ?
The problem is that you used timestamp as the type, and things messed up due to the time portion. Try to use Date.
When you said between 2014-09-20 and 2014-09-20, you are actually saying between 2014-09-20 midnight and 2014-09-20 midnight, apparently nothing falls in between other than the exact moment of midnight.
If you cannot control the table structure, do what PM 77-1 suggested in his comment below - use cast to cast timestamp into date:
select 1 from table1
where cast(scan_time as date) between 'someday1' and 'someday2';
A TIMESTAMP contains both a date and a time. Since you're not specifying the time in your WHERE clause, it's using the beginning of the day for both times. So you're actually writing the equivalent of:
WHERE SCAN_TIME between '20.9.2014 00:00:00' and '20.9.2014 00:00:00'
Unless the time part of the timestamp is actually 00:00:00, it won't satisfy this criterion. You should convert the timestamp to a date, or specify the times in your range, e.g.
WHERE SCAN_TIME between '20.9.2014 00:00:00' and '20.9.2014 23:59:59'

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