sqlinner-joinintersectsql-except

Is there a fundamental difference between INTERSECT and INNER JOIN?


I understand, that INNER JOIN is made for referenced keys and INTERSECT is not. But afaik in some cases, both of them can do the same thing. So, is there a difference (in performance or anything) between the following two expressions? And if there is, which one is better?

Expression 1:

SELECT id FROM customers 
INNER JOIN orders ON customers.id = orders.customerID;

Expression 2:

SELECT id FROM customers
INTERSECT
SELECT customerID FROM orders

Solution

  • They are very different, even in your case.

    The INNER JOIN will return duplicates, if id is duplicated in either table. INTERSECT removes duplicates. The INNER JOIN will never return NULL, but INTERSECT will return NULL.

    The two are very different; INNER JOIN is an operator that generally matches on a limited set of columns and can return zero rows or more rows from either table. INTERSECT is a set-based operator that compares complete rows between two sets and can never return more rows than in the smaller table.