Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it make sense to use "LIMIT 1" in a query "SELECT 1 ..."?

The question should be clear enough, but is it of any advantage to use instead of

SELECT 1 FROM table ...

SELECT 1 FROM table ... LIMIT 1?

like image 856
Chris Avatar asked Aug 02 '12 19:08

Chris


People also ask

What is the use of LIMIT 1 in SQL?

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.

Can you use LIMIT in subquery?

In Denodo,at this moment Limit is only supported at the end of a SELECT statement to reduce the size of the result set but it cannot be used in subqueries.

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.

Will the reducer work or not if you use LIMIT 1 in any Hiveql query?

Reducer will not run if we use limit in select clause.


1 Answers

Let's say your table has a million rows...

SELECT 1 FROM table ...

Will return the value 1, a million times...

SELECT 1 FROM table ... LIMIT 1

Will return the value 1, one time.


EDIT

You mention that you're specifically interested in regards to an EXISTS check. EXISTS stops processing after the first row is found (which is why EXISTS is more efficient than IN in this case), so with this in mind, there isn't a functional difference between these two queries:

SELECT *
FROM tableA ta
WHERE EXISTS (
    SELECT 1
    FROM TableB tb
    WHERE tb.ID = ta.ID
);

And

SELECT *
FROM tableA ta
WHERE EXISTS (
    SELECT 1
    FROM TableB tb
    WHERE tb.ID = ta.ID
    LIMIT 1
);
like image 157
Michael Fredrickson Avatar answered Oct 06 '22 23:10

Michael Fredrickson