⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Difference between "IN" and "EXISTS" in SQL.

IN

select * from Rating 
where ID_PLAYER in (
    select ID_PLAYER from Players where PLAYER_STATUS = \'Active\'
    );

EXISTS

select * from Rating r
where exists (
    select 1 from Players p
    where  p.ID_PLAYER = r.ID_PLAYER and p.PLAYER_STATUS = \'Active\'
    ); 


Which method is "better"?


The first method: IN

- Easier to write
- Loads all found IDs into memory
- Will behave slower with a large Players table
- May perform poorly without good indexes
- Will throw an error if the subquery returns NULL (for NOT IN)


The second method: EXIST

- Fast search until the first match
- Works better with indexes
- Works much better for correlated subqueries
- Ignores NULL

Performance:

- On small datasets: IN and EXISTS show roughly the same performance.
- On large datasets: EXISTS usually wins.
- For correlated subqueries: EXISTS is usually the best choice.

Why?

Because IN must compare and save each result in the query, whereas EXISTS simply checks for the presence of the required record and continues.

Modern optimizers are actually quite smart and can optimize both query variants quite well, but it's still useful to know the difference.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.