SQL Operators 🧮
Mentor's Note: Operators are the verbs of your query logic. They define how you want to filter, calculate, or compare your data. Without them, you can only fetch raw lists. 💡
🌟 The Scenario: The Online Store 🛒
Imagine you run an e-commerce site. You need to filter products.
- Arithmetic: "Calculate the price after a 10% discount." (
Price * 0.9) - Comparison: "Show products cheaper than ₹500." (
Price < 500) - Logical: "Show items that are Red AND Large." (
Color = 'Red' AND Size = 'L')
🎨 Visual Logic: Operator Types
💻 1. Arithmetic Operators (Math) ➕
Used to perform mathematical operations on numeric data.
| Operator | Description | Example | Result |
|---|---|---|---|
+ | Add | SELECT 10 + 5; | 15 |
- | Subtract | SELECT 10 - 5; | 5 |
* | Multiply | SELECT 10 * 5; | 50 |
/ | Divide | SELECT 10 / 5; | 2 |
% | Modulus (Remainder) | SELECT 10 % 3; | 1 |
-- Scenario: Calculate Annual Salary
SELECT salary * 12 AS annual_salary FROM employees;
💻 2. Comparison Operators (Testing) ⚖️
Used to compare two values. Returns TRUE or FALSE.
| Operator | Description | Example |
|---|---|---|
= | Equal to | WHERE salary = 50000 |
<> or != | Not equal to | WHERE dept <> 'HR' |
> | Greater than | WHERE age > 18 |
< | Less than | WHERE price < 100 |
>= | Greater than or equal | WHERE rating >= 4.5 |
<= | Less than or equal | WHERE stock <= 10 |
-- Scenario: Find High Value Products
SELECT * FROM products WHERE price > 1000;
💻 3. Logical Operators (Combiners) 🔗
Used to combine multiple conditions.
| Operator | Description | Logic |
|---|---|---|
| AND | TRUE if all conditions are TRUE | Red AND Large (Must be both) |
| OR | TRUE if any condition is TRUE | Red OR Blue (Can be either) |
| NOT | Reverses the result | NOT Red (Anything but Red) |
-- Scenario: Find specific shoes
SELECT * FROM shoes
WHERE (color = 'Black' OR color = 'Brown')
AND size = 10;
💡 Operator Precedence (BODMAS for SQL)
When combining operators, SQL follows a strict order:
- Parentheses
() - Multiplication/Division
* / - Addition/Subtraction
+ - - NOT
- AND
- OR
Rule of Thumb: Always use Parentheses
()when mixing AND/OR to ensure clarity!