🐍 Python for Everyone

← Back to practice bank

Chapter 21 Coding Challenges 50-65 min, auto-graded

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.

How grading works Your code runs entirely in your browser using Pyodide (Python compiled to WebAssembly) — nothing is uploaded anywhere. Keep the function name in the stub exactly as given, since the grader calls it by name.

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.

Constraints: system_name is always a string.
Examples:
classify_db_type("MySQL") → "relational"
classify_db_type("MongoDB") → "document"
challenge_1.py
Show Solution
solution_1.py
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.

Constraints: table and column are strings; value may be any type.
Examples:
build_select_query("students", "name", "Ana") → ["SELECT * FROM students WHERE name = %s", ["Ana"]]
challenge_2.py
Show Solution
solution_2.py
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.

Constraints: sql_building_code is always a string.
Examples:
is_injection_vulnerable('"SELECT * FROM t WHERE name = %s"') → false
is_injection_vulnerable('"SELECT * FROM t WHERE name = " + name') → true
challenge_3.py
Show Solution
solution_3.py
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.

Constraints: table is a list of dicts, each with a "name" key; name is a string.
Examples:
safe_lookup([{"name": "Ben", "grade": 78}], "Ben") → {"name": "Ben", "grade": 78}
safe_lookup([{"name": "Ben", "grade": 78}], "x' OR '1'='1") → None
challenge_4.py
Show Solution
solution_4.py
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.

Constraints: documents is a list of dicts; query is a dict (possibly empty).
Examples:
count_matching_documents([{"grade": 91}, {"grade": 78}], {"grade": 91}) → 1
challenge_5.py
Show Solution
solution_5.py
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.

Constraints: document and set_fields are both dicts.
Examples:
apply_set_update({"name": "Ana", "grade": 91}, {"grade": 95}) → {"name": "Ana", "grade": 95}
challenge_6.py
Show Solution
solution_6.py
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.

Constraints: both arguments are booleans.
Examples:
recommend_storage_model(false, true) → "relational"
recommend_storage_model(true, false) → "document"
challenge_7.py
Show Solution
solution_7.py
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.

Constraints: every key in required_keys is guaranteed to exist in env.
Examples:
build_config_from_env({"DB_HOST": "cloud.example.com", "DB_USER": "reader"}, ["DB_HOST"]) → {"DB_HOST": "cloud.example.com"}
challenge_8.py
Show Solution
solution_8.py
def build_config_from_env(env, required_keys):
    return {key: env[key] for key in required_keys}
← Practice Bank Interview Questions →