Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT and DELETE

Tags:

java

mysql

I want to select the first row in a table, order by time (ascending), then delete that row. I don't want to use two queries since there's a possibility that another client could select that row before it gets deleted (there will be several machines connected at once from different networks).

I was thinking I could do something like

SELECT * FROM `mytable` ORDER BY `time` LIMIT 1;
    DELETE FROM `mytable` ORDER BY `time` LIMIT 1

...but I got an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '; DELETE * FROM pending ORDER BY time LIMIT 1' at line 1

What's the best way to do this? Thanks.

like image 938
Tom Marthenal Avatar asked Dec 03 '10 22:12

Tom Marthenal


People also ask

Which is faster select or delete?

The select query runs much faster than a similar delete query. Delete does more work than select. But how many rows are found, and how many rows are deleted? (Which should be the same number, of course).

What select * means?

SELECT == It orders the computer to include or select each content from the database name(table ) . (*) == means all {till here code means include all from the database.} FROM == It refers from where we have to select the data. example_table == This is the name of the database from where we have to select data.

What is select used for?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.


3 Answers

Re your error message (different than in your question):

DELETE * FROM pending ORDER BY time LIMIT 1

Looks like an error in your syntax. Try removing the *. That is,

DELETE FROM pending ORDER BY time LIMIT 1

Should work fine.

like image 144
Riedsio Avatar answered Oct 01 '22 06:10

Riedsio


You have to create a temporary table, MySQL doesn't let you delete from a table that you are using, see this code:

insert  tmpTable
        (id)
select  id
from    YourTable yt
order by time limit 1;

delete  
from    YourTable
where   ID in (select id from tmpTable);
like image 24
Eduardo Rascon Avatar answered Oct 01 '22 05:10

Eduardo Rascon


You can use sub-queries like.

delete from table where id in ( select id from table order by time limit 1);

Performance wise am not sure, how good is this solution. You might have to do a analyze and see how this works for you.

like image 29
Vanchinathan Chandrasekaran Avatar answered Oct 01 '22 05:10

Vanchinathan Chandrasekaran