In this lesson, you will learn how to combine multiple criteria in a single SQL query to precisely filter the data you retrieve from your database.
The Power of Boolean Logic
When you want to pull information, a single condition (like "find customers from New York") is rarely enough. Real-world questions often require nuance, such as "find customers from New York who have spent over $500."
To build these specific filters, we use Boolean logic operators: AND, OR, and NOT. These act like the "glue" that connects your conditions:
AND: Requires both conditions to be true. Use this to make your results more exclusive.OR: Requires at least one condition to be true. Use this to widen your results.NOT: Excludes records that match the condition. Use this to filter out unwanted data.
Practical Illustration
Imagine you are querying a Products table. You want to find items that are either "Electronics" OR cost more than $1,000. If you also want to make sure the item is currently in stock, you can combine them:
SELECT *
FROM Products
WHERE (Category = 'Electronics' OR Price > 1000)
AND StockQuantity > 0;
Why Parentheses Matter
Just like in math, the order of operations matters. SQL processes AND before OR. By wrapping (Category = 'Electronics' OR Price > 1000) in parentheses, we force the database to evaluate those two conditions together as a single unit before checking if the item is in stock (AND StockQuantity > 0). Without the parentheses, the database might return an expensive item that is out of stock because it would prioritize the AND logic first.
By mastering these operators, you stop acting like a "filter" that catches everything, and start acting like a "sieve" that captures only the specific data points your application requires.
Key Takeaway: Use AND, OR, and NOT with strategic parentheses to create precise, complex filters that isolate the exact records you need from your database.