Are conditional subqueries optimized if the condition is false?

I have a foo table and a table where each foo can have a panel (and a panel can belong to several foos).

Now I need to select all foos with a string. My sql is as follows

SELECT * 
  FROM foo f 
 WHERE [...] 
   AND ($param IS NULL OR (SELECT ((COUNT(*))>0) 
                             FROM bar b 
                            WHERE f.bar = b.id))

with the replacement of $ param at runtime.

The question arises: will the subquery be executed even if param is zero, or does dbms optimize the subquery?

We use mysql, mssql and oracle. Is there any difference between the two in relation to the above?

+3
source share
2 answers

. , , . , , . , $param, , , .

Exists Count (*)

Select ..
From foo f
Where ....
    And ( $param Is Null
            Or Exists   (
                        Select 1
                        From bar b
                        Where b.id = f.bar
                        ))
+2

, , , , .

$param , foo. , .

:

if ($param is null)
  SELECT * 
  FROM foo f 
  WHERE [...] 
else
  SELECT distinct f.* 
  FROM foo f 
  inner join bar b on f.bar = b.id
  WHERE [...] 
end if
+1

Source: https://habr.com/ru/post/1746402/


All Articles