Interview Questions: Working with Databases
Databases sit behind nearly every real application, and SQL injection specifically is one of the most consequential security questions in software engineering interviews. This set covers mysql-connector-python's connection/cursor model, parameterized queries and SQL injection, pymongo's document model and CRUD methods, relational vs. document tradeoffs, and cloud-hosted connections with environment-variable credentials.
1 What does a database driver library actually do, and why can't Python just use open() the way it does for files?
A database (MySQL, MongoDB, or otherwise) is separate software, usually running as its own server process, speaking its own specific network protocol — even when it happens to run on the same machine as the Python program. A driver library (mysql-connector-python, pymongo) is written specifically to speak that protocol: opening the network connection, sending commands in the format the server expects, and translating results back into ordinary Python values. open() works for files because a file is just bytes on the same machine's disk, reachable through the operating system directly — a database requires a whole separate negotiation over a network connection instead.
Describing a database as "just a bigger file" or not being able to explain why a network connection (even to "localhost") is fundamentally different from opening a local file.
Follow-up"If MySQL is running on the exact same machine as the Python program, is a network connection still involved?" (Yes — even "localhost" connections go through the same client-server protocol a remote connection would, just without leaving the machine; the driver still has to open a network connection, not a plain file handle.)
2 Walk through the objects involved in a basic MySQL query: connection, cursor, and results.
mysql.connector.connect(host=, user=, password=, database=) opens a connection to the server. connection.cursor() returns a cursor — the object every SQL command actually runs through. cursor.execute(sql, params) sends a command; for a SELECT, cursor.fetchall() then returns every matching row as a list, or cursor.fetchone() returns just the first one (or None). For a data-changing command (INSERT/UPDATE/DELETE), connection.commit() is what actually makes the change permanent.
Confusing the connection and the cursor (thinking commands run directly through the connection object), or forgetting that data-changing operations need an explicit commit().
"If a program calls cursor.execute() for an UPDATE but never calls connection.commit(), what happens?" (The change is not guaranteed to be saved permanently — MySQL requires an explicit commit for changes made inside a transaction to actually persist, which is exactly why forgetting commit() is a common real bug.)
3 What is SQL injection, and how does it actually work?
SQL injection is an attack where untrusted input (something a user typed) is glued directly into a SQL command as raw text, letting that input change what the query actually does, not just what data it searches for. Concretely: if a query is built as f"SELECT * FROM students WHERE name = '{name}'" and an attacker enters x' OR '1'='1 as name, the closing quote in their input ends the intended string early and appends OR '1'='1' — a condition that's always true — turning a lookup for one specific student into a query that matches every row in the table.
Describing SQL injection vaguely ("it's a hacking technique") without being able to walk through a concrete example of how a query's structure actually changes.
Follow-up"Why does the attacker's single quote matter so much in that example?" (Because the query was built with the value wrapped in quotes as part of the string itself — the attacker's own quote character closes that string early, and everything after it gets interpreted as new SQL syntax rather than as more of the search value.)
4 What is a parameterized query, and why does it prevent SQL injection completely, rather than just making it harder?
A parameterized query writes %s as a placeholder inside the SQL string wherever a value belongs, then passes the actual values separately as a tuple to cursor.execute(sql, params). The driver substitutes each %s in a way that always treats the value strictly as data — never as SQL syntax — no matter what characters (quotes, semicolons, SQL keywords) that value contains. This is a structural guarantee, not a filter: there's no "sanitizing" step being bypassed, because the substituted value never touches the part of the process that parses SQL syntax in the first place.
Describing parameterized queries as "checking input for bad characters" (that's a fundamentally different, weaker approach) rather than as structurally separating code from data.
Follow-up"Could a sufficiently clever attacker still break out of a parameterized query the way they broke out of the f-string version?" (No — that's precisely the guarantee: the substituted value is never parsed as part of the SQL command's structure at all, so there's no "clever enough" input that changes the query's meaning; it's a structural fix, not a best-effort filter.)
5 Why isn't "checking user input for quote characters" considered an adequate defense against SQL injection?
Because it's a blocklist approach trying to anticipate every way an attacker might break out of a string, and attackers have far more techniques than a single quote character — different quoting styles, encoding tricks, and database-specific syntax quirks can all bypass a naive character check. Parameterized queries sidestep the entire category of attack structurally, by never letting a substituted value touch the SQL command's syntax at all, which is why they're the standard fix rather than any form of input scanning or escaping done by hand.
Red flagsSuggesting "just escape the quotes" or "strip dangerous characters" as a sufficient fix, rather than reaching for parameterized queries.
Follow-up"If a team is using an ORM (object-relational mapper) instead of raw SQL, are they automatically safe from SQL injection?" (Mostly, for standard query-building methods the ORM provides, since those typically generate parameterized queries under the hood — but many ORMs still allow dropping into raw SQL for complex queries, and that raw-SQL escape hatch reintroduces exactly the same injection risk if it's built with string formatting instead of parameters.)
6 What is a MongoDB document, and how is it different from a SQL row?
A MongoDB document is a flexible, self-contained record, similar to a JSON object — in Python, it's just a plain dict, with no separate translation step needed. Unlike a SQL row, a document isn't bound to a fixed set of columns shared by every other document in its collection: one document might have a field another document entirely lacks, and a field can hold a nested list or nested document directly, without needing a separate related table the way SQL would.
Red flagsDescribing a MongoDB document as "just a row with a different name" without acknowledging the flexible-schema difference, or not knowing that a document maps directly to a Python dict.
Follow-up"Can two documents in the same MongoDB collection have completely different sets of fields?" (Yes — that's the core structural difference from a SQL table; MongoDB doesn't require every document in a collection to share the same shape by default.)
7 Walk through the four CRUD operations in pymongo.
Create: collection.insert_one(document) adds a new document (a plain dict). Read: collection.find(query) returns every document matching a query dict; find_one(query) returns just the first match, or None. Update: collection.update_one(query, {"$set": {...}}) changes specific fields on the first matching document, leaving everything else untouched. Delete: collection.delete_one(query) removes the first matching document. A query is itself just a dict, like {"name": "Ana Torres"}, meaning "match documents where that field equals that value."
Forgetting the "$set" wrapper on updates (a common mistake that silently no-ops against a real MongoDB server, since an update without "$set" means something different), or not knowing that update_one/delete_one only touch the first match.
"What happens if update_one(query, {"grade": 82}) is called WITHOUT wrapping the update in {"$set": ...}, against a real MongoDB server?" (Without an update operator like $set, MongoDB interprets the second argument as a full replacement document — it would replace the ENTIRE matched document with just {"grade": 82}, losing every other field, rather than updating just the grade field.)
8 When would you choose a relational database over a document database, and vice versa?
A relational database (MySQL, PostgreSQL) fits data with a genuinely fixed, well-known shape and relationships that benefit from being queried flexibly across tables via joins — financial ledgers, inventory systems, anything where consistency and enforced structure matter more than flexibility. A document database (MongoDB) fits data whose shape genuinely varies record to record, or where a whole related record naturally belongs nested inside its parent — a product catalog with wildly different attributes per category, user profiles with many optional fields. Real production systems often use both, chosen per use case, rather than picking one database for an entire company's needs.
Red flagsClaiming one is universally "better" than the other, or being unable to name a concrete real-world scenario that fits each.
Follow-up"Could a document database technically store data that also fits a relational model well?" (Yes, technically — but it would give up efficient joins across separate collections and any enforced fixed schema, so while it's possible, it's not naturally the best fit for that kind of data.)
9 What is a join, and why does a document database's design avoid needing one as often?
A join combines rows from two or more related tables (connected by a shared value, like a foreign key) into one combined result — it's necessary in a relational database because related data is deliberately split across separate, fixed-column tables. A document database avoids needing a join for the same relationship by nesting related data directly inside one document instead (a student's clubs stored as a list field on their own document, rather than in a separate clubs table). The tradeoff: nesting is simpler for reading one complete record, but a separate table with a join can be more efficient for certain cross-cutting queries (like "which students are in the chess club," across every student).
Describing joins as purely a limitation of SQL rather than understanding they're the natural consequence of deliberately normalized, separated tables.
Follow-up"Could nested data inside a MongoDB document ever become a problem for querying?" (Yes — querying "every student in the chess club" requires scanning every document and checking each one's nested clubs list, which can be less efficient at scale than a dedicated, indexed join in a relational design built specifically for that kind of cross-cutting query.)
10 How does connecting to a cloud-hosted database differ from connecting to a local one, at the code level?
Almost nothing about the driver code changes — the same mysql.connector.connect() or MongoClient() call is used either way. Only the value passed for the host (or, for MongoDB, the entire connection string/URI) changes, from "localhost" to a remote server's address. This is precisely why understanding the driver API well pays off: the exact same code that runs against a local database in development runs against a production, cloud-hosted database with just a configuration change, not a code change.
Believing cloud-hosted connections require an entirely different API or driver, rather than just a different host value.
Follow-up"If a team's local development database and production database use the exact same driver calls, what SHOULD differ between the two environments?" (Only the connection details — host, credentials, database name — ideally read from environment variables, so the same source code runs correctly against either environment without any code changes.)
11 Why should database credentials live in environment variables instead of directly in source code?
Source code is very often stored in a shared or public repository (like this course's own GitHub repo) — a hardcoded password or connection string committed there is exposed to anyone with access, and remains recoverable in the git history even after being removed from the latest version. Reading credentials through os.environ at startup means the actual secret value is set outside the source code entirely, on whatever machine or platform is actually running the program, so the same code can run correctly across a developer's laptop, a staging server, and production, each with different real credentials, without ever risking a leaked secret in version control.
Suggesting a hardcoded credential is acceptable "just for now" or in a private repository, or not knowing that git history retains removed secrets.
Follow-up"If a password was accidentally committed and later removed in a follow-up commit, is the secret still exposed?" (Yes — it still exists in the git history's earlier commit, retrievable by anyone with repository access unless the history itself is rewritten and force-pushed, which is disruptive and often impractical; the safer practice is rotating the leaked credential immediately, not just removing it from the latest code.)
12 What does TLS add to a cloud database connection, beyond keeping credentials out of source code?
Environment variables solve where credentials are stored; TLS (Transport Layer Security) separately solves how safely those credentials and the data itself travel over the network. Without TLS, anyone able to intercept network traffic between the program and a remote database server could potentially read the credentials and data being exchanged in plain text. Real cloud database services enable or require TLS by default specifically to prevent this — it's a different, complementary protection from "don't hardcode secrets," addressing what happens to data once it's actually in transit.
Red flagsConflating "credentials aren't hardcoded" with "the connection itself is secure" — they address genuinely different risks and both matter for a real cloud connection.
Follow-up"If credentials come from environment variables but the connection itself has no TLS, is the connection fully secure?" (No — the credentials are still sent over the network to authenticate the connection, and without TLS encrypting that traffic, they (and all data exchanged afterward) could be read by anyone able to intercept the connection, even though they're never hardcoded in the source code.)
Rapid-Fire Review
Quick recall check — fill in each blank and hit Check.