Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete rows with date older than 30 days with SQL Server query

I need a SQL statement to delete row that are older than 30 days.

My table events has a field date that contains the date and the time it was inserted in the database.

Will this work?
SELECT * from Results WHERE [Date] >= DATEADD(d, -30, getdate())

like image 463
Alex Avatar asked Dec 06 '10 09:12

Alex


People also ask

How do I delete old records in SQL Server?

So the delete statement is used to delete rows from a table using the where clause to select only the rows to be deleted. Always use a unique identifier to locate the rows that you need to delete. To delete all the rows in a table, always use TRUNCATE TABLE.

How do I get last 30 days records in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

Can I use limit with delete in SQL?

It is used in the DELETE LIMIT statement so that you can order the results and target those records that you wish to delete. It specifies a limited number of rows in the result set to delete based on row_count. For example, LIMIT 10 would delete the first 10 rows matching the delete criteria.

How do you delete consecutive rows in SQL?

Another way to delete multiple rows is to use the IN operator. DELETE FROM table_name WHERE column_name IN (value 1, value 2, value 3, etc...); If you want to delete all records from the table then you can use this syntax.


2 Answers

Use DATEADD in your WHERE clause:

... WHERE date < DATEADD(day, -30, GETDATE()) 

You can also use abbreviation d or dd instead of day.

like image 97
Colin Mackay Avatar answered Sep 30 '22 14:09

Colin Mackay


You could also use

SELECT * from Results WHERE date < NOW() - INTERVAL 30 DAY; 
like image 37
Vikas Chauhan Avatar answered Sep 30 '22 14:09

Vikas Chauhan