Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any point in using LIMIT in EXISTS query?

Is there any performance benefit in adding a LIMIT to an EXISTS query, or would MySQL apply the limit on its own?

Example:

IF EXISTS (
    SELECT 1
      FROM my_table
     LIMIT 1    -- can this improve performance?
)
THEN ... END IF;
like image 646
shmosel Avatar asked Jan 13 '16 05:01

shmosel


People also ask

Does limit improve query performance?

Yes, you will notice a performance difference when dealing with the data. One record takes up less space than multiple records.

What is the use of limit in SQL query?

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 the use of limit clause with SELECT query?

The LIMIT clause can restrict the result set of the query to some maximum number of rows. If this clause specifies a value smaller than the number of qualifying rows, the query returns only a subset of the rows that satisfy the selection criteria.

What can I use instead of limits in SQL?

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

The purpose of EXISTS() is to perform the query only until it can decide if there are any rows in that table matching the WHERE clause. That is, it logically does the same thing as LIMIT 1. EXISTS is probably called semi-join in some circles.

Bottom line: Don't use LIMIT 1 inside EXISTS().

Addenda: As Paul points out, a LIMIT with an OFFSET (or LIMIT m,n) does have meaning.

like image 193
Rick James Avatar answered Sep 16 '22 15:09

Rick James