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 BYtime
LIMIT 1' at line 1
What's the best way to do this? Thanks.
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).
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.
The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With