Coding Challenges: Working with Databases
8 HackerRank-style challenges, auto-graded right in your browser —
no setup required, and no live database or driver install needed. Write
your function in the code box, then click Run Tests to
check it against a set of test cases (including edge cases). Stuck?
Every challenge has a Show Solution reveal at the
bottom. Only uses what Chapters 1-21 have covered so far. No import
beyond
json/os/re/math/datetime/random/csv/threading/concurrent.futures.
1 Classify a Database Type Easy
Write a function classify_db_type(system_name) that returns "relational" if system_name is one of "MySQL", "PostgreSQL", or "SQLite"; "document" if it's one of "MongoDB" or "CouchDB"; and "unknown" otherwise.
system_name is always a string.
classify_db_type("MySQL") → "relational"classify_db_type("MongoDB") → "document"
Show Solution
def classify_db_type(system_name):
relational = {"MySQL", "PostgreSQL", "SQLite"}
document = {"MongoDB", "CouchDB"}
if system_name in relational:
return "relational"
if system_name in document:
return "document"
return "unknown"
2 Build a Parameterized Query Medium
Write a function build_select_query(table, column, value) that returns a two-item list [sql, params], where sql is the string f"SELECT * FROM {table} WHERE {column} = %s" and params is the list [value] — the table and column names are safe to format directly (they come from your own code, not user input), but the value always stays a separate parameter.
table and column are strings; value may be any type.
build_select_query("students", "name", "Ana") → ["SELECT * FROM students WHERE name = %s", ["Ana"]]
Show Solution
def build_select_query(table, column, value):
sql = f"SELECT * FROM {table} WHERE {column} = %s"
return [sql, [value]]
3 Detect an SQL Injection Risk Medium
Write a function is_injection_vulnerable(sql_building_code) that returns True if the given line of code (as a string) looks like it builds SQL by directly formatting a value into the string — specifically, if it contains f" or f' (an f-string), or contains " + " without also containing %s (string concatenation with no parameterized placeholder) — and False otherwise.
sql_building_code is always a string.
is_injection_vulnerable('"SELECT * FROM t WHERE name = %s"') → falseis_injection_vulnerable('"SELECT * FROM t WHERE name = " + name') → true
Show Solution
def is_injection_vulnerable(sql_building_code):
has_fstring = 'f"' in sql_building_code or "f'" in sql_building_code
has_concat_no_params = " + " in sql_building_code and "%s" not in sql_building_code
return has_fstring or has_concat_no_params
4 Safely Look Up a Row Easy
Write a function safe_lookup(table, name) that searches a list of dicts table (each with a "name" key) for the first row where row["name"] == name, returning that row, or None if no row matches. This models what a parameterized WHERE name = %s query does: name is only ever compared as plain data, so a value like "x' OR '1'='1" simply won't match any real row, instead of matching every row the way an injected query would.
table is a list of dicts, each with a "name" key; name is a string.
safe_lookup([{"name": "Ben", "grade": 78}], "Ben") → {"name": "Ben", "grade": 78}safe_lookup([{"name": "Ben", "grade": 78}], "x' OR '1'='1") → None
Show Solution
def safe_lookup(table, name):
matches = [row for row in table if row["name"] == name]
return matches[0] if matches else None
5 Count Matching Documents Medium
Write a function count_matching_documents(documents, query) that returns how many dicts in the list documents match every key/value pair in the dict query — the same matching rule pymongo's find() uses. An empty query matches every document.
documents is a list of dicts; query is a dict (possibly empty).
count_matching_documents([{"grade": 91}, {"grade": 78}], {"grade": 91}) → 1
Show Solution
def count_matching_documents(documents, query):
return sum(1 for d in documents if all(d.get(k) == v for k, v in query.items()))
6 Apply a $set-Style Update Easy
Write a function apply_set_update(document, set_fields) that returns a new dict equal to document with every key/value pair from set_fields applied on top — modeling what pymongo's {"$set": set_fields} does: change only the given fields, leave everything else untouched.
document and set_fields are both dicts.
apply_set_update({"name": "Ana", "grade": 91}, {"grade": 95}) → {"name": "Ana", "grade": 95}
Show Solution
def apply_set_update(document, set_fields):
updated = dict(document)
updated.update(set_fields)
return updated
7 Recommend a Storage Model Medium
Write a function recommend_storage_model(shape_varies, needs_joins) that returns "relational" if needs_joins is True and shape_varies is False; "document" if shape_varies is True and needs_joins is False; and "either could work" in every other case.
recommend_storage_model(false, true) → "relational"recommend_storage_model(true, false) → "document"
Show Solution
def recommend_storage_model(shape_varies, needs_joins):
if needs_joins and not shape_varies:
return "relational"
if shape_varies and not needs_joins:
return "document"
return "either could work"
8 Build a Config from Environment Variables Easy
Write a function build_config_from_env(env, required_keys) that returns a dict containing only the keys listed in required_keys, with their values taken from the dict env (standing in for os.environ) — modeling how a program should read its database connection details from environment variables instead of hardcoding them.
required_keys is guaranteed to exist in env.
build_config_from_env({"DB_HOST": "cloud.example.com", "DB_USER": "reader"}, ["DB_HOST"]) → {"DB_HOST": "cloud.example.com"}
Show Solution
def build_config_from_env(env, required_keys):
return {key: env[key] for key in required_keys}