The Python Oracle

SELECT EXISTS vs. LIMIT 1

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle2

--

Chapters
00:00 Question
01:05 Accepted answer (Score 3)
01:38 Answer 2 (Score 8)
01:53 Answer 3 (Score 2)
02:20 Thank you

--

Full question
https://stackoverflow.com/questions/1059...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sql #postgresql

#avk47



ANSWER 1

Score 9


To my eye the second statement is problematic in that it will not return a row if the condition is not satisfied.




ACCEPTED ANSWER

Score 5


PostgreSQL seems to clever enough to treat both statements alike as you can clearly see in your execution plans.

My tests with a local table with ~150000 rows and ~100 selected out of that by the condition also show the same behaviour

The bottomline is: it doesn't really matter which one you use, but you should be aware that other DBMS might not behave in the same way.




ANSWER 3

Score 3


When you use EXPLAIN you can see that the first statement will execute an additional subquery and the second does not.

That is why I would prefer using limit instead of exists

Example:

explain SELECT EXISTS (SELECT 1 FROM checkout WHERE id = 3);
explain SELECT 1 FROM checkout WHERE id = 3 limit 1;