Skip to content

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.

  1. Arithmetic: "Calculate the price after a 10% discount." (Price * 0.9)
  2. Comparison: "Show products cheaper than ₹500." (Price < 500)
  3. Logical: "Show items that are Red AND Large." (Color = 'Red' AND Size = 'L')

🎨 Visual Logic: Operator Types

mindmap
  root((SQL Operators))
    Arithmetic
      + (Add)
      - (Subtract)
      * (Multiply)
      / (Divide)
      % (Modulus)
    Comparison
      = (Equal)
      <> (Not Equal)
      > (Greater)
      < (Less)
    Logical
      AND (Both True)
      OR (One True)
      NOT (Reverse)
    Special
      BETWEEN
      LIKE
      IN
      IS NULL

💻 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: 1. Parentheses () 2. Multiplication/Division * / 3. Addition/Subtraction + - 4. NOT 5. AND 6. OR

Rule of Thumb: Always use Parentheses () when mixing AND/OR to ensure clarity!


📈 Learning Path