Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting record with lowest ID

Tags:

mysql

When I type this query in MySQL :

DELETE FROM myTable WHERE ID = ( SELECT Min( ID ) FROM myTable )

I get the following error message :

#1093 - You can't specify target table 'myTable' for update in FROM clause

What is the problem ?

What is the right equivalent ?

like image 444
LeGEC Avatar asked Mar 22 '12 09:03

LeGEC


People also ask

Is WHERE clause mandatory in DELETE statement?

If you run a DELETE statement with no conditions in the WHERE clause, all of the records from the table will be deleted. As a result, you will most often include a WHERE clause with at least one condition in your DELETE statement.

How do I remove a primary key from a record?

Use SQL Server Management Studio In Object Explorer, expand the table that contains the primary key and then expand Keys. Right-click the key and select Delete. In the Delete Object dialog box, verify the correct key is specified and select OK.


2 Answers

Basically in MySQL you can't do an update on a table which you use in the SELECT part. For detail you could check this behaviour which is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html

In theory every DELETE is an UPDATE so that's why you get this error.

You could simply do following:

DELETE FROM myTable 
ORDER BY my_id
LIMIT 1;
like image 142
huzeyfe Avatar answered Sep 22 '22 07:09

huzeyfe


try

DELETE FROM myTable ORDER BY ID LIMIT 1;

like image 33
Guillaume USE Avatar answered Sep 22 '22 07:09

Guillaume USE