Which SQL query is faster? Filter on Join criteria or Where clause?

前端 未结 9 1001
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 03:36

Compare these 2 queries. Is it faster to put the filter on the join criteria or in the WHERE clause. I have always felt that it is faster on the join criteria b

9条回答
  •  佛祖请我去吃肉
    2020-11-27 04:03

    Performance-wise, they are the same (and produce the same plans)

    Logically, you should make the operation that still has sense if you replace INNER JOIN with a LEFT JOIN.

    In your very case this will look like this:

    SELECT  *
    FROM    TableA a
    LEFT JOIN
            TableXRef x
    ON      x.TableAID = a.ID
            AND a.ID = 1
    LEFT JOIN
            TableB b
    ON      x.TableBID = b.ID
    

    or this:

    SELECT  *
    FROM    TableA a
    LEFT JOIN
            TableXRef x
    ON      x.TableAID = a.ID
    LEFT JOIN
            TableB b
    ON      b.id = x.TableBID
    WHERE   a.id = 1
    

    The former query will not return any actual matches for a.id other than 1, so the latter syntax (with WHERE) is logically more consistent.

提交回复
热议问题