Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does adding 'LIMIT 1' to MySQL queries make them faster when you know there will only be 1 result?

When I add LIMIT 1 to a MySQL query, does it stop the search after it finds 1 result (thus making it faster) or does it still fetch all of the results and truncate at the end?

like image 482
Logan Serman Avatar asked Jan 18 '09 17:01

Logan Serman


People also ask

What does limit 1 do in MySQL?

3) Using MySQL LIMIT to get the nth highest or lowest value The clause LIMIT n-1, 1 returns 1 row starting at the row n . As you can see clearly from the output, the result was correct as expected.

What is the purpose of limit clause in database queries?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.


1 Answers

Depending on the query, adding a limit clause can have a huge effect on performance. If you want only one row (or know for a fact that only one row can satisfy the query), and are not sure about how the internal optimizer will execute it (for example, WHERE clause not hitting an index and so forth), then you should definitely add a LIMIT clause.

As for optimized queries (using indexes on small tables) it probably won't matter much in performance, but again - if you are only interested in one row than add a LIMIT clause regardless.

like image 71
Eran Galperin Avatar answered Sep 30 '22 17:09

Eran Galperin