SQL WHERE Clause

The WHERE clause in SQL is used to filter records that meet specific conditions. Instead of retrieving all the rows from a table, you can apply conditions to fetch only the data you need.

📌 Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

📊 Example Table: users

id | name    | age | city
---+---------+-----+---------
1  | Alice   | 22  | New York
2  | Bob     | 30  | London
3  | Charlie | 18  | Sydney
4  | Diana   | 27  | Toronto
5  | Ethan   | 35  | Paris

🔍 Example 1: Filter by Numeric Value

SELECT name, age FROM users WHERE age > 20;

🔍 Example 2: Filter by Text

Find all users from London:

SELECT * FROM users WHERE city = 'London';

🔍 Example 3: Using Comparison Operators

  • = : Equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to
  • <> or != : Not equal to

🔍 Example 4: Using AND & OR

-- Find users older than 20 AND from New York
SELECT * FROM users WHERE age > 20 AND city = 'New York';

-- Find users from London OR Paris
SELECT * FROM users WHERE city = 'London' OR city = 'Paris';

🔍 Example 5: Pattern Matching with LIKE

Find users whose names start with 'A':

SELECT * FROM users WHERE name LIKE 'A%';

🔍 Example 6: Using IN and BETWEEN

-- Users from specific cities
SELECT * FROM users WHERE city IN ('London', 'Paris');

-- Users aged between 20 and 30
SELECT * FROM users WHERE age BETWEEN 20 AND 30;

⚡ Best Practices

  • Always use quotes for string values ('London').
  • Use AND/OR carefully to avoid logic errors.
  • Indexes on columns used in WHERE improve performance.
  • Test your conditions with sample queries before applying to production.

📝 Summary

The WHERE clause makes SQL powerful by filtering rows based on conditions. You can use operators, combine conditions withAND / OR, match patterns withLIKE, and simplify multiple checks with IN andBETWEEN.

🚀 Next Steps

In the next lesson, we will cover the SQL INSERT Statement, which lets you add new rows into your database.