MySQL Operators
MySQL Operators: Arithmetic, Comparison, and Logical Rules
MySQL operators are symbols and keywords that calculate values, compare columns, and combine conditions inside SQL expressions. Knowing operator precedence and NULL behavior prevents silent calculation bugs in queries and reports.
Core Operator Categories
| Category | Operators | Purpose |
|---|---|---|
| Arithmetic | +, -, *, /, DIV, % / MOD |
Math calculations (price * qty) |
| Comparison | =, != / <>, <=>, >, <, >=, <= |
Compare values (<=> is null-safe equal) |
| Logical | AND, OR, NOT, XOR |
Combine boolean conditions |
| Range & Set | BETWEEN, IN, LIKE, IS NULL |
Filter ranges, lists, and patterns |
Practical SQL Examples
This query calculates line totals, applies a tax rate, and uses NULLIF() to prevent division-by-zero surprises on demo_products:
SELECT
id,
product_name,
price,
stock_qty,
ROUND(price * stock_qty, 2) AS inventory_value,
ROUND(price / NULLIF(stock_qty, 0), 2) AS price_per_unit
FROM demo_products
WHERE price >= 20.00
AND (category = 'Electronics' OR category = 'Furniture');
| id | product_name | price | stock_qty | inventory_value | price_per_unit |
|---|---|---|---|---|---|
| 8 | Wireless Headphones | 89.99 | 15 | 1349.85 | 6.00 |
| 14 | Standing Desk | 299.50 | 4 | 1198.00 | 74.88 |
Common Mistakes and Best Practices
- Prevent Division by Zero: Dividing by zero returns
NULLin permissive SQL modes or throws an error underERROR_FOR_DIVISION_BY_ZEROin strict mode. Always wrap denominators withNULLIF(divisor, 0)so queries fail safely instead of crashing. - Know Integer Division (
DIV) vs. Float Division (/): Standard7 / 2yields3.5000, whereas7 DIV 2performs integer division and returns3. - Use the Null-Safe Equality Operator: Unlike
=, MySQL's null-safe equality operator returns1when both columns areNULLand0when only one column isNULL. - Parenthesize Mixed Logical Conditions: Always wrap
ORbranches inside parentheses when combining them withAND, becauseANDevaluates beforeOR.
Frequently Asked Questions
What is the difference between = and null-safe equality in MySQL?
Writing NULL = NULL evaluates to UNKNOWN (false in WHERE), whereas MySQL's null-safe equality operator evaluates NULL compared to NULL as 1 (true).
Does MySQL use && and || for AND and OR?
&& works as AND, but || acts as string concatenation if PIPES_AS_CONCAT is enabled; always write AND and OR explicitly for clarity.
Which runs first: multiplication * or addition +?
Arithmetic *, /, DIV, and % bind tighter than + and -, and AND always binds tighter than OR.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.