Python SQLite: How to Use the WHERE Clause

Last updated 1 month ago | 99 views 75     5

Tags:- Python SQLite

The WHERE clause in SQL allows you to filter data so that your query returns only the rows that meet specific conditions. When combined with Python’s sqlite3 module, WHERE becomes a powerful tool to extract exactly the information you need.

In this article, you'll learn:

  • How to use WHERE in SQLite with Python

  • Various comparison and logical operators

  • How to prevent SQL injection with parameterized queries

  • Real-world examples and common pitfalls


✅ Prerequisites

  • Python 3.x installed

  • SQLite database and a table (e.g., Users) with sample data inserted

Example table:

CREATE TABLE Users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    age INTEGER
);

Step 1: Connect to the SQLite Database

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

Step 2: Use a Basic WHERE Clause

To select all users older than 30:

cursor.execute("SELECT * FROM Users WHERE age > 30")
rows = cursor.fetchall()

for row in rows:
    print(row)

Output (Example)

(3, 'Charlie', '[email protected]', 35)

⚙️ WHERE Clause: Syntax and Operators

Comparison Operators

Operator Meaning
= Equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
<> or != Not equal

Logical Operators

Operator Description
AND Both conditions
OR Either condition
NOT Negates a condition

Example: Multiple Conditions

cursor.execute("SELECT * FROM Users WHERE age > 25 AND name = 'Alice'")

Use Parameterized Queries (Avoid SQL Injection)

Do not use string concatenation:

# ❌ Dangerous
cursor.execute(f"SELECT * FROM Users WHERE name = '{name}'")

Use this instead:

# ✅ Safe
cursor.execute("SELECT * FROM Users WHERE name = ?", (name,))

Example: Using WHERE with Python

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

# Get users older than a certain age
min_age = 30
cursor.execute("SELECT name, age FROM Users WHERE age > ?", (min_age,))

results = cursor.fetchall()
for name, age in results:
    print(f"{name} is {age} years old")

conn.close()

More Examples

WHERE with Text Match

cursor.execute("SELECT * FROM Users WHERE name = ?", ("Alice",))

WHERE with NOT

cursor.execute("SELECT * FROM Users WHERE NOT age = 25")

WHERE with OR

cursor.execute("SELECT * FROM Users WHERE age < 25 OR age > 40")

WHERE with IN

cursor.execute("SELECT * FROM Users WHERE name IN (?, ?, ?)", ("Alice", "Bob", "Charlie"))

Tips for Using WHERE with SQLite in Python

Tip Why It’s Helpful
✅ Always use parameterized queries Prevents SQL injection
✅ Use fetchone() for expected single results More efficient
✅ Use proper data types in conditions Avoids type mismatch errors
✅ Test your SQL queries in an SQLite GUI or CLI first Speeds up debugging

⚠️ Common Pitfalls

Issue Cause Fix
Query returns nothing Wrong condition or data not matching Double-check data values and query logic
SQL injection vulnerability String formatting in queries Use ? with parameters
Type mismatch errors Comparing strings to integers Use correct types consistently

Best Practices

  • Keep WHERE conditions readable — use parentheses if needed

  • Separate logic in Python and SQL (don’t overload queries with too much logic)

  • Use functions or named queries for repeated filters

  • When filtering by date or range, make sure the format is consistent (e.g., YYYY-MM-DD)


Conclusion

The WHERE clause is a fundamental part of querying data in any SQL database, and Python’s sqlite3 module makes it safe and easy to use. With WHERE, you can extract just the data you need based on flexible conditions — making your applications faster and smarter.