Q
Problem solve Get help with specific problems with your technologies, process and projects.

Mixing ANDs and ORs

I am trying to write this query in ORACLE, but I cannot make it work. What am I doing wrong?

SELECT UsedInfoCodes.TERM_NO, 
UsedInfoCodes.INFO_CODE,
PLTFLOOR.INFORMATION_CODE.GAUGE, 
PLTFLOOR.INFORMATION_CODE.DESCR
FROM PLTFLOOR.ORDECONT, 
PLTFLOOR.INFORMATION_CODE, UsedInfoCodes
WHERE PLTFLOOR.INFORMATION_CODE.INFO_CODE
 = UsedInfoCodes.INFO_CODE
AND PLTFLOOR.ORDECONT.PART_NBR
 = UsedInfoCodes.PART_NBR
AND ((To_Number(PULL_GOAL)) > 0 )
AND ((To_Number(PULL_SCHED_COUNT))<>1)
AND ((To_Number(PULL_ORDER_COUNT))<>1)
OR (((TO_NUMBER (PULL_SCHED_COUNT)) = 1)
AND ((To_Number(PULL_ORDER_COUNT))=1)
AND ((To_Number(PULL_BO))>0))
ORDER BY UsedInfoCodes.TERM_NO;

Ah, those pesky parentheses again. Let's remove the redundant ones first --

SELECT UsedInfoCodes.TERM_NO
     , UsedInfoCodes.INFO_CODE
     , PLTFLOOR.INFORMATION_CODE.GAUGE
     , PLTFLOOR.INFORMATION_CODE.DESCR
  FROM PLTFLOOR.ORDECONT
     , PLTFLOOR.INFORMATION_CODE
     , UsedInfoCodes
 WHERE PLTFLOOR.INFORMATION_CODE.INFO_CODE 
     = UsedInfoCodes.INFO_CODE
   AND PLTFLOOR.ORDECONT.PART_NBR 
     = UsedInfoCodes.PART_NBR
   AND To_Number(PULL_GOAL) > 0 
   AND To_Number(PULL_SCHED_COUNT)<>1
   AND To_Number(PULL_ORDER_COUNT))<>1
    OR ( 
       TO_NUMBER(PULL_SCHED_COUNT) = 1
   AND To_Number(PULL_ORDER_COUNT)=1
   AND To_Number(PULL_BO)>0
       )
ORDER 
    BY UsedInfoCodes.TERM_NO;

In effect, you have --


 WHERE join conditions
   AND filter conditions
    OR ( 
       filter conditions
       )

When what you really need is --

 WHERE join conditions
   AND (
       filter conditions
    OR filter conditions
       )

Remember, ANDs take precedence over ORs. Conditions are not strung together, each attaching to the previous one, but rather, the ANDs are evaluated as though they had parentheses around them. Use parentheses when in doubt, to ensure that your join conditions prevail for all rows. But don't use unnecessary ones, they make it hard to read and debug the syntax.

For More Information


This was last published in September 2002

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close