Intermediate Chapter 159 · 30 min read · Module 12: Python Database and APIs
SQL Queries Using Python
- After this chapter you can run a SELECT query and read rows with fetchone, fetchmany and fetchall.
- You can filter data with WHERE and pass values safely using ? placeholders.
- You can sort, limit and search results with ORDER BY, LIMIT and LIKE.
- You can summarise data with aggregate functions, GROUP BY and HAVING.
- You can join two tables and read rows by column name.
Storing data is only useful if you can ask questions about it. SQL is the language for those questions, and Python is the program that sends them. In this chapter you will use the sqlite3 module to run queries and turn the answers into normal Python values.
You will begin with simple SELECT statements and the three fetch methods. Then you will add conditions, sorting and searching. After that you will summarise data with GROUP BY and combine two tables with JOIN.
One idea runs through the whole chapter: values must travel as parameters, not be glued into the SQL text. This one habit protects your program from a whole family of attacks and from many confusing bugs.
Running a query from Python
SQL is the language you use to ask a database for data. Python does not replace SQL. Instead, Python sends your SQL text to the database through a connection, and the database sends rows back. With the built-in sqlite3 module you call conn.execute(sql) and get a cursor. The cursor is the object that holds the result of the query and lets you read the rows one by one or all together.
Reading rows is done with three methods. fetchone() returns the next row, or None when there are no more. fetchall() returns a list of all remaining rows. fetchmany(n) returns a list of at most n rows. A cursor is also iterable, so for row in cursor: works and uses little memory because rows come one at a time. Each row is a tuple by default, in the same order as the columns you wrote after SELECT.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER)')
conn.executemany('INSERT INTO staff (name, dept, salary) VALUES (?, ?, ?)', [
('Asha', 'IT', 50000), ('Bela', 'HR', 40000), ('Chen', 'IT', 60000),
('Dev', 'Sales', 45000), ('Esha', 'HR', 42000)])
cur = conn.execute('SELECT name, salary FROM staff ORDER BY salary DESC')
print(cur.fetchone())
print(cur.fetchall())
print(cur.fetchone())
Filtering with WHERE and placeholders
Most queries need a condition. The WHERE clause keeps only the rows that match, for example WHERE dept = 'IT'. When the value comes from a variable, never build the SQL text with f-strings or +. That style can break when the value has a quote in it, and it opens the door to SQL injection, where a user types SQL code as data. Use a placeholder ? in the query and pass the values as a tuple in the second argument. The driver then treats them as plain data.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER)')
conn.executemany('INSERT INTO staff (name, dept, salary) VALUES (?, ?, ?)', [
('Asha', 'IT', 50000), ('Bela', 'HR', 40000), ('Chen', 'IT', 60000),
('Dev', 'Sales', 45000), ('Esha', 'HR', 42000)])
dept = 'IT'
min_salary = 55000
cur = conn.execute('SELECT name FROM staff WHERE dept = ? AND salary >= ?', (dept, min_salary))
print(cur.fetchall())
bad = "x' OR '1'='1"
cur = conn.execute('SELECT name FROM staff WHERE dept = ?', (bad,))
print(cur.fetchall())
(dept,). Without the comma, Python sees only brackets around a string, and sqlite3 will treat each letter as a separate value.Sorting, limiting and searching
ORDER BY column sorts the result, and DESC reverses the order. LIMIT n returns only the first n rows, which is handy for a top-three list. The LIKE operator searches text patterns: % matches any number of characters and _ matches exactly one. Together these give you leaderboards, search boxes and paged lists with very little code. Always add a second sort column, such as the id, if two rows can tie, so the order stays the same every time you run the query.
Summaries with aggregates and GROUP BY
Aggregate functions turn many rows into one value: COUNT, SUM, AVG, MIN and MAX. With GROUP BY you get one result row for each group, such as one row per department. If you want to filter on the aggregate itself, use HAVING, because WHERE runs before the groups are made. Aggregates return a single row when there is no GROUP BY, so fetchone()[0] is a common way to read them.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER)')
conn.executemany('INSERT INTO staff (name, dept, salary) VALUES (?, ?, ?)', [
('Asha', 'IT', 50000), ('Bela', 'HR', 40000), ('Chen', 'IT', 60000),
('Dev', 'Sales', 45000), ('Esha', 'HR', 42000)])
print(conn.execute("SELECT name FROM staff WHERE name LIKE '%e%' ORDER BY name").fetchall())
print(conn.execute('SELECT name FROM staff ORDER BY salary DESC, id LIMIT 2').fetchall())
for row in conn.execute('SELECT dept, COUNT(*), AVG(salary) FROM staff GROUP BY dept HAVING COUNT(*) > 1 ORDER BY dept'):
print(row)
Joining two tables
Real data is split across tables. A JOIN connects them by a shared column, usually a foreign key. An INNER JOIN keeps only rows that have a match on both sides, while a LEFT JOIN keeps every row from the left table and fills the missing right side with None. Use short table aliases such as s and d to keep the SQL readable.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER)')
conn.executemany('INSERT INTO staff (name, dept, salary) VALUES (?, ?, ?)', [
('Asha', 'IT', 50000), ('Bela', 'HR', 40000), ('Chen', 'IT', 60000),
('Dev', 'Sales', 45000), ('Esha', 'HR', 42000)])
conn.execute('CREATE TABLE dept (code TEXT, boss TEXT)')
conn.execute("INSERT INTO dept VALUES ('IT', 'Mira'), ('HR', 'Omar')")
q = 'SELECT s.name, d.boss FROM staff s {} dept d ON s.dept = d.code ORDER BY s.id'
print(conn.execute(q.format('INNER JOIN')).fetchall())
print(conn.execute(q.format('LEFT JOIN')).fetchall())
Rows as dictionaries
Reading row[2] is easy to get wrong when you add a column later. Set conn.row_factory = sqlite3.Row and each row can be read by column name, like row['salary']. You can also read cur.description to see column names. Choose names with AS in the SQL for computed columns, for example AVG(salary) AS average.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, dept TEXT, salary INTEGER)')
conn.executemany('INSERT INTO staff (name, dept, salary) VALUES (?, ?, ?)', [
('Asha', 'IT', 50000), ('Bela', 'HR', 40000), ('Chen', 'IT', 60000),
('Dev', 'Sales', 45000), ('Esha', 'HR', 42000)])
conn.row_factory = sqlite3.Row
row = conn.execute('SELECT name, salary * 12 AS yearly FROM staff WHERE id = 1').fetchone()
print(row['name'], row['yearly'])
print(row.keys())
Writing queries that stay safe and clear
Keep SQL keywords in capital letters and put long queries in triple quotes so they are easy to read. Placeholders only work for values, not for table or column names. If a column name must change, choose it from a fixed list of names that you wrote yourself, never from user input. Select only the columns you need instead of *, because it makes the code clearer and keeps working when the table gains columns. Finally, close the connection when you are done, or use it inside a with block for transactions, as you saw in earlier chapters.
Python syntax
cur = conn.execute('SELECT col1, col2 FROM table WHERE col = ? ORDER BY col1 LIMIT 5', (value,))
rows = cur.fetchall()SELECT group_col, COUNT(*) FROM table GROUP BY group_col HAVING COUNT(*) > 1SELECT a.x, b.y FROM a INNER JOIN b ON a.key = b.keyReal-world applications
- Search boxes on websites that filter products by name or price.
- Reports that count sales per month or per region.
- Leaderboards in games using ORDER BY and LIMIT.
- Loading data for analysis from a local database.
- Login checks that look up a user by name using a safe parameter.
Common mistakes
Fix: Use a placeholder: execute('... WHERE name = ?', (name,)). This prevents SQL injection and quote errors.
Fix: A one-item tuple needs a trailing comma. Without it sqlite3 may raise a binding error.
Fix: A cursor is consumed as you read it. Store the list in a variable or run the query again.
Fix: Use HAVING for conditions on aggregates, after GROUP BY.
Fix: Placeholders are for values only. Pick names from a fixed list that you control.
Important tips
- Select only the columns you need instead of *.
- Add a tie-breaking column to ORDER BY so the order is stable.
- Use sqlite3.Row to read columns by name.
- Print the SQL while debugging, but never print real passwords.
Key points summary
- conn.execute returns a cursor that you read with fetchone, fetchmany or fetchall.
- Use ? placeholders and a tuple of values.
- WHERE filters rows, GROUP BY makes groups, HAVING filters groups.
- JOIN combines tables on a shared column; LEFT JOIN keeps unmatched left rows.
- Rows are tuples unless you set a row factory.
Exam and interview points
- Placeholders prevent SQL injection.
- The order of clauses is SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
- fetchone returns None when the rows run out.
- INNER JOIN drops unmatched rows; LEFT JOIN keeps left rows.
Quick revision
- execute -> cursor -> fetch.
- Use ? and a tuple.
- HAVING filters groups.
- LEFT JOIN fills missing with None.
- Row factory gives column names.
Frequently asked questions
What is the difference between fetchone and fetchall?
fetchone returns a single row (or None), while fetchall returns a list of all remaining rows. Use fetchall for small results and iterate the cursor for large ones.
Why do I get an empty list and not an error when nothing matches?
A query with no matching rows is valid. The result is simply empty, so check with if not rows before using it.
Can I use ? for the table name?
No. Placeholders only replace values. Table and column names must be written in the SQL text, taken from a trusted list.
What does LIKE '%a%' do?
It matches any text that contains the letter a anywhere. The percent sign stands for any number of characters.
Is SQL case sensitive?
Keywords are not, so select and SELECT are the same. Text comparison with = in SQLite is case sensitive by default, while LIKE ignores case for plain English letters.
Practise this chapter
18 practice questions Take the chapter quiz