Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: WHERE Clause in MySQL

Python MySQL WHERE Clause - Complete Guide

Learn how to filter data using the WHERE clause in MySQL with Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is the WHERE Clause?
  • WHERE Clause Syntax
  • Comparison Operators
  • Logical Operators (AND, OR, NOT)
  • LIKE Operator for Pattern Matching
  • IN Operator
  • BETWEEN Operator
  • Real-World Example
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • 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!

1

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

2

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

3

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)

4

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

5

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

6

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

7

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

8

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

9

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. What does the WHERE clause do in SQL?
2. Which operator is used for "not equal to" in SQL?
3. What does LIKE '%@gmail.com' find?
4. What does the IN operator do?
5. What does BETWEEN 20 AND 25 include?

Frequently Asked Questions

What is the difference between WHERE and HAVING? ā–¼

WHERE filters rows before grouping. HAVING filters groups after grouping (used with GROUP BY). WHERE is for individual rows, HAVING is for groups.

Can I use multiple conditions with WHERE? ā–¼

Yes, you can combine multiple conditions using AND, OR, and NOT. Use parentheses to group conditions and control the order of evaluation.

What is the difference between LIKE and IN? ā–¼

LIKE is used for pattern matching with wildcards (% and _). IN checks if a value matches any value in a list. Use LIKE for text patterns and IN for matching against specific values.

What is a common interview question about WHERE? ā–¼

Common questions include: "Explain the difference between WHERE and HAVING," "How do you use LIKE with wildcards?" and "Write a query to find all users with Gmail accounts."

How can I speed up WHERE queries? ā–¼

To speed up WHERE queries: create indexes on columns used in WHERE, avoid functions on indexed columns, use specific conditions instead of general ones, and avoid leading % in LIKE patterns when possible.

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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: Select Data Next: Update Data →