Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Most likely this post is because of too much spare time :) But if you're interested in SQL you may find this compelling. I find this issue amusing (and a bit confusing if you don't know about pre-defined conditions or condition cost).

If you think about the evaluation order of conditions combined with OR in SQL. What is the correct evaluation order for this statement, does it fail?
SQL
SELECT 1
WHERE 1/0=42 OR 1=1

Feel free to change the order and test the results (in your favorite DBMS).

What about this one (written for Sql Server):
SQL
SELECT 1
WHERE 1/(SELECT COUNT(*) FROM sysobjects WHERE type = 'NotPossible')=2 OR 2<5

The behavior will be a bit different among different databases.
Posted
Comments
Sergey Alexandrovich Kryukov 8-Apr-11 16:12pm    
How come you can ever get too much spare time? I want it, too :-)
--SA
Wendelius 8-Apr-11 16:18pm    
You can lease it, if we can agree on the payment :)
Sergey Alexandrovich Kryukov 8-Apr-11 19:48pm    
Thank you, your offer is being considered... :-)
--SA
DaveAuld 8-Apr-11 16:52pm    
Are both results = 1 ?
Wendelius 8-Apr-11 17:19pm    
Well to be exact the other one is dívision by zero, but if you run it against for example SQL Server it's not going to fail, no matter in which order you put the conditions... The funny part is that they always produce a result. Thinking about programming languages like C# it doesn't make sense :)

1 solution

I just ran it on Oracle 9.2.0.5 and it always returns 1. :)
SQL> select 1 from dual where 1/0=42 or 1=1;
         1
----------
         1
SQL> edit
Wrote file afiedt.buf
  1  select 1 from dual
  2*  where 1=1 or 1/0=42
  3  ;
         1
----------
         1
SQL> edit
Wrote file afiedt.buf
  1  select 1 from dual
  2*  where 1=1 or 1/(select count(*) from all_tables where table_name = 'NOTHING')=42
  3  ;
         1
----------
         1
SQL> edit
Wrote file afiedt.buf
  1  select 1 from dual
  2*  where 1/(select count(*) from all_tables where table_name = 'NOTHING')=42 or 1=1
  3  ;
         1
----------
         1
SQL> 

I hope this doesn't mean that Oracle is exceptional or rather exceptionless. :)
 
Share this answer
 
Comments
Wendelius 12-Apr-11 12:23pm    
Exactly as it should have gone :) Oracle makes no exception from what I've seen.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900