SELECT EXISTS vs. LIMIT 1

那年仲夏 提交于 2020-12-04 03:18:30

问题


I see SELECT EXISTS used a lot like:

    if db.query("""
        SELECT EXISTS (
            SELECT 1 FROM checkout
            WHERE checkout_id = %s
        )
    """ % checkout_id).getresult()[0][0] == 't':

vs. what i prefer:

    if db.query("""
        SELECT 1 FROM checkout
        WHERE checkout_id = %s
        LIMIT 1
    """ % checkout_id).getresult():

Which one is preferred and why?

P.S. i am using Python and PosgreSQL.

cert=> explain SELECT EXISTS (SELECT 1 FROM checkout WHERE checkout_id = 3);
                                      QUERY PLAN                                      
--------------------------------------------------------------------------------------
 Result  (cost=4.03..4.03 rows=1 width=0)
   InitPlan
     ->  Index Scan using checkout_pkey on checkout  (cost=0.00..4.03 rows=1 width=0)
           Index Cond: (checkout_id = 3)
(4 rows)

cert=> explain SELECT 1 FROM checkout WHERE checkout_id = 3 limit 1;
                                     QUERY PLAN                                     
------------------------------------------------------------------------------------
 Limit  (cost=0.00..4.03 rows=1 width=0)
   ->  Index Scan using checkout_pkey on checkout  (cost=0.00..4.03 rows=1 width=0)
         Index Cond: (checkout_id = 3)
(3 rows)

My point is, why getting a row from the result and check if it's first column is true, if i can just check if there are any rows at all, meaning the same?


回答1:


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.




回答2:


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




回答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;


来源:https://stackoverflow.com/questions/10598935/select-exists-vs-limit-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!