Home > Net >  Need help to understand EXISTS behaviour/return
Need help to understand EXISTS behaviour/return

Time:09-27

I am a beginner. As I understand, EXISTS will return true if the subquery contains any rows. Does that mean there's only one boolean returned?

 SELECT * FROM TABLE1 T1 WHERE EXISTS (
 SELECT 1 FROM TABLE2 T2 WHERE T1.ID= T2.ID
);

For example: this query should return tuples of Table 1 only where the IDs from both table match. But if EXISTS returns only 1 true (because the subquery is not empty - there's at least one row) then shouldn't it be equivalent to:

SELECT * FROM TABLE1 T1 WHERE TRUE;

Shouldn't it return all the rows in Table 1? If EXISTS returns a boolean every time a row is not empty then it would make much more sense to me. Thank you.

CodePudding user response:

You might be misinterpreting the logic of your first query. In plain English, your exists query says to return every record from TABLE1 for which we can find a record in TABLE2 having the same ID. Note that the query inside the exists clause is logically evaluated for every record in TABLE1. It does not just execute once.

  • Related