smartyfy.mrindigi.com

Databases & SQL Master Course — 011. Boolean Logic with AND OR and NOT

Lesson 011 Boolean Logic with AND OR and NOT

A shop assistant wants books that are affordable and available, with a special exception for travel guides. Each part sounds simple, but the placement of one parenthesis can change who qualifies. This lesson turns such requests into explicit conditions and checks them against awkward records rather than trusting the first plausible result.

Prerequisites and objectives

Complete lesson 10 first. You should already be comfortable with SELECT, WHERE, ORDER BY, NULL, aliases, and the four-book practice catalog. No Python knowledge is needed. Combine comparisons with AND, OR, and NOT; explain which conditions belong together; and predict what missing stock does to a filter.

Build a fresh practice database

Run this setup once in a new, empty SQLite scratch database and keep the connection open. Start another empty database to reset. Never use important data. These records are fictional; prices are integer cents and stock counts copies.

The original books remain unchanged. A separate stock_samples table adds a missing stock count, a zero count, an expensive available item, and a cheaper available item. These are diagnostic samples, not additional catalog books.

PRAGMA foreign_keys = ON;
CREATE TABLE authors (
  author_id INTEGER PRIMARY KEY,
  author_name TEXT NOT NULL
);
CREATE TABLE books (
  book_id INTEGER PRIMARY KEY,
  title TEXT NOT NULL,
  author_id INTEGER NOT NULL REFERENCES authors(author_id),
  genre TEXT NOT NULL,
  price_cents INTEGER NOT NULL,
  stock INTEGER NOT NULL
);
INSERT INTO authors (author_id, author_name) VALUES
  (1, 'Mira Chen'), (2, 'Omar Silva'), (3, 'Nia Patel');
INSERT INTO books
  (book_id, title, author_id, genre, price_cents, stock) VALUES
  (101, 'River Maps', 1, 'Travel', 1800, 4),
  (102, 'SQL Trail', 2, 'Technology', 2500, 8),
  (103, 'Garden Notes', 3, 'Nature', 1200, 0),
  (104, 'Night Signals', 1, 'Fiction', 1800, 5);

CREATE TABLE stock_samples (
  sample_id INTEGER PRIMARY KEY,
  price_cents INTEGER,
  stock INTEGER
);
INSERT INTO stock_samples (sample_id, price_cents, stock) VALUES
  (201, 1800, NULL), (202, 900, 0),
  (203, 2500, 2), (204, 1200, 2);

1. Translate the rule before typing

A predicate is an expression used to test a row. The comparison price_cents <= 1800 asks one question. The comparison stock > 0 asks another. AND requires both answers to be true. OR requires at least one true answer, so a book satisfying both still appears once. Neither operator combines or duplicates records; both decide whether an existing row survives.

Write the business rule as a sentence with brackets: “[Travel or Fiction] and [available].” Then replace each phrase with a complete comparison. Repeat the column name on each side of OR. Writing genre = 'Travel' OR 'Fiction' leaves the second operand as text rather than a comparison, which does not express the intended choice.

2. Make grouping visible

SQLite evaluates AND more tightly than OR. Therefore A OR B AND C means A OR (B AND C). If availability applies to either genre, write (A OR B) AND C instead. Formatting the conditions on separate lines helps people read them, but whitespace does not change their meaning. Parentheses do.

SELECT 1 OR 0 AND 0 AS ungrouped,
       (1 OR 0) AND 0 AS grouped;

Expected output:

ungrouped | grouped
1 | 0

The literal probe removes catalog details so you can focus on grouping. In the first column, the AND result is false but the left OR operand is true. In the second, the parenthesized result is true and the final AND operand is false. SQLite displays these comparison results as one and zero.

For Garden Notes, Nature is true, Fiction is false and stock greater than zero is false. Without parentheses A OR B AND C evaluates1 OR(0 AND0)=1 and includes the unavailable book. With(A OR B) AND C it evaluates(1 OR0) AND0=0 and excludes it.
AND binds more tightly than OR. Group the alternative genres before applying a shared availability requirement; otherwise Nature remains an independent route into the result. Open full-size diagram

3. Treat unknown as a real possibility

A missing stock count is not evidence of availability or unavailability. Comparing it with zero produces NULL. A WHERE clause retains true results and discards both false and unknown results. NOT reverses true and false, but NOT applied to unknown remains unknown. Consequently, excluding available items does not automatically include records whose availability is missing.

Two useful checkpoints prevent overgeneralizing: false AND unknown is false, because one failed requirement already decides the result; true OR unknown is true, because one successful alternative already decides it. When unknown needs special treatment, state that policy using IS NULL. Do not assume every logical expression containing NULL must produce NULL.

Four worked exercises

Exercise 1: Require two facts

Find original catalog books costing at most 1800 cents with at least one copy. Predict the excluded low-price book before running the query.

Worked answer and explanation
SELECT book_id, title FROM books
WHERE price_cents <= 1800 AND stock > 0
ORDER BY book_id;

Expected output:

book_id | title
101 | River Maps
104 | Night Signals

First compare each price with the inclusive ceiling. Then check stock for the survivors. Garden Notes meets the price requirement but has zero copies, so AND rejects it. SQL Trail has stock but fails the price condition. Two independent requirements leave exactly two books.

Exercise 2: Apply a shared requirement

Choose Nature or Fiction books, but require stock for both genres. Explain why the parentheses matter even though the condition looks short.

Worked answer and explanation
SELECT book_id, title FROM books
WHERE (genre = 'Nature' OR genre = 'Fiction')
  AND stock > 0
ORDER BY book_id;

Expected output:

book_id | title
104 | Night Signals

The grouped choice first admits Garden Notes and Night Signals conceptually, then availability removes Garden Notes. Without parentheses, the Nature condition stands outside the stock requirement because AND binds more tightly. That faulty version would include the unavailable Nature book, a concrete counterexample to the request.

Exercise 3: Negate a complete condition

Return samples that are neither expensive nor unavailable. Here expensive means over 1800 cents and unavailable means exactly zero stock. Do not include unknown stock.

Worked answer and explanation
SELECT sample_id FROM stock_samples
WHERE NOT (price_cents > 1800 OR stock = 0)
ORDER BY sample_id;

Expected output:

sample_id
204

The condition inside NOT identifies either disqualifying fact. Sample 203 is expensive and sample 202 is unavailable. Sample 201 has an acceptable price but unknown stock: the inner result remains unknown, and negation does not change that. Only sample 204 has two known acceptable facts.

Exercise 4: State a missing-data policy

Prepare a review queue for stock that is zero or not yet counted. These two reasons have different meanings even though they share a queue.

Worked answer and explanation
SELECT sample_id, stock FROM stock_samples
WHERE stock = 0 OR stock IS NULL
ORDER BY sample_id;

Expected output:

sample_id | stock
201 | NULL
202 | 0

Use one comparison for a confirmed zero and IS NULL for a missing observation. Sample 201 qualifies through the second branch; sample 202 qualifies through the first. Keeping the stock column in the output makes the distinction visible to the reviewer instead of disguising unknown values as zeros.

Common pitfalls and a checking routine

Do not use the order of WHERE conditions as a promise about execution order. Describe the required result, and avoid relying on a left condition to make an unsafe right expression harmless. Also distinguish NOT (A OR B) from NOT A OR B: the second leaves B as an independent route into the result.

For each new rule, choose one row that passes everything, one that fails only the first condition, one that fails only the second, and one with a missing value. List their expected IDs before executing. If no existing row exposes a grouping mistake, add a fictional diagnostic sample rather than declaring two conditions equivalent from one convenient dataset.

Knowledge check

Question 1

How is A OR B AND C grouped without parentheses?

  1. (A OR B) AND C
  2. A OR (B AND C)
  3. (A AND B) OR C
  4. All three operators run left to right
Answer and explanation

B. AND has higher precedence than OR. Explicit parentheses should still show the intended business grouping.

Question 2

What happens to a row when its WHERE expression is NULL?

  1. It is included once
  2. It is included twice
  3. It is excluded
  4. SQLite raises a missing-value error
Answer and explanation

C. WHERE keeps true expressions. Unknown does not satisfy that requirement, but it is not an execution error.

Question 3

What is NOT NULL in a Boolean expression?

  1. One
  2. Zero
  3. An empty string
  4. NULL
Answer and explanation

D. Negation cannot turn an unknown proposition into a known truth or falsehood. Use IS NULL to test missingness.

Question 4

A row satisfies both sides of an OR. How many times does that alone return it?

  1. Once
  2. Twice
  3. Zero times
  4. The result depends on the column order
Answer and explanation

A. OR is a predicate on that input row. It does not create another row for a second successful branch.

Question 5

Which condition includes both confirmed zero stock and missing stock?

  1. stock = 0 AND stock IS NULL
  2. stock = 0 OR stock IS NULL
  3. NOT stock > 0
  4. stock = NULL OR stock = 0
Answer and explanation

B. The two explicit alternatives cover both categories. Equality with NULL does not test missingness, and negating a comparison still leaves missing stock unknown.

Summary

Translate each requirement into a complete comparison, group shared requirements explicitly, and decide what missing values should mean. Validate the rule with counterexamples, especially rows that qualify through one OR branch while failing a shared condition. A correct filter reflects the intended policy rather than merely producing plausible-looking rows.

SQLite behavior and primary references

Verified with SQLite 3.53.1. Run the SQL in a SQLite tool; the verification script is for course maintenance. Other database engines can differ in Boolean displays, comparison rules, and text matching. This lesson uses ordinary SQLite features, with any important portability limits explained above.