Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQl Delete top 100 from table

Tags:

sql

I am trying to delete the all but the most recent 3,000 items in a table. The table has 105,000 records.

I am trying this, but an error is generated incorrect syntax.

delete tRealtyTrac where creation in( select top 103000 from tRealtyTrac order by creation)
like image 680
Bryan Avatar asked Apr 30 '09 21:04

Bryan


People also ask

How do I get rid of select top 1000 rows in SQL?

By default in SSMS, you can select 1000 Rows and Edit 200 Rows. If you would like to change the default value then go to SSMS > Tools > Options: In the Options dialog box, highlight SQL Server Object Explorer and change the default values to any number as per your requirements.

Can we use top in delete query?

SQL delete statement and TOP clauseYou can use the TOP statement to delete the rows as well. For example, the below query deletes the top 100 rows from the Orders table.

How do you delete the first 3 rows in SQL?

DELETE FROM table_name WHERE column_name BETWEEN value 1 AND value 2; 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.


3 Answers

The delete syntax is going to be slightly different from what you have. An example would be:

DELETE FROM tRealtyTrac
WHERE creation in( select top 103000 creation from tRealtyTrac order by creation)

Notice how there is the "from" keyword. This is saying we want to delete from the table called tRealtyTrac

The one problem I foresee with this is, you are probably going to want to not use creation...

Instead:

DELETE FROM tRealtyTrac
WHERE someuniqueidcolumnlikeakeyofsomesort in( select top 103000 someuniqueidcolumnlikeakeyofsomesort from tRealtyTrac order by creation)

Otherwise you may delete more than you intended.

like image 184
Brian Avatar answered Oct 12 '22 01:10

Brian


The inner query needs to be:

select top 103000 creation from ...

like image 22
Andy White Avatar answered Oct 12 '22 00:10

Andy White


As for me, CTE is the better solution for ordered deletion

;WITH records_delete AS (
    select top 103000 creation 
    from tRealtyTrac 
    order by creation)
DELETE records_delete 
like image 32
AdvanTiSS Avatar answered Oct 12 '22 00:10

AdvanTiSS