Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all but top n from database table in SQL

Tags:

sql

What's the best way to delete all rows from a table in sql but to keep n number of rows on the top?

like image 776
Riri Avatar asked Sep 05 '08 17:09

Riri


People also ask

How do I delete multiple records from a table in SQL Server?

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

DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table) 

Edit:

Chris brings up a good performance hit since the TOP 10 query would be run for each row. If this is a one time thing, then it may not be as big of a deal, but if it is a common thing, then I did look closer at it.

like image 179
Cory Foy Avatar answered Sep 29 '22 06:09

Cory Foy


I would select ID column(s) the set of rows that you want to keep into a temp table or table variable. Then delete all the rows that do not exist in the temp table. The syntax mentioned by another user:

DELETE FROM Table WHERE ID NOT IN (SELECT TOP 10 ID FROM Table) 

Has a potential problem. The "SELECT TOP 10" query will be executed for each row in the table, which could be a huge performance hit. You want to avoid making the same query over and over again.

This syntax should work, based what you listed as your original SQL statement:

create table #nuke(NukeID int)  insert into #nuke(Nuke) select top 1000 id from article  delete article where not exists (select 1 from nuke where Nukeid = id)  drop table #nuke 
like image 41
Chris Miller Avatar answered Sep 29 '22 04:09

Chris Miller