Sunday, 10 May 2015

SQL: NOT IN , NOT EXISTS and MINUS in Oracle SQL (Performance)

Lets drive directly to example.

Followings are the two tables with data

 Table  X                   Table Y
     a                                 b
--------------             --------------
    1                                  1
    NULL                         2

-----------------------------------------------------------------------

  1)  NOT IN
==========================================
Select  b from Y where b is NOT IN  (Select a from X);

Output
-----------------
0 rows

Why 0 Rows?  Any guess?

The target table X consists of the NULL records causing the the NOT IN implementation of SQL return false , hence NO rows selected.

What should  we do to get the correct result ?
The answer is use NOT EXIST.

2) NOT EXIST
==================================================
Select b from Y y where NOT EXISTS (Select 1 from X x where x.a=y.b );
output
---------------
2

The NOT EXISTS returns the intended  output.

3) MINUS (EXCEPT- sql server)
=====================================
select b from Y
 MINUS
select a from X

output
-----------------
2

Whats the difference between the EXCEPT and NOT-EXISTS  ?
 1. EXCEPT operator returns all distinct rows from left hand side table which does not exist in right hand side table.
 2.  EXCEPT adds the sorts and the records and removes the duplicates, however NOT EXIST does not removes duplicates.
3. The recommendation is to use the NOT EXIST as it doesn't add the performance overhead of buffer sort.

No comments:

Post a Comment