MSSQL Obtain the last entries added in the last 30 seconds? - sql-server

I want to obtain the last entries in the last 30 seconds from a MSSQL database.
In Mysql you do:
SELECT * FROM table WHERE datetime > (now() - interval 30 second)
How to do that in MSSQL?

DATEDIFF is your solution here.
SELECT
*
FROM
[table]
WHERE
DATEDIFF(second, [datetime], GETDATE()) < 30

Using dateadd with a negative integer will give you the data you are asking for
DATEADD (Transact-SQL)
SELECT
*
FROM
table
WHERE
datetime >= DATEADD(SECOND,-30,datetime)

You can use GETDATE() in combindation with DATEADD:
SELECT * FROM table WHERE datetime > (DATEADD(second,-30,getdate()))

Use DATEADD()
DATEADD(SECOND,-30,GETDATE())

Related

SQL Server : return boolean if timestamp is within 1 minute

Disclaimer that I am very novice on SQL writing...
How would I return a single boolean if any record within the query has a timestamp updated within the last 1 minute.
SELECT *
FROM myTable
WHERE mytimestamp >= NOW() - INTERVAL 1 MINUTE
Thanks!
This will give you one row if there is any record matching the criteria:
select exists (
select 1 from mytable where mytimestamp >= dateadd(minute, -1, getdate()) )
You could use current_timestamp which is ANSI SQL equivalent of getdate().

SQL Server- Get Date 6 months in past

Hey how would I get data for a date column that's older than 6 months?
select * from myTable where dateColumn >
Thanks
Use DATEDIFF function.
Read more here: https://msdn.microsoft.com/en-us/library/ms189794.aspx
SELECT *
FROM myTable
WHERE DATEDIFF(MM, dateColumn, GETDATE()) > 6
SELECT * FROM myTable WHERE DATEDIFF(day, NOW(), dateColumn) > 180
select *
from table
where
date_column >=
DATEADD(m, -6, convert(date, convert(varchar(6), getdate(),112) + '01'))
I would use
select * from myTable where dateColumn > DATEADD(mm,GETDATE(),-6)
This way you arent applying a function on the lookup column, which in some cases can result in performance issues
Dateadd is very simple to use.
the first parameter is the interval, m means month, d means day ect. the second parameter is the increment, and the last one is obviously the date
select dateadd(m,6,getdate())
more info here
http://www.w3schools.com/sql/func_dateadd.asp
Once you understand dateadd then you can simply use it in where clause as such
Select * from Table1 where date1 >= dateadd(m,6,date1)

Why DATEDIFF in SQL Server returning error while interval is set to second

While running following query
select DATEDIFF(SECOND, 0, DATEADD(SECOND, -1, '2014-04-11 23:52'))
I am getting following error message, no matter whatever the date I provide to it.
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
Datediff takes these parameters: interval, starting_date, ending_date, so your SELECT is trying to find difference in seconds between server default for starting_date and your date.
When you specified 0 as starting_date, MS SQL replaced it with '1900-01-01 00:00'. The returned seconds where ~3606249060, but the DATEDIFF returns int, and the seconds returned where larger than datatype int could handle.
It works fine if you specify minute instead of second, because it'll return 60104151, which is int
You could use similar select to find difference in seconds between now and your defined date:
select DATEDIFF(SECOND, GETDATE(), DATEADD(SECOND,-1,'2014-04-11 23:52'))
If you put your hard-coded date as starting_date parameter, then you'll get -1 second difference (due to DATEADD you've used):
select DATEDIFF(SECOND, '2014-04-11 23:52', DATEADD(SECOND,-1,'2014-04-11 23:52'))
According to this DateDiff is not working because difference between 2 dates in Interval of Seconds is more than 68 years.
First argument in DateDiff as 0 means it is '1900-01-01 00:00:00.000', and difference with '2014-04-11 23:52' is more than 68 years.
Your current query results in a bigint, DATEDIFF can only return an integer. That is why you get overflow
3597523200 is the seconds between year 1900 and 2014
Try this instead:
SELECT 3597523200
+ DATEDIFF(S, '2014', DATEADD(SECOND,-1,'2014-04-11 23:52'))
This would be the same as:
SELECT CAST(DATEDIFF(S, '1900', '1950') AS BIGINT)
+ DATEDIFF(S, '1950', '2014')
+ DATEDIFF(S, '2014', DATEADD(SECOND,-1,'2014-04-11 23:52'))

How to get number of rows with timestamp between 10am and now?

I am trying to run a T-SQL query that would return all rows that contain a timestamp between 00:00:00 and now for any given date.
I've used the following code, but this only returns items within the past 24 hours:
SELECT *
FROM table
WHERE timestamp_closed = DATE(GETDATE()-1);
Here you have the number of rows:
SELECT COUNT(*)
FROM *yourtable*
WHERE timestamp_closed BETWEEN CAST(GETDATE() AS DATE) AND GETDATE()
SELECT *
FROM table
WHERE timestamp_closed BETWEEN CAST(GETDATE() AS DATE) AND GETDATE()
You could build the datevalue for "Today at 00:00:00" and now and then do a
WHERE timestamp_closed >= "Today at 00:00:00" and timestamp_closed<=GETDATE()
You can probably wrap this in a function.
select *
from table
where datepart(hh,timestamp_closed)*100 + datepart(mi,timestampclosed) <
datepart(hh,getdate())*100 + datepart(mi,getdate())
SELECT *
FROM table
WHERE (timestamp_closed > CAST(#specificDate AS DATE)
AND timestamp_closed <= GETDATE())

SQL Server remove milliseconds from datetime

select *
from table
where date > '2010-07-20 03:21:52'
which I would expect to not give me any results... EXCEPT I'm getting a record with a datetime of 2010-07-20 03:21:52.577
how can I make the query ignore milliseconds?
You just have to figure out the millisecond part of the date and subtract it out before comparison, like this:
select *
from table
where DATEADD(ms, -DATEPART(ms, date), date) > '2010-07-20 03:21:52'
If you are using SQL Server (starting with 2008), choose one of this:
CONVERT(DATETIME2(0), YourDateField)
LEFT(RTRIM(CONVERT(DATETIMEOFFSET, YourDateField)), 19)
CONVERT(DATETIMEOFFSET(0), YourDateField) -- with the addition of a time zone offset
Try:
SELECT *
FROM table
WHERE datetime >
CONVERT(DATETIME,
CONVERT(VARCHAR(20),
CONVERT(DATETIME, '2010-07-20 03:21:52'), 120))
Or if your date is an actual datetime value:
DECLARE #date DATETIME
SET #date = GETDATE()
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(20), #date, 120))
The conversion to style 120 cuts off the milliseconds...
select * from table
where DATEADD(ms, DATEDIFF(ms, '20000101', date), '20000101') > '2010-07-20 03:21:52'
You'll have to trim milliseconds before comparison, which will be slow over many rows
Do one of these to fix this:
created a computed column with the expressions above to compare against
remove milliseconds on insert/update to avoid the read overhead
If SQL Server 2008, use datetime2(0)
Use CAST with following parameters:
Date
select Cast('2017-10-11 14:38:50.540' as date)
Output: 2017-10-11
Datetime
select Cast('2017-10-11 14:38:50.540' as datetime)
Output: 2017-10-11 14:38:50.540
SmallDatetime
select Cast('2017-10-11 14:38:50.540' as smalldatetime)
Output: 2017-10-11 14:39:00
Note this method rounds to whole minutes (so you lose the seconds as well as the milliseconds)
DatetimeOffset
select Cast('2017-10-11 14:38:50.540' as datetimeoffset)
Output: 2017-10-11 14:38:50.5400000 +00:00
Datetime2
select Cast('2017-10-11 14:38:50.540' as datetime2)
Output: 2017-10-11 14:38:50.5400000
For this particular query, why make expensive function calls for each row when you could just ask for values starting at the next higher second:
select *
from table
where date >= '2010-07-20 03:21:53'
Use 'Smalldatetime' data type
select convert(smalldatetime, getdate())
will fetch
2015-01-08 15:27:00
There's more than one way to do it:
select 1 where datediff(second, '2010-07-20 03:21:52', '2010-07-20 03:21:52.577') >= 0
or
select *
from table
where datediff(second, '2010-07-20 03:21:52', date) >= 0
one less function call, but you have to be beware of overflowing the max integer if the dates are too far apart.
One more way I've set up SQL Server queries to ignore milliseconds when I'm looking for events from a particular second (in a parameter in "YYYY-MM-DD HH:TT:SS" format) using a stored procedure:
WHERE
...[Time_stamp] >= CAST(CONCAT(#YYYYMMDDHHTTSS,'.000') as DateTime) AND
...[Time_stamp] <= CAST(CONCAT(#YYYYMMDDHHTTSS,'.999') as DateTime)
You could use something similar to ignore minutes and seconds too.
Please try this
select substring('12:20:19.8470000',1,(CHARINDEX('.','12:20:19.8470000',1)-1))
(No column name)
12:20:19
I'm very late but I had the same issue a few days ago. None of the solutions above worked or seemed fit. I just needed a timestamp without milliseconds so I converted to a string using Date_Format and then back to a date with Str_To_Date:
STR_TO_DATE(DATE_FORMAT(your-timestamp-here, '%Y-%m-%d %H:%i:%s'),'%Y-%m-%d %H:%i:%s')
Its a little messy but works like a charm.
May be this will help..
SELECT [Datetime] = CAST('20120228' AS smalldatetime)
o/p:
2012-02-28 00:00:00
Review this example:
declare #now datetimeoffset = sysdatetimeoffset();
select #now;
-- 1
select convert(datetimeoffset(0), #now, 120);
-- 2
select convert(datetimeoffset, convert(varchar, #now, 120));
which yields output like the following:
2021-07-30 09:21:37.7000000 +00:00
-- 1
2021-07-30 09:21:38 +00:00
-- 2
2021-07-30 09:21:37.0000000 +00:00
Note that for (1), the result is rounded (up in this case), while for (2) it is truncated.
Therefore, if you want to truncate the milliseconds off a date(time)-type value as per the question, you must use:
declare #myDateTimeValue = <date-time-value>
select cast(convert(varchar, #myDateValue, 120) as <same-type-as-#myDateTimeValue>);

Resources