Lesson

MySQL Operators

10 min reading
Free Course

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 NULL in permissive SQL modes or throws an error under ERROR_FOR_DIVISION_BY_ZERO in strict mode. Always wrap denominators with NULLIF(divisor, 0) so queries fail safely instead of crashing.
  • Know Integer Division (DIV) vs. Float Division (/): Standard 7 / 2 yields 3.5000, whereas 7 DIV 2 performs integer division and returns 3.
  • Use the Null-Safe Equality Operator: Unlike =, MySQL's null-safe equality operator returns 1 when both columns are NULL and 0 when only one column is NULL.
  • Parenthesize Mixed Logical Conditions: Always wrap OR branches inside parentheses when combining them with AND, because AND evaluates before OR.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum