devmtl devmtl - 6 months ago 20
SQL Question

SQL EXISTS vs. Aggregate IS NOT NULL

I have two different forms of SQL condition clauses.

Using EXISTS:

exists (select 1 from [table] where [conditions])


Using Aggregate function:

(select max(1) from [table] where [conditions]) is not null


[table] and [conditions] are equal in both statements.
Is there a possibility these two clauses will return different results?
If not, which one has better query performance?
If it matters, the database in question is IBM DB2 UDB v10.

Answer

I don't have DB2 to test this on. But I think it depends. The following statement:

select max(1)
from (select 1 as i)t
where i = 2

Produces different results on SQL Server (null) and MySQL (1). If DB2 returns 1, then the statements are different. I would expect it to return null, though.

If it returns null, then the two statements are the same in effect. However, the max() statement is likely to perform less well than the exists. The exists statement can stop at the first matching value.

Comments