Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete where id is the biggest

Tags:

mysql

I would like to detele the row with the biggest order_id, I tried this:

DELETE FROM orders WHERE MAX(order_id)

But this is wrong! any other ideas?

Thank you for your time.

like image 923
TooCooL Avatar asked Nov 29 '22 16:11

TooCooL


1 Answers

First idea (among many others that had exactly the same):

DELETE FROM orders 
WHERE order_id = 
      ( SELECT MAX(order_id)
        FROM orders
      )

Unfortunately MySQL complains with:

> ERROR 1093 (HY000): You can't specify target table 'orders' for update in FROM
> clause

Two ways to bypass the error:

DELETE FROM orders 
WHERE order_id =
       ( SELECT maxo
         FROM  
           ( SELECT MAX(order_id) AS maxo
             FROM orders
           ) AS tmp
        )

or:

DELETE FROM orders
ORDER BY order_id DESC
LIMIT 1 
like image 172
ypercubeᵀᴹ Avatar answered Dec 20 '22 10:12

ypercubeᵀᴹ