SQL Average Time from timestamp stored as string - sql

I have two columns called date and starthour in a Microsoft SQL Server table.
Both columns are char; Another guy make it and I don't know why it was built in this way. :)
date starthour
20/01/2011 8:10:00
20/01/2011 8:20:00
20/01/2011 8:30:00
20/01/2011 8:40:00
21/01/2011 8:10:00
21/01/2011 8:20:00
21/01/2011 8:30:00
I want to determine the average starthour for each date.
date starthour
20/01/2011 8:25:00
21/01/2011 8:20:00
I tried the following:
SELECT date, Avg(cast(starhour as datetime())) AS starhour
FROM table
GROUP BY date
but it doesn't work.

SELECT [date],
CAST(DATEADD(second, AVG(DATEDIFF(second, 0 , starhour)), '00:00:00') AS time)
FROM dbo.test17
GROUP BY [date]
Demo on SQLFiddle

Let's not beat around the bush: you should fix this schema as soon as possible.
In the meantime, this will return the correct value.
select [date],
CONVERT(VARCHAR(8),
cast((avg(cast(cast(starhour as datetime) as float))) as datetime) , 108)
from table
group by [date]

Do not store dates, datetimes or timestamps as varchar. For instance, MySQL has native types for all three of these types, which guarantees that you won't have invalid data in them, and that MySQL will know how to treat them: http://dev.mysql.com/doc/refman/5.1/en/datetime.html
What you should do is have a single field, date, that is of timestamp type, containing both the date and the time. You should refactor your database and transfer over all your data to the new format by casting it, so that you never have to worry about again.
After that what you need to do differs based on your SQL flavour. For example, this answer will be for MySQL, but every flavour has different datetime functions (unfortunately!).
MySQL's datetime functions are http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Untested but something like:
GROUP BY EXTRACT(day from date)
AVG(EXTRACT(hour from date)*60 + EXTRACT(minute from date))

Related

Is there a quick way to separate date and time from a time stamp in sql?

I am using sql to calculate the average daily temperature and max daily temperature based on a date timestamp in an existing database. Is there a quick way to accomplish this?
I am using dBeaver to do all my data calculations and the following code is what I have used so far:
SELECT
convert(varchar, OBS_TIME_LOCAL , 100) AS datepart,
convert(varchar, OBS_TIME_LOCAL, 108) AS timepart,
CAST (datepart AS date) date_local,
CAST (timepart AS time) time_local
FROM
APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER;
The data format as follows:
ID time_stamp temp
--------------------------------------------
de2145 2018-07-16 16:55 103
There are multiple IDs with 24hrs of temperature data at 1 min increments.
I am not sure if I understand what you need but I will try:
Your question: "Is there a quick way to separate date and time from a time stamp in sql?"
Answer:
select to_char(datec, 'hh24:mi')
, to_char(datec, 'yyyy-mm-dd')
from test;
Use to_char with format to select date part and time part.
You seem to want aggregation:
SELECT convert(date, OBS_TIME_LOCAL) AS datepart,
avg(temp), max(temp)
FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER
GROUP BY convert(date, OBS_TIME_LOCAL);

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 Server 2012 - Datetimeoffset field want to find noon time for each day

I have a database that sample well levels hourly each day for numerous wells. The datetime is in a datetimeoffset field called sampleTime.
I want to filter the data so that I will find 18:00:00 utc time for each day. I cannot seem to find a way to set the time correctly to look for this in an SQL statement. We have SQL Server 2012.
Here is what I have tried.
SELECT
wellID,
CAST(sampleTime AS time(0)) as "welltime",
CAST(sampleTime AS date) as welldate,
sampleTime, waterLevel
FROM
dbo.Real_Time_Water_Level_Data
WHERE
'welltime' = CAST('18:00:00' AS time)
ORDER BY
welldate
I get an message
Conversion failed when converting date and/or time from character string
I am assuming that is in my method of trying to set the '18:00:00' as a what I am looking for. I have tried it without the CAST and using a CONVERT but also getting errors.
What I really would love to get is the local noon time record for each day but I know that I would have to deal with CST and CDT and just decide to get the specific one of 18:00:00
Thanks.
SELECT
wellID,
CAST(sampleTime AS time(0)) as welltime,
CAST(sampleTime AS date) as welldate,
sampleTime, waterLevel
FROM dbo.Real_Time_Water_Level_Data
WHERE CAST(sampleTime AS time(0)) = CAST('18:00:00' AS time)
ORDER BY CAST(sampleTime AS date)
You can't use an alias in the where clause. You query has been modified to that effect.

Selecting all the data using time greater than 4pm

I need to select the Data containing time > 4pm in datatimestamp every day in SQL Server Management Studio Microsoft SQL Server 2005 - 9.00.4060.00 (X64) DB table which has two years of data. What's the best way to do this? My time stamp has following format:DATETIME, '2005-10-13 16:00:00', 102. I have data at random times every afternoon. I need to get the data after 4pm for every day. Not just for one day.
For example i tried for one day like this:
SELECT Yield, Date, ProductType, Direct
FROM MIAC_CCYX
WHERE (Date < CONVERT(DATETIME, '2005-10-13 16:00:00', 102)) Thanks for help
It's hard to read your question, but assuming you really are using a datetime data type, you can use datepart to find any dates with a time greater than 4 PM:
WHERE datepart(hh, YourDate) > 16
Since you now need minutes as well, if you want records after 4:45 PM, you can cast your date to a time like this:
SQL Server 2000/2005
SELECT Yield, [Date], ProductType, Direct
FROM MIAC_CCYX
WHERE cast(convert(char(8), [Date], 108) as datetime) > cast('16:45' as datetime)
Essentially you cast the date using convert's Date and Time styles to convert the date to a time string, then convert back to a datetime for comparison against your desired time.
SQL Server 2008+
SELECT Yield, [Date], ProductType, Direct
FROM MIAC_CCYX
WHERE CAST([Date] as time) > CAST('16:45' as time)
This will work whatever your date is. This will not compare the dates. Rather, Datepart() will extract the hour element from datetime and comapre with your given time (e.g. 4 P.M. in your case)
SELECT * from <table> where DATEPART(hh, ModifiedDate) >= 16
I am assuming ModifiedDate as column name. this will return data from 4 P.M. to 11:59:59 P.M
Edit: I have checked this against MS SQL server 2012. Also it will work with datetime format.

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