SQL Operators
Arithmetic, comparison, and logical operators
SQL provides various operators for calculations, comparisons, and combining conditions.
Arithmetic Operators
| Operator | Description | Example |
|---|---|---|
| + | Addition | price + tax |
| - | Subtraction | total - discount |
| * | Multiplication | price * quantity |
| / | Division | total / count |
| % | Modulo (remainder) | id % 2 |
-- Calculate order totals
SELECT
product_name,
price,
quantity,
price * quantity AS subtotal,
price * quantity * 0.1 AS tax,
price * quantity * 1.1 AS total
FROM order_items;
-- Find even/odd IDs
SELECT * FROM users WHERE id % 2 = 0; -- Even IDsComparison Operators
| Operator | Meaning | Example |
|---|---|---|
| = | Equal to | status = 'active' |
| != or <> | Not equal to | role != 'admin' |
| < | Less than | age < 18 |
| > | Greater than | price > 100 |
| <= | Less than or equal | quantity <= 0 |
| >= | Greater than or equal | rating >= 4 |
Logical Operators
-- AND: Both conditions must be true SELECT * FROM products WHERE price > 50 AND category = 'Electronics'; -- OR: Either condition can be true SELECT * FROM users WHERE role = 'admin' OR role = 'moderator'; -- NOT: Negates a condition SELECT * FROM orders WHERE NOT status = 'cancelled'; -- Combining with parentheses (IMPORTANT!) SELECT * FROM products WHERE category = 'Electronics' AND (price < 100 OR on_sale = TRUE);
Tip: AND has higher precedence than OR. Use parentheses to make your intent clear!