Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2010

    Unanswered: Correct way of using conditions in a SQL statement?

    Dear friends, I've a sql like below:

    SELECT   <list of cols>
      FROM <table>
     WHERE col1 = value1
       AND col2 = value2
       AND (   (col3 != value3 AND (col4 = value41 OR col4 = value42)) ---> condition 1
            OR (col5 NOT IN (<a list of text values>) ---> condition 2
            OR (col6 != 'Y') ---> condition 3
    ORDER BY col7;
    Now I want the sql to NOT return any rows if any of the conditions 1, 2, or 3 are being met. I.e. if the result has any rows satisfied by condition 1, it should not be part of the result set, and similarly for condition 2, and condition 3.

    What is happening right now is that condition 1 is satisfied, then it stops the sql and I get some rows in the result set which are NOT being satisfied by condition 2, i.e. some rows with values specified in condition 2 are still returned.

    What is the best way to rewrite this SQL?
    Hope I was able to make myself clear here/

  2. #2
    Join Date
    Mar 2007
    Looks like a simple negation of the given condition. Did you try to put a simple NOT operator before that whole condition
    WHERE col1 = value1
       AND col2 = value2
       AND NOT ( <all those conditions> )
    If you do not like this construction, just follow De Morgan's law for simplifying them. It is described in this link:
    For example,
    NOT (<condition1> OR <condition2>)
    is equivalent to
    (<NOT condition1> AND <NOT condition2>)
    [Edit: position of NOT in the last code]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts