EXISTS vs JOIN and use of EXISTS clause

前端 未结 4 1677
萌比男神i
萌比男神i 2020-11-28 04:16

Below is the code sample:

CREATE TABLE #titles(
    title_id       varchar(20),
    title          varchar(80)       NOT NULL,
    type           char(12)           


        
4条回答
  •  天涯浪人
    2020-11-28 05:00

    EXISTS is used to return a boolean value, JOIN returns a whole other table

    EXISTS is only used to test if a subquery returns results, and short circuits as soon as it does. JOIN is used to extend a result set by combining it with additional fields from another table to which there is a relation.

    In your example, the queries are semantically equivalent.

    In general, use EXISTS when:

    • You don't need to return data from the related table
    • You have dupes in the related table (JOIN can cause duplicate rows if values are repeated)
    • You want to check existence (use instead of LEFT OUTER JOIN...NULL condition)

    If you have proper indexes, most of the time the EXISTS will perform identically to the JOIN. The exception is on very complicated subqueries, where it is normally quicker to use EXISTS.

    If your JOIN key is not indexed, it may be quicker to use EXISTS but you will need to test for your specific circumstance.

    JOIN syntax is easier to read and clearer normally as well.

提交回复
热议问题