Practice: SQL Queries Using Python
Q1. Count the IT staff
Using the staff table from the chapter (Asha IT, Bela HR, Chen IT, Dev Sales, Esha HR), print how many people work in IT. Use a placeholder.
Goal: Filter rows with a parameter.
Q2. Highest salary name
Print the name of the best paid person.
Goal: Use ORDER BY and LIMIT.
Q3. Average salary per department
Print each department and its average salary, sorted by department name, as tuples one per line.
Goal: Group and aggregate.
Q4. Names containing a letter
Print the sorted list of names that end with the letter 'a', using LIKE.
Goal: Search text with LIKE.
Q5. Salary range with BETWEEN
Print the names (sorted) of staff whose salary is between 42000 and 50000 inclusive, using two placeholders.
Goal: Combine placeholders with BETWEEN.
Q6. Departments with more than one person
Print the departments that have more than one person, sorted, as a list.
Goal: Use HAVING.
Q7. What does fetchone print?
Predict the output.
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 FROM staff ORDER BY id')
print(cur.fetchone())
print(cur.fetchone())
Goal: Read rows with fetchone.
Q8. Cursor is used up
Predict the output.
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 FROM staff WHERE dept = "HR" ORDER BY id')
print(len(cur.fetchall()))
print(len(cur.fetchall()))
Goal: Know that cursors are consumed.
Q9. Sorted two ways
Predict the output.
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 ORDER BY salary').fetchall()[0])
print(conn.execute('SELECT name FROM staff ORDER BY salary DESC').fetchall()[0])
Goal: Use ORDER BY with DESC.
Q10. Sum and max
Predict the output.
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 SUM(salary), MAX(salary) FROM staff WHERE dept <> ?', ('IT',)).fetchone())
Goal: Use aggregates with conditions.
Q11. Left join result
Predict the output.
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')")
rows = conn.execute('SELECT s.name, d.boss FROM staff s LEFT JOIN dept d ON s.dept = d.code WHERE s.id IN (1, 2) ORDER BY s.id').fetchall()
print(rows)
Goal: Understand LEFT JOIN.
Q12. Row factory output
Predict the output.
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
r = conn.execute('SELECT name, dept FROM staff WHERE id = 3').fetchone()
print(r['dept'], r[0])
Goal: Read rows by name.
Q13. Fix the injection risk
The code builds the query with an f-string, which is unsafe. Rewrite it with a placeholder so it still prints the matching names.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (name TEXT)')
conn.executemany('INSERT INTO t VALUES (?)', [('Ann',), ("O'Neil",)])
name = "O'Neil"
print(conn.execute(f"SELECT name FROM t WHERE name = '{name}'").fetchall())
Goal: Avoid SQL injection.
Q14. Fix the one-item tuple
This code raises an error because of the parameter. Fix it.
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (name TEXT)')
conn.execute('INSERT INTO t VALUES (?)', ('Ann',))
print(conn.execute('SELECT name FROM t WHERE name = ?', ('Ann')).fetchall())
Goal: Write one-item tuples.
Q15. Fix WHERE with COUNT
This query fails because WHERE cannot use an aggregate. Fix it to print departments with at least 2 people.
SELECT dept FROM staff WHERE COUNT(*) >= 2 GROUP BY deptGoal: Use HAVING correctly.
Q16. WHERE versus HAVING
In your own words, explain when you use WHERE and when you use HAVING.
Goal: Separate WHERE from HAVING.
Q17. Why placeholders
Give two reasons to use ? placeholders instead of string formatting in SQL.
Goal: Explain safe queries.
Q18. Search function
Write a function search(conn, text) that returns the names (sorted) of staff whose name contains text, then print search(conn, 'sh'). Use a parameter and LIKE.
Goal: Build a safe search.