Let's understand Mainframe
Home Tutorials Interview Q&A Quiz Mainframe Memes Contact us About us

Module 5: DB2 SQL SELECT and Filtering


AND OR NOT

One predicate is rarely enough. AND, OR and NOT combine predicates into richer search conditions - the everyday logic of real queries.

AND, OR and NOT in one line

  • AND - both predicates must be true. Narrows the result.
  • OR - at least one predicate must be true. Widens the result.
  • NOT - reverses a predicate: NOT (SALARY > 40000) means salary is 40000 or less.
  • You can chain as many as you need: A AND B OR C AND NOT D.

Evaluation order and parentheses

  • DB2 evaluates NOT first, then AND, then OR.
  • So A OR B AND C means A OR (B AND C) - not (A OR B) AND C.
  • Parentheses override the default order. Use them whenever OR and AND mix.
  • Reading the condition aloud helps: say 'and'/'or' exactly where they appear.

NOT and NULL need care

  • NOT (SALARY > 40000) is true for salaries of 40000 or below - but not for NULL salaries.
  • NOT flips true to false and false to true; unknown stays unknown.
  • If NULLs matter, add an explicit IS NULL or IS NOT NULL test.
  • Prefer positive conditions where possible - they are easier to read and to index.

Example

SELECT EMPNO, LASTNAME, WORKDEPT, JOB FROM EMP WHERE WORKDEPT = 'D11' AND (JOB = 'MANAGER' OR JOB = 'OPERATOR') AND NOT LASTNAME LIKE 'S%'; -- Result: D11 managers/operators whose name does not start with S EMPNO LASTNAME WORKDEPT JOB ------ -------- -------- -------- 000060 STERN D11 MANAGER





© copyright mainframebug.com
Privacy Policy
MainframeBug Assistant