Logic Gates: AND vs. OR Explained
The Complexity Creep
By Thursday, the questions got harder. The Sales VP stopped by. *"I need a list of all products in the 'Electronics' category, BUT only if they are priced over $500. Oh, and if they're in the 'Home' category and out of stock, include those too."*
My mind started to twist. I couldn't just use one filter. I needed to combine logic.
The Quest: Building the Logic Bridge
To handle multiple requirements, SQL gives us two primary "Logic Gates":
The Implementation: The Double Filter
I started by solving the first half of his request: Electronics over $500.
-- Scenario 1: Strict requirement (both must be true)
SELECT *
FROM products
WHERE category = 'Electronics' AND price > 500;
Then, I tackled the "Or" scenario:
-- Scenario 2: Inclusive requirement (either can be true)
SELECT *
FROM products
WHERE category = 'Home' OR stock_count = 0;
The Power of Parentheses
When you combine AND and OR in the same query, things get dangerous. SQL processes AND before OR by default. To stay safe, always use parentheses to "Group" your logic:
-- The "CEO" Query
SELECT *
FROM products
WHERE (category = 'Electronics' AND price > 500)
OR (category = 'Home' AND stock_count = 0);
The "Oops" Moment
I once wrote a query without parentheses and accidentally included every single 'Home' product in our store, regardless of price, because I misplaced an `OR`. It made the sales forecast look like we were billionaires for about five minutes.
**Pro Tip**: When in doubt, wrap your conditions in `()`. It makes your intent clear to the computer and to other humans reading your code.
The Victory
The VP got his list. He could see the high-ticket electronics that needed special marketing and the home goods that were causing bottlenecks. Combining logic is how you start to see the "Big Picture" in your data.
Your Task for Today
Write a query with two conditions. First, use `AND` to find a very specific subset. Then, use `OR` to see how much wider the net becomes.
*Day 5: The Final Touch—Ordering Your Results.*