Python SQL Interview Questions with Checked SQLite Examples
Python SQL interviews connect query semantics with driver behaviour. Practise passing values as parameters, interpreting joins and aggregates, choosing transaction boundaries and closing resources. The example below uses an in-memory SQLite database to show a quoted name, a course with no matching bookings and a rolled-back duplicate insert. It creates no database file or server connection.
Topic: Python for AI & Automation in AI & Data · Interview preparation
Quick answer: Python SQL interviews connect query semantics with driver behaviour. Practise passing values as parameters, interpreting joins and aggregates, choosing transaction boundaries and closing resources. The example below uses an in-memory SQLite database to show a quoted name, a course with no matching bookings and a rolled-back duplicate insert. It creates no database file or server connection. Explain which behaviour belongs to Python's sqlite3 module and which belongs to the database, then check the chosen driver before applying the answer to another system.
Key takeaways
- Pass data values through the driver’s parameter interface.
- Explain whether a filter belongs in a join condition or after it.
- Choose transaction behaviour explicitly and verify the resulting state.
- Distinguish result fetching from a guarantee of unbuffered execution.
- Use a query plan and workload evidence before recommending an index.
Table of Contents
- What does Python’s database API standardise?
- How should values be passed into a query?
- What do the checked SQLite results establish?
- Why can a LEFT JOIN lose unmatched rows?
- Which transaction assumptions should you state aloud?
- What should you check about foreign keys and NULL?
- How do raw SQL, an ORM and analysis tools differ?
- References
What does Python’s database API standardise?
Question: what is the difference between a connection and a cursor? Answer cue: a connection provides the database session and transaction interface, while a cursor executes statements and exposes results. PEP 249 defines common interfaces, exceptions and parameter styles; it does not make every database's SQL or transaction behaviour identical.
Question: what do fetchone, fetchmany and fetchall return? Answer cue: the next row or no-row marker, a batch, and remaining rows respectively. Iterating can avoid creating one large application list, but driver buffering and server behaviour still matter. State the actual driver, result size and retrieval approach instead of claiming that a cursor guarantees constant-memory streaming.
How should values be passed into a query?
Question: a course name contains an apostrophe. Should you manually escape it? Answer cue: pass it as a value using the driver's documented parameters. The OWASP SQL injection prevention guide distinguishes parameterised values from query structure. The fixture uses a normal invented name, not an attack against an application.
Question: can a parameter select a table or column name? Answer cue: value binding does not substitute arbitrary SQL identifiers. If the application offers sorting choices, map supported choices to fixed developer-defined query fragments and reject unsupported choices. Placeholder syntax also varies by driver. A question-mark example from sqlite3 should not be pasted unchanged into an interface that documents a different parameter style.
What do the checked SQLite results establish?
The Python sqlite3 reference documents the connection context manager and explicit autocommit control. Run this standalone example with Python 3.12 or later and its sqlite3 module. It commits the invented baseline, then deliberately triggers a duplicate primary key inside a separate transaction.
import sqlite3
db = sqlite3.connect(":memory:", autocommit=False)
try:
db.execute("CREATE TABLE course(id INTEGER PRIMARY KEY, name TEXT)")
db.execute("CREATE TABLE booking(course_id INTEGER, status TEXT)")
db.executemany("INSERT INTO course VALUES (?, ?)",
[(1, "O'Reilly"), (2, "Basics"), (3, "No bookings")])
db.executemany("INSERT INTO booking VALUES (?, ?)",
[(1, "approved"), (1, "pending"), (2, "approved")])
db.commit()
print("Bound value:", db.execute(
"SELECT name FROM course WHERE name = ?", ("O'Reilly",)
).fetchone()[0])
rows = db.execute(
"SELECT c.name, COUNT(b.course_id) "
"FROM course AS c LEFT JOIN booking AS b "
"ON b.course_id = c.id AND b.status = ? "
"GROUP BY c.id, c.name ORDER BY c.id", ("approved",)
).fetchall()
print("Approved bookings:", rows)
try:
with db:
db.execute("INSERT INTO course VALUES (?, ?)", (4, "Draft"))
db.execute("INSERT INTO course VALUES (?, ?)", (4, "Duplicate"))
except sqlite3.IntegrityError:
print("Duplicate rejected; transaction rolled back")
print("Course 4 rows:", db.execute(
"SELECT COUNT(*) FROM course WHERE id = ?", (4,)
).fetchone()[0])
finally:
db.close()Expected output:
Bound value: O'Reilly
Approved bookings: [("O'Reilly", 1), ('Basics', 1), ('No bookings', 0)]
Duplicate rejected; transaction rolled back
Course 4 rows: 0The zero count shows that the first insertion of course 4 was rolled back with the failing second insertion. The finally block closes the connection; the connection's transaction context alone does not close it. This exercise does not test crash durability, concurrent clients or another database engine.
Why can a LEFT JOIN lose unmatched rows?
Question: why does the example put the approved-status condition in ON? Answer cue: it limits matching bookings while preserving each course. A later WHERE condition requiring the right-hand status would discard the null-extended unmatched result. The SQLite SELECT documentation explains this distinction in query processing.
Question: why count the matching booking field instead of COUNT(*)? Answer cue: the unmatched course still contributes a result row, while its right-side fields are NULL. The intended question is how many bookings matched. Specify the question before choosing the aggregate. Also define what a second-highest value means: distinct values and the second row under a tie-breaking order answer different questions.
| Course condition | Matching approved bookings | Expected count |
|---|---|---|
| One approved and one pending | Only the approved row | 1 |
| One approved booking | That matching row | 1 |
| No bookings | Null-extended course row | 0 when counting the matching field |
Which transaction assumptions should you state aloud?
Question: does every sqlite3 data change automatically open the same transaction arrangement? Answer cue: behaviour depends on the configured mode. The fixture explicitly sets autocommit=False rather than relying on a changing or legacy default. Its baseline commit separates setup from the later rollback demonstration.
Question: does a successful commit prove every business rule was checked? Answer cue: distinguish application rules, declared database constraints and the selected isolation and durability configuration. A transaction is useful for an agreed atomic operation, but it cannot invent an omitted rule. Keep production transactions appropriately bounded, and verify the result after handling an exception. Do not catch an error inside a transaction block and then assume the block necessarily rolled back.
What should you check about foreign keys and NULL?
Question: does writing a foreign-key declaration alone establish enforcement in every SQLite connection? Answer cue: inspect and configure the applicable connection correctly. The SQLite foreign_keys documentation warns against relying on its default and says changing enforcement within a transaction is ineffective. The teaching schema deliberately does not claim a foreign-key constraint.
Question: does equality to NULL identify missing values? Answer cue: use the database's documented null predicates and three-valued logic. An unknown value differs from an empty string or zero. In the booking exercise, absence of a matching row is a join result, not evidence that the course has an empty name. Explain those meanings before converting missing values for display.
How do raw SQL, an ORM and analysis tools differ?
Question: does an ORM eliminate the need to understand queries? Answer cue: no. You still need the generated access pattern, transaction and result semantics. The SQLAlchemy 2.0 relationship-loading guide explains lazy and eager strategies, including the N+1 pattern of additional relationship queries.
Choose a strategy for the actual relationship and workload. A join can duplicate parent columns or change result processing, while another loading strategy can issue additional bounded queries. Do not promise that one option is always faster. For analytical work, a DataFrame may be a useful destination, but transferring an unbounded result has its own cost. This article executes sqlite3 only and makes no SQLAlchemy, pandas or server-database runtime claim.
| Interview question | Evidence a useful answer requests |
|---|---|
| Why is the query slow? | Actual plan, row counts, filters and workload |
| Should an index be added? | Supported access pattern and write cost |
| Does the ORM issue N+1 queries? | Observed statements and relationship loading |
| Is the result correct? | Expected rows, NULL handling, ties and ordering |
Related reading: Flask and Django interview questions; Python data-structure choices.
References
Frequently Asked Questions
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Wow
0
Sad
0
Angry
0