- What is WHERE ā filtering data in MySQL
- Comparison operators ā =, >, <, >=, <=, !=
- Logical operators ā AND, OR, NOT
- LIKE operator ā pattern matching with wildcards
- IN operator ā matching multiple values
- BETWEEN operator ā range filtering
What is the WHERE Clause?
The WHERE clause is one of the most important parts of SQL. It lets you filter your data and get only the rows you want.
š” Key concept: WHERE is like a sieve that lets some data through and stops other data. It helps you ask specific questions to your database.
Think of it like searching through a large list. If you want to find all students older than 20, you would look through the list and pick only those who meet that condition. The WHERE clause does this automatically for you!
Why WHERE is Important
# ============================================================ # WHY WE NEED WHERE # ============================================================ # Without WHERE, you get ALL rows SELECT * FROM students; # Returns 1000 students (including the ones you don't need) # With WHERE, you get ONLY the rows you want SELECT * FROM students WHERE age > 20; # Returns only students older than 20 # ============================================================ # COMMON USE CASES # ============================================================ # 1. Finding a specific record SELECT * FROM students WHERE student_id = 5; # 2. Filtering by a condition SELECT * FROM students WHERE age >= 18; # 3. Finding data within a range SELECT * FROM students WHERE age BETWEEN 18 AND 25; # 4. Pattern matching SELECT * FROM students WHERE email LIKE '%@gmail.com'; # 5. Multiple conditions SELECT * FROM students WHERE age > 20 AND first_name LIKE 'A%';
Key point: WHERE helps you find exactly what you're looking for without having to search through all the data yourself.
Quick Check: What does the WHERE clause do? (Answer: It filters rows based on a condition)
WHERE Clause Syntax
Basic WHERE Syntax
# ============================================================
# BASIC SYNTAX
# ============================================================
SELECT column1, column2
FROM table_name
WHERE condition;
# ============================================================
# REAL EXAMPLES
# ============================================================
# 1. Simple condition
SELECT * FROM students WHERE age = 22;
# 2. Using comparison operators
SELECT * FROM students WHERE age > 20;
SELECT * FROM students WHERE age >= 21;
SELECT * FROM students WHERE age < 25;
SELECT * FROM students WHERE age <= 24;
# 3. String comparison
SELECT * FROM students WHERE first_name = 'Rahul';
# 4. Using NOT
SELECT * FROM students WHERE age != 22;
SELECT * FROM students WHERE NOT age = 22;
# ============================================================
# IN PYTHON
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# Select students older than 20
cursor.execute("SELECT * FROM students WHERE age > 20")
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
connection.close()
WHERE clause structure:
- SELECT ā specifies what columns to return
- FROM ā specifies the table
- WHERE ā specifies the filter condition
- Condition ā a true/false expression
Quick Check: What is the correct order of clauses? (Answer: SELECT, FROM, WHERE)
Comparison Operators
Using Comparison Operators
# ============================================================
# COMPARISON OPERATORS
# ============================================================
# = equal to
# != not equal to
# > greater than
# < less than
# >= greater than or equal to
# <= less than or equal to
# ============================================================
# EXAMPLES
# ============================================================
# 1. Equal to
SELECT * FROM students WHERE age = 22;
# Returns students who are exactly 22
# 2. Not equal to
SELECT * FROM students WHERE age != 22;
# Returns students who are NOT 22
# 3. Greater than
SELECT * FROM students WHERE age > 22;
# Returns students older than 22
# 4. Less than
SELECT * FROM students WHERE age < 22;
# Returns students younger than 22
# 5. Greater than or equal to
SELECT * FROM students WHERE age >= 22;
# Returns students 22 or older
# 6. Less than or equal to
SELECT * FROM students WHERE age <= 22;
# Returns students 22 or younger
# ============================================================
# IN PYTHON
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# Different WHERE conditions
conditions = [
("age = 22", "age is exactly 22"),
("age > 22", "age is greater than 22"),
("age < 22", "age is less than 22"),
("age >= 22", "age is 22 or more"),
("age <= 22", "age is 22 or less"),
("age != 22", "age is not 22")
]
for condition, description in conditions:
query = f"SELECT COUNT(*) FROM students WHERE {condition}"
cursor.execute(query)
count = cursor.fetchone()[0]
print(f"{description}: {count} students")
cursor.close()
connection.close()
Comparison operators summary:
- = ā equals (exact match)
- != ā not equals
- > ā greater than
- < ā less than
- >= ā greater than or equal
- <= ā less than or equal
Quick Check: What operator is used for "not equal to"? (Answer: !=)
Logical Operators (AND, OR, NOT)
Combining Multiple Conditions
# ============================================================
# LOGICAL OPERATORS
# ============================================================
# AND - both conditions must be true
# OR - at least one condition must be true
# NOT - reverses the condition
# ============================================================
# AND OPERATOR
# ============================================================
# Students who are older than 20 AND younger than 25
SELECT * FROM students
WHERE age > 20 AND age < 25;
# Students named Rahul AND older than 20
SELECT * FROM students
WHERE first_name = 'Rahul' AND age > 20;
# ============================================================
# OR OPERATOR
# ============================================================
# Students who are 22 OR 25 years old
SELECT * FROM students
WHERE age = 22 OR age = 25;
# Students named Rahul OR Priya
SELECT * FROM students
WHERE first_name = 'Rahul' OR first_name = 'Priya';
# ============================================================
# NOT OPERATOR
# ============================================================
# Students who are NOT 22 years old
SELECT * FROM students
WHERE NOT age = 22;
# Students whose name is NOT Rahul
SELECT * FROM students
WHERE NOT first_name = 'Rahul';
# ============================================================
# COMBINING AND + OR
# ============================================================
# Students older than 20 AND (named Rahul OR Priya)
SELECT * FROM students
WHERE age > 20 AND (first_name = 'Rahul' OR first_name = 'Priya');
# ============================================================
# IN PYTHON
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# AND condition
cursor.execute("SELECT * FROM students WHERE age > 20 AND age < 25")
results = cursor.fetchall()
print(f"Students between 21 and 24: {len(results)}")
# OR condition
cursor.execute("SELECT * FROM students WHERE age = 22 OR age = 25")
results = cursor.fetchall()
print(f"Students aged 22 or 25: {len(results)}")
# NOT condition
cursor.execute("SELECT * FROM students WHERE NOT age = 22")
results = cursor.fetchall()
print(f"Students not aged 22: {len(results)}")
cursor.close()
connection.close()
Logical operators summary:
- AND ā both conditions must be true
- OR ā at least one condition must be true
- NOT ā reverses the condition
- Use parentheses to group conditions
Quick Check: What does AND do in a WHERE clause? (Answer: Both conditions must be true)
LIKE Operator for Pattern Matching
Finding Patterns in Text
# ============================================================
# LIKE OPERATOR
# ============================================================
# % - matches any number of characters
# _ - matches exactly one character
# ============================================================
# EXAMPLES WITH %
# ============================================================
# Names starting with 'R'
SELECT * FROM students WHERE first_name LIKE 'R%';
# Returns: Rahul, Ravi, etc.
# Names ending with 'a'
SELECT * FROM students WHERE first_name LIKE '%a';
# Returns: Priya, Sneha, etc.
# Names containing 'a' anywhere
SELECT * FROM students WHERE first_name LIKE '%a%';
# Returns: Rahul, Priya, Sneha, etc.
# Emails ending with '@gmail.com'
SELECT * FROM students WHERE email LIKE '%@gmail.com';
# Emails starting with 'r'
SELECT * FROM students WHERE email LIKE 'r%';
# ============================================================
# EXAMPLES WITH _
# ============================================================
# Names with exactly 5 characters
SELECT * FROM students WHERE first_name LIKE '_____';
# Names starting with 'R' and exactly 5 characters
SELECT * FROM students WHERE first_name LIKE 'R____';
# ============================================================
# IN PYTHON - Using LIKE with Parameterized Queries
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# Search for names starting with 'R'
search_term = "R%"
cursor.execute("SELECT * FROM students WHERE first_name LIKE %s", (search_term,))
results = cursor.fetchall()
print(f"Names starting with 'R': {len(results)}")
# Search for Gmail users
cursor.execute("SELECT * FROM students WHERE email LIKE %s", ("%@gmail.com",))
results = cursor.fetchall()
print(f"Gmail users: {len(results)}")
cursor.close()
connection.close()
LIKE pattern wildcards:
- % ā matches any number of characters
- _ ā matches exactly one character
- Use LIKE for partial text searches
- Use parameterized queries with LIKE
Quick Check: What does % mean in a LIKE pattern? (Answer: Any number of characters)
IN Operator
Matching Multiple Values
# ============================================================
# IN OPERATOR
# ============================================================
# IN checks if a value matches any value in a list
# ============================================================
# BASIC IN EXAMPLE
# ============================================================
# Students aged 22, 25, or 27
SELECT * FROM students
WHERE age IN (22, 25, 27);
# Same as using OR but cleaner:
# WHERE age = 22 OR age = 25 OR age = 27
# ============================================================
# IN WITH TEXT
# ============================================================
# Students named Rahul, Priya, or Amit
SELECT * FROM students
WHERE first_name IN ('Rahul', 'Priya', 'Amit');
# ============================================================
# NOT IN
# ============================================================
# Students NOT aged 22, 25, or 27
SELECT * FROM students
WHERE age NOT IN (22, 25, 27);
# ============================================================
# IN WITH SUBQUERY (Advanced)
# ============================================================
# Students who have placed orders
SELECT * FROM students
WHERE student_id IN (SELECT DISTINCT student_id FROM orders);
# ============================================================
# IN PYTHON
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# Using IN with a list of ages
ages = (22, 25, 27)
placeholders = ', '.join(['%s'] * len(ages))
query = f"SELECT * FROM students WHERE age IN ({placeholders})"
cursor.execute(query, ages)
results = cursor.fetchall()
print(f"Students aged 22, 25, or 27: {len(results)}")
# Using IN with names
names = ('Rahul', 'Priya', 'Amit')
placeholders = ', '.join(['%s'] * len(names))
query = f"SELECT * FROM students WHERE first_name IN ({placeholders})"
cursor.execute(query, names)
results = cursor.fetchall()
print(f"Students named Rahul, Priya, or Amit: {len(results)}")
cursor.close()
connection.close()
IN operator features:
- IN ā matches any value in a list
- NOT IN ā excludes values in a list
- Much cleaner than multiple OR conditions
- Works with subqueries as well
Quick Check: What does IN do? (Answer: Checks if a value matches any value in a list)
BETWEEN Operator
Checking for Values Within a Range
# ============================================================
# BETWEEN OPERATOR
# ============================================================
# BETWEEN checks if a value is within a range (inclusive)
# ============================================================
# BASIC BETWEEN EXAMPLES
# ============================================================
# Students aged between 20 and 25 (including 20 and 25)
SELECT * FROM students
WHERE age BETWEEN 20 AND 25;
# Same as:
# WHERE age >= 20 AND age <= 25
# ============================================================
# BETWEEN WITH DATES
# ============================================================
# Students who joined between two dates
SELECT * FROM students
WHERE joined_date BETWEEN '2024-01-01' AND '2024-12-31';
# ============================================================
# NOT BETWEEN
# ============================================================
# Students NOT aged between 20 and 25
SELECT * FROM students
WHERE age NOT BETWEEN 20 AND 25;
# ============================================================
# BETWEEN IN PYTHON
# ============================================================
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="secret",
database="myapp_db"
)
cursor = connection.cursor()
# Students aged 20-25
cursor.execute("SELECT * FROM students WHERE age BETWEEN %s AND %s", (20, 25))
results = cursor.fetchall()
print(f"Students aged 20-25: {len(results)}")
# Students aged 25-30
cursor.execute("SELECT * FROM students WHERE age BETWEEN %s AND %s", (25, 30))
results = cursor.fetchall()
print(f"Students aged 25-30: {len(results)}")
cursor.close()
connection.close()
BETWEEN operator features:
- BETWEEN ā checks if a value is in a range
- NOT BETWEEN ā checks if a value is outside a range
- Includes the start and end values
- Works with numbers, dates, and text
Quick Check: Does BETWEEN include the start and end values? (Answer: Yes, it's inclusive)
Real-World Example: Advanced Search
Building an Advanced Search System
# ============================================================
# ADVANCED SEARCH SYSTEM
# ============================================================
import mysql.connector
class AdvancedSearch:
"""Advanced search with multiple filters"""
def __init__(self, db_config):
self.db_config = db_config
self.connection = None
self.cursor = None
def connect(self):
try:
self.connection = mysql.connector.connect(**self.db_config)
self.cursor = self.connection.cursor()
return True
except mysql.connector.Error as e:
print(f"Connection failed: {e}")
return False
def search_students(self, first_name=None, last_name=None, min_age=None,
max_age=None, email_domain=None, exact_name=False):
"""
Search students with multiple filters
"""
conditions = []
params = []
# Build conditions dynamically
if first_name:
if exact_name:
conditions.append("first_name = %s")
params.append(first_name)
else:
conditions.append("first_name LIKE %s")
params.append(f"%{first_name}%")
if last_name:
conditions.append("last_name LIKE %s")
params.append(f"%{last_name}%")
if min_age is not None:
conditions.append("age >= %s")
params.append(min_age)
if max_age is not None:
conditions.append("age <= %s")
params.append(max_age)
if email_domain:
conditions.append("email LIKE %s")
params.append(f"%@{email_domain}")
# Build query
query = "SELECT * FROM students"
if conditions:
query += " WHERE " + " AND ".join(conditions)
# Execute query
self.cursor.execute(query, params)
return self.cursor.fetchall()
def display_results(self, results, title="Search Results"):
"""Display results"""
if not results:
print(f"\n{title}: No results found")
return
print(f"\n{title}: {len(results)} students found")
print("-" * 60)
for row in results:
print(f"ID: {row[0]} | {row[1]} {row[2]} | Age: {row[3]} | {row[4]}")
def close(self):
if self.cursor:
self.cursor.close()
if self.connection:
self.connection.close()
# ============================================================
# DEMONSTRATION
# ============================================================
db_config = {
"host": "localhost",
"user": "root",
"password": "secret",
"database": "myapp_db"
}
search = AdvancedSearch(db_config)
if search.connect():
# 1. Search by name (partial match)
results = search.search_students(first_name="Ra")
search.display_results(results, "Search: first_name contains 'Ra'")
# 2. Search by age range
results = search.search_students(min_age=22, max_age=26)
search.display_results(results, "Search: age between 22 and 26")
# 3. Search by email domain
results = search.search_students(email_domain="gmail.com")
search.display_results(results, "Search: Gmail users")
# 4. Multiple filters
results = search.search_students(
first_name="R",
min_age=22,
max_age=30,
email_domain="email.com"
)
search.display_results(results, "Search: name starts with 'R', age 22-30, email domain 'email.com'")
# 5. Exact name match
results = search.search_students(first_name="Rahul", exact_name=True)
search.display_results(results, "Search: exact match for 'Rahul'")
search.close()
This example shows:
- Building dynamic WHERE clauses
- Using multiple filters together
- LIKE with pattern matching
- BETWEEN for age ranges
- Exact match vs partial match
- Parameterized queries for safety
Quick Check: What is the advantage of building WHERE clauses dynamically? (Answer: You can create flexible search filters based on user input)
Best Practices
Tips for Using WHERE Effectively
# ============================================================
# BEST PRACTICES FOR WHERE CLAUSE
# ============================================================
print("1. USE PARAMETERIZED QUERIES")
print(" - Always use %s placeholders")
print(" - Never use string concatenation for SQL")
print(" - Protects against SQL injection")
print("\n2. BE SPECIFIC WITH CONDITIONS")
print(" - Use the most restrictive conditions first")
print(" - This improves performance")
print(" - Example: age > 20 AND age < 25")
print("\n3. USE INDEXES FOR FILTERED COLUMNS")
print(" - Columns used in WHERE should be indexed")
print(" - This speeds up queries significantly")
print("\n4. AVOID USING FUNCTIONS ON INDEXED COLUMNS")
print(" - WHERE YEAR(date_column) = 2024 is slower")
print(" - Use WHERE date_column BETWEEN '2024-01-01' AND '2024-12-31'")
print("\n5. USE LIKE CAREFULLY")
print(" - 'name%' is faster than '%name%'")
print(" - Leading % makes the query slower")
print(" - Consider full-text search for complex text searches")
print("\n6. USE NOT OPERATORS WISELY")
print(" - NOT IN and NOT LIKE can be slow")
print(" - Consider alternative approaches for large datasets")
Summary of best practices:
- Parameterized queries ā always for security
- Specific conditions ā better performance
- Indexes ā speed up WHERE clauses
- Avoid functions on indexed columns ā slows queries
- Use LIKE wisely ā avoid leading % when possible
Quick Check: Why should you use parameterized queries? (Answer: To prevent SQL injection attacks)
Try It Yourself
Experiment with WHERE clauses in the editor below.
WHERE CLAUSE - PRACTICE
========================================
1. COMPARISON OPERATORS
----------------------------------------
Age = 23: 2 students
-------------------------------------------------------
ID: 4 | Sneha Reddy | Age: 23 | sneha@email.com
ID: 8 | Meera Iyer | Age: 23 | meera@email.com
Age > 24: 3 students
-------------------------------------------------------
ID: 2 | Priya Patel | Age: 25 | priya@email.com
ID: 5 | Vikram Kumar | Age: 26 | vikram@email.com
ID: 7 | Ravi Desai | Age: 27 | ravi@email.com
Age < 24: 3 students
-------------------------------------------------------
ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com
ID: 4 | Sneha Reddy | Age: 23 | sneha@email.com
ID: 8 | Meera Iyer | Age: 23 | meera@email.com
2. LOGICAL OPERATORS
----------------------------------------
Age 22-25 (AND): 4 students
-------------------------------------------------------
ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com
ID: 2 | Priya Patel | Age: 25 | priya@email.com
ID: 3 | Amit Singh | Age: 24 | amit@email.com
ID: 4 | Sneha Reddy | Age: 23 | sneha@email.com
Age 22 or 25 (OR): 2 students
-------------------------------------------------------
ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com
ID: 2 | Priya Patel | Age: 25 | priya@email.com
3. LIKE PATTERN MATCHING
----------------------------------------
Name starts with 'R': 3 students
-------------------------------------------------------
ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com
ID: 7 | Ravi Desai | Age: 27 | ravi@email.com
ID: 5 | Vikram Kumar | Age: 26 | vikram@email.com
Name contains 'a': 4 students
-------------------------------------------------------
ID: 1 | Rahul Sharma | Age: 22 | rahul@email.com
ID: 2 | Priya Patel | Age: 25 | priya@email.com
ID: 6 | Anjali Nair | Age: 21 | anjali@email.com
ID: 7 | Ravi Desai | Age: 27 | ravi@email.com
Email ends with 'email.com': 8 students
-------------------------------------------------------
4. MULTIPLE CONDITIONS
----------------------------------------
Name starts with 'R' AND age > 24: 2 students
-------------------------------------------------------
ID: 5 | Vikram Kumar | Age: 26 | vikram@email.com
ID: 7 | Ravi Desai | Age: 27 | ravi@email.com
ā WHERE clauses make data filtering powerful!
You've Got It!
You now understand how to use the WHERE clause in MySQL with Python. You know comparison operators, logical operators, LIKE, IN, and BETWEEN.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between WHERE and HAVING?
Can I use multiple conditions with WHERE?
What is the difference between LIKE and IN?
What is a common interview question about WHERE?
How can I speed up WHERE queries?
Where to Go From Here
Now that you know how to filter data with WHERE, check out these related topics:
Select Data
Learn how to retrieve data from MySQL.
Learn More āUpdate Data
Learn how to modify existing data.
Learn More āDelete Data
Learn how to remove data safely.
Learn More ā