Delete items older than a day - SQL Server - sql

In a table in my datatase I have a datatime column which stores the time at which the record is added. How can I delete all records which are older than a day when I run a stored procedure (considering the current time) ?

You can build a DELETE statement making use of the datediff and the getdate functions.
Usage example:
DELETE FROM yourTable WHERE DATEDIFF(day,getdate(),thatColumn) < -1

When it comes to SQL, you have to specify what you mean by "older than a day".
DATEDIFF: it uses day boundary midnight so run it at 19th October 00:05 and you'll delete rows 6 minutes old (18th October 23:59)
24 hours?
Yesterday midnight? Run code on 19th October, delete rows before 18th?
Also, don't put a function on a column.
This assumes 24 hours to the minute:
DELETE
MyTableWhere
WHERE
MyColumn < DATEADD(day, -1, GETDATE())
This assumes yesterday midnight:
DELETE
MyTableWhere
WHERE
MyColumn < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), -1)

Delete <TableName>
Where DATEDIFF(day, <ColumnName>, getdate()) > 0
Raj

I generally advise against actually deleting data from your database because you never know when you may need to go back and recover or rollback to previous records because of data corruption or an audit, etc. Instead I would add an bit column title something like "IsDeleted" and set day old entries to true using an update statement.
Something like
'UPDATE tablename SET IsDeleted = 1 WHERE (DATEDIFF(day,DateCreatedOn,GETDATE()) > 0)
Where DateCreatedOn is where your record's created on or timestamp date would go

Assuming date column to be "RecordCreatedDate"
DELETE FROM yourtable WHERE RecordCreatedDate < DATEADD(d, -1, GETDATE())
I only caution that if your database has millions of rows your should have an index on the RecordCreatedDate column and possibly do smaller batch deletes if you will be removing large amounts of data.

delete from YourTable where DateColumn < getdate()-1

or
ts >= now() - INTERVAL 1 DAY
where ts is a name of the datetime column

Related

SQL Date less than few days from today

I have a table in which I have emails to users and I want to make request to take users who are dated less than two days from today. How can make this?
This is my SQL table :
CREATE TABLE vacation_users(EMAIL VARCHAR(255), STARTDATE DATE, ENDDATE DATE);
The answer is this. I use HSQLDB and this is answer.
SELECT * FROM vacation_user WHERE (ENDDATE < (SYSDATE + 2 DAY));
Try this(not tested):
SELECT EMAIL from vacation_users
WHERE ENDDATE < DATEADD(day, +2, CURRENT_DATE) AND ENDDATE > CURRENT_DATE
It selects the mails, which have the enddate, which is equal bigger than current date, but smaller than current date + 2.
EDIT: I updated the answer, since the OP informed me about the DB, which is used. If CURRENT_DATE also doesn't work, you can try another from the built-in functions.
select *
from vacation_users
where STARTDATE = dateadd(day,datediff(day,2,STARTDATE),0)
That depends on a database you use, but the principle is more or less the same.
In Oracle, you'd do something like
select email
from vacation_users
where startdate < sysdate - 2;
which returns you to exact time 2 days ago (if it is 09:53 today, it'll be 09:53 2 days ago). Depending on what you really need, you might need to TRUNCate those values (so that you'd get date without its time component) or apply some other function or principle, regarding possible index impact etc.
Though, "dated less than two days from today" is ... what exactly? Is it a STARTDATE or ENDDATE (or some combination of those two)?
SELECT *
FROM vacation_users
WHERE (DATEADD(day,2,ENDDATE)) < (CONVERT(date, SYSDATETIME()))

Dropping mssql data records for records older than xx days

I'm trying to drop all the records from my DB where the records are OLDER than 3 days.
I've written something like this:
delete from Results WHERE [Date] > DATEADD(d, -3, getdate())
I wanted to check whether this sql query is correct since I'm worried that I might make a mistake and delete more than I should...
this this query correct?
Your code is deleting everything newer than 3 days old, and should be:
DELETE FROM Results WHERE [Date] < DATEADD(DAY, -3, GETDATE())
Otherwise, this is fine for deleting everything that is older than exactly 72 hours, although as others have said you should definitely be testing either on a copy of the data or at least by using SELECT statement
SELECT * FROM Results WHERE [date] < DATEADD(DAY, -3, GETDATE())
However, if you want to delete everything that happened before three days ago (e.g. It is now Monday, and I want to delete everything that happened before Friday) you would need to eliminate the time aspect.
DELETE FROM Results WHERE CONVERT(DATE, [date]) < DATEADD(DAY, -3, GETDATE())
Always check WHERE clause in SELECT clause before update or delete statement :
SELECT DATEADD(d, -3, getdate())
First check your WHERE clause in SELECT statement.It gives your expected date means continue with same WHERE clause in DELETE.

SQL query to delete records from a query

I am trying to write 2 queries to delete records where dates are greater than a certain date:
The first one:
delete from RPT_HistSnapEng_temp
where ForecastDate> DATEADD(WEEK,7,CAST(GETDATE() AS DATE))
This query deletes records when forecastdate is greater than 7 weeks from today
The second one is:
delete from RPT_HistSnapEng_temp
where ForecastDate< DATEADD(WEEK,-6,CAST(GETDATE() AS DATE))
This query deletes records when forecastdate is less than 6 weeks from today.
So basically, this should filter out records from Dec 2015 - Nov 2016 and only show records from previous 6 weeks and next 7 weeks from today.
Even though the query runs, its not deleting records. I cannot hardcode dates because I will be using this query on a rolling basis inside a SSIS package.
Your current where clauses are trying to grab records that are both less than a date in the past AND greater than a date in the future. I think you (and the other answer) should be using or.
But, since this looks like a temp table that you are loading to then report with, I would adjust your insert to simply grab the records you are looking for, rather than loading more than you need and then deleting.
select *
from RPT_HistSnapEng -- base table name?
where cast(ForecastDate as date) between dateadd(week, -6, cast(current_timestamp as date)) and dateadd(week, 7, cast(current_timestamp as date))
Just add your insert to that if it gets the records you need.
However, to directly answer your question about deletes, you can change this query to simply use NOT between:
delete
from RPT_HistSnapEng_temp
where cast(ForecastDate as date) not between dateadd(week, -6, cast(current_timestamp as date)) and dateadd(week, 7, cast(current_timestamp as date))
As you can see, I like the use of between (which is inclusive of the date arguments) for this type of range check rather than getting caught up in using >= and < or confusing the and and or which you've seemingly done. I also like the ANSI standard current_timestamp over the t-sql specific getdate() but they are equivalent.
Try "ww" or "wk" instead of "week" in the dateadd function. Try a SELECT statement to get the records you want to delete:
SELECT ID, ForecastDate
FROM RPT_HistSnapEng_temp
WHERE CAST(ForecastDate AS DATE) > DATEADD(ww,7,CAST(GETDATE() AS DATE))
OR CAST(ForecastDate AS DATE) < DATEADD(WEEK,-6,CAST(GETDATE() AS DATE))
ORDER BY ForecastDate
To Delete just remove the SELECT and the ORDER BY:
DELETE
FROM RPT_HistSnapEng_temp
WHERE CAST(ForecastDate AS DATE) > DATEADD(ww,7,CAST(GETDATE() AS DATE))
OR CAST(ForecastDate AS DATE) < DATEADD(WEEK,-6,CAST(GETDATE() AS DATE))

How to count number of records present in a date range between a fixed time in SQL Server?

I need to get the number of records present in my [RecordsTable] for the last 3 months.
However the catch is I need the records which are processed between 10PM and 2AM.
For example --
07/01/2015 10PM -- 07/02/2015 2AM
07/02/2015 10PM -- 07/03/2015 2AM
07/03/2015 10PM -- 07/04/2015 2AM
The below SQL gives me the records present on any particular day starting from May,2015.
But I am not able to get the timing(10PM-2AM of next day) embedded in the SQL and need some help.
SELECT CONVERT(VARCHAR(12), RecordDate, 101),count(RecordID)
FROM [RecordsTable](NOLOCK)
WHERE RecordDate > '2015-05-01'
GROUP BY CONVERT(VARCHAR(12), RecordDate, 101)
MSSQL Supports both Date and Time datatypes. You can break up your where statement to reflect both date and time conditions separately.
SELECT COUNT(Records)
FROM TABLE
WHERE CONVERT(Date,DateCol) BETWEEN 'MM/DD/YYYY' AND 'MM/DD/YYYY'
AND CONVERT(Time,DateCol) BETWEEN 'HH:MM:SS' AND 'HH:MM:SS'
Try the following:
SELECT count(1)
FROM RecordsTable
WHERE RecordDate > '2015-05-01'
AND NOT DATEPART(hour, RecordDate) BETWEEN 2 AND 21
I assume RecordDate is a datetime or datetime2 column. between 2 and 21 will return rows where the hour for RecordDate is between 2am and 9pm, inclusive. NOT between 2 and 21 will return the reverse, giving you data for 10pm, 11pm, 12pm, and 1am. This does not include any time between 2:00am and 2:59am. If you need to include events that occurred precisely at but not after 2:00am, things get a bit tricker, but similar code based on not between would apply.
To get records in the last 3 months you can use two ways -- one by month looks like this
WHERE MONTH(colname) >= MONTH(GETDATE()) -3
This will get you inclusive months but not partial months. To get partial months is a bit more tricky because you could mean (for example for today) the 9th day of 3 months ago or you could mean 90 days ago. In the first case this works
WHERE colname >= dateadd(month,-3, getdate())
and for 90 days ago
WHERE colname >= dateadd(day,-90, getdate())
To get between 10PM and 2AM use this
WHERE datepart(hour,colname) >= 22 OR datepart(hour,colname) <= 2
Use DATEPART
SELECT COUNT(1)
FROM Table1
WHERE RecordDate > '2015-05-01'
AND (DATEPART(HOUR, RecordDate) <= 2 OR DATEPART(HOUR, RecordDate) >= 22)
Try this
SELECT count(*) FROM tablename where created_at>='2015-03-17 07:15:10' and created_at<='2015-07-09 02:23:50';
You can even use between
SELECT count(*) FROM tablename where created_at between '2015-03-17 07:15:10' and '2015-07-09 02:26:50';
You can use curdate() to get today's date

Using Dates as a SQL Filter

I have a table of data that goes quite some time back, but I only want to results in my query for the last 13 weeks. There is a date column in that table.
I can use
SELECT DATEADD(Week, -13, GETDATE())
to get the date of 13 weeks back as a separate query - but I am having trouble linking that into the initial select to only return me the last 13 weeks of data. I have used that query as the data should refresh every day to go back 13 weeks to that date.
Is there any way I can do that?
Thanks in advance
This should be what you are looking for:
SELECT *
FROM TABLE_NAME
WHERE date_field >
(SELECT DATEADD(Week, - 13, GETDATE()))
I'm a bit confused on what your issue is. You should be able to use the dateadd() in your where clause:
SELECT *
FROM TABLE
WHERE DATECOLUMNTOCOMPARE > DATEADD(WEEK,-13,GETDATE())