Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LIMIT 1 in MySQL

Tags:

mysql

When is it appropriate to add LIMIT 1 at the end of the query in MySQL. I normally add it in DELETE but I've seen it being used with INSERT a and even UPDATE. Is it an overkill or a good practice?

like image 500
santa Avatar asked May 07 '11 21:05

santa


People also ask

What is the use of LIMIT 1 in MySQL?

The LIMIT clause is used to specify the number of records to return. The LIMIT clause is useful on large tables with thousands of records. Returning a large number of records can impact performance.

What is meant by LIMIT 1 in SQL?

This LIMIT clause would return 3 records in the result set with an offset of 1. What this means is that the SELECT statement would skip the first record that would normally be returned and instead return the second, third, and fourth records.

What is LIMIT 2 1 SQL query?

LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements). To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter.


1 Answers

 INSERT INTO .. VALUES () LIMIT 1 

Doesn't exist. Hopefully you know how many VALUES() you put in there!

 INSERT INTO .. SELECT ... LIMIT 1 

Does exist and is pretty useful, and off topic since the LIMIT is on the SELECT.

 DELETE ... LIMIT 1  UPDATE ... LIMIT 1 

Extremely rarely useful. Either you know your database enough to be certain that your WHERE matches a UNIQUE condition, or you don't, in which case you should spend a little more time looking at your database and learning SQL.

But ...

 UPDATE jobs SET owner=me WHERE owner IS NULL ORDER BY job_submit_time LIMIT 1 

Can be extremely useful! This makes a near-lockless job queue, where you can come and take a job from the queue without any waiting, locking, or conflict resolution. Quite excellent.

 DELETE FROM cache ORDER BY last_update_time LIMIT N 

Cache takes too much space ? Purge the N oldest rows...

like image 104
bobflux Avatar answered Sep 25 '22 07:09

bobflux