Published by Patrick Mutisya · 14 days ago
By the end of this lesson you will be able to perform searches in a database using a variety of operators, including AND, OR, NOT, LIKE, >, <, =, >= and <=.
Operators let you define the criteria that records must meet to be retrieved. Using the right combination of operators makes your queries precise and efficient.
| Operator | Purpose | Example (SQL WHERE clause) |
|---|---|---|
| AND | Both conditions must be true | WHERE price > 20 AND stock > 0 |
| OR | Either condition can be true | WHERE category = 'Books' OR category = 'Magazines' |
| NOT | Exclude records that meet a condition | WHERE NOT status = 'Discontinued' |
| LIKE | Pattern matching with wildcards (%) and (_) | WHERE name LIKE 'A%' |
| > | Greater than | WHERE quantity > 50 |
| < | Less than | WHERE quantity < 10 |
| = | Equal to | WHERE country = 'UK' |
| >= | Greater than or equal to | WHERE score >= 80 |
| <= | Less than or equal to | WHERE score <= 50 |
When mixing AND and OR, use parentheses to control the order of evaluation.
Example: Find products that are either in the “Electronics” category and cost less than $100, or are in the “Books” category.
WHERE (category = 'Electronics' AND price < 100) OR category = 'Books'
Example: Retrieve all customers who are not from Canada.
WHERE NOT country = 'Canada'
Wildcards:
Examples:
WHERE name LIKE 'J%'WHERE phone LIKE '%1234'WHERE postcode LIKE '_##'Use >, <, =, >=, <= to compare numeric fields such as price, quantity, scores, dates, etc.
Example: Students who scored between 70 and 90 (inclusive).
WHERE score >= 70 AND score <= 90
quantity = 0) or discontinued (status = 'Discontinued').Write the SQL WHERE clause for each of the following requirements.
role != 'Manager').% (any length) and _ (single character).>, <, =, >=, <= and can be chained with AND for ranges.