SQL logical operator efficiency

41 Views Asked by At

I know doing an explain plan on the 2 queries below will yield the same cost, but will the database evaluate both parts of an OR condition or will it stop after the first part that evaluates to true?

select 1 from dual where
exists (select 1 from small_table where col1 = 10)
or
exists (select 1 from big_table where col1 = 10);

Swap the 2 exists conditions:

select 1 from dual where
exists (select 1 from big_table where col1 = 10)
or
exists (select 1 from small_table where col1 = 10);

An example of why this would matter:

Say one of the subqueries uses a table with millions of records (big_table) and the other part uses a table with only a couple hundred records (small_table). I know that the record I'm searching for is more likely to be in small_table, but could sometimes be in big_table. In this case, I would want to order the OR condition with the small_table first. If this were java...

String a = "small";
if (a == "small" || a == "big") {
    // a == "big" won't get executed
}
0

There are 0 best solutions below