Python MySQL Tutorial – Using the WHERE Clause to Filter Data

Last updated 5 months, 1 week ago | 175 views 75     5

Tags:- MySQL Python

The WHERE clause in SQL allows you to filter rows returned by a query based on specific conditions. In this tutorial, you'll learn how to use the WHERE clause in MySQL queries through Python using the mysql-connector-python package.


Table of Contents

  1. What is the WHERE Clause?

  2. Prerequisites

  3. Install MySQL Connector

  4. Connect to MySQL with Python

  5. Use WHERE Clause with a Single Condition

  6. Use Multiple Conditions (AND, OR)

  7. Use Wildcards (LIKE)

  8. Use Placeholders to Prevent SQL Injection

  9. Full Working Example

  10. Tips and Common Pitfalls


✅ 1. What is the WHERE Clause?

The WHERE clause is used in SQL to filter records that meet a certain condition.

Example (SQL):

SELECT * FROM users WHERE age > 25;

⚙️ 2. Prerequisites

You need the following:

  • Python installed

  • MySQL Server with a database and table

  • The mysql-connector-python library installed


3. Install MySQL Connector

Use pip to install the MySQL connector:

pip install mysql-connector-python

4. Connect to MySQL with Python

import mysql.connector

db = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password",
    database="mydatabase"
)

cursor = db.cursor()

Replace with your actual credentials.


5. Use WHERE Clause with a Single Condition

sql = "SELECT * FROM users WHERE age > %s"
val = (25,)

cursor.execute(sql, val)
results = cursor.fetchall()

for row in results:
    print(row)

Explanation:

  • %s is a placeholder that prevents SQL injection.

  • val is a tuple with values to substitute into the query.


6. Use Multiple Conditions (AND / OR)

AND Condition:

sql = "SELECT * FROM users WHERE age > %s AND city = %s"
val = (25, "New York")

OR Condition:

sql = "SELECT * FROM users WHERE age < %s OR city = %s"
val = (20, "Chicago")

7. Use Wildcards with LIKE

Use LIKE to perform pattern matching.

sql = "SELECT * FROM users WHERE name LIKE %s"
val = ("%J%",)  # Names containing 'J'

cursor.execute(sql, val)
results = cursor.fetchall()

for row in results:
    print(row)

8. Use Placeholders to Prevent SQL Injection

Always use %s placeholders and avoid string concatenation in SQL queries:

Don’t do this:

sql = "SELECT * FROM users WHERE name = '" + name + "'"

Do this:

sql = "SELECT * FROM users WHERE name = %s"
val = (name,)

9. Full Working Example

import mysql.connector
from mysql.connector import Error

def filter_users():
    try:
        db = mysql.connector.connect(
            host="localhost",
            user="root",
            password="your_password",
            database="mydatabase"
        )

        cursor = db.cursor()

        # Filter users older than 25 in New York
        sql = "SELECT id, name, email FROM users WHERE age > %s AND city = %s"
        val = (25, "New York")

        cursor.execute(sql, val)
        results = cursor.fetchall()

        for row in results:
            print(row)

    except Error as e:
        print("Error:", e)

    finally:
        if db.is_connected():
            db.close()
            print("Connection closed.")

filter_users()

⚠️ 10. Common Pitfalls and Tips

Pitfall Solution
SQL injection vulnerability Always use %s placeholders
Wrong number of parameters Ensure the number of %s matches values
Forgetting comma in single-value tuple Use a comma: ("New York",)
Empty results Make sure the data actually matches the condition

✅ Tips:

  • Use fetchone() for a single result, fetchall() for multiple.

  • Debug by printing the query and values.

  • Use LIKE '%value%' for substring searches.


Summary Table

Task Query Example
Filter by age "WHERE age > %s"
Multiple conditions "WHERE age > %s AND city = %s"
Pattern match "WHERE name LIKE %s"
Safe query Use parameterized queries (%s)

Final Thoughts

Using the WHERE clause in MySQL with Python helps you query and filter records effectively. By writing safe, parameterized queries, you protect your application from SQL injection and ensure reliable database operations.