Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Top-N' Rows from a Table with some sorting(order by 'Column')

I am having some confusion regarding Deleting the top N Rows order by some column.

I created have an example here Example at fiddle

What is wrong with these queries?

 Delete Top(3) from Table1 order by id desc   Delete Top(3) from Table1   where id IN (select id from Table1 order by id desc) 

Since in mysql the limit keyword does the job very well

like image 831
Shah Avatar asked Nov 22 '12 08:11

Shah


People also ask

Can we use order by in delete query?

You can't DELETE TOP (x) with an ORDER BY.


2 Answers

You can use a CTE to do a faster ordered delete without the need for a separate sub query to retrieve the top 3 ids.

WITH T      AS (SELECT TOP 3 *          FROM   Table1          ORDER  BY id DESC) DELETE FROM T  
like image 188
Martin Smith Avatar answered Oct 14 '22 04:10

Martin Smith


Add the top 3 clause to the subselect:

Delete from Table1  where id IN (     select top 3 id      from Table1      order by id desc ) 
like image 22
Cristian Lupascu Avatar answered Oct 14 '22 03:10

Cristian Lupascu