15Explain and fix AI-generated SQL

mediumsql
40:00

15 Explain and fix AI-generated SQL

OpenAI data scientist candidates report a screen where they're handed AI-generated SQL or Python and asked what it does and what's wrong with it (1 report), plus hands-on SQL (1 report).

solution.py holds four queries an assistant wrote against users(user_id, signup_date, country) and events(user_id, event, event_date). Each one runs without an error and each one is wrong. For each, first say what it was meant to compute and what it actually computes. Then fix it.

Set a 40-minute timer. Read one level at a time, and run only that level's tests until they pass: pytest problems/15_debug_ai_sql -k level1. Earlier levels must keep passing.

Level 1. DAILY_ACTIVE_USERS: distinct users with any event, per day. Columns event_date, dau, ordered by date.

Level 2. DAY7_RETENTION: per signup date, the share of users active exactly 7 days after signing up, not on day 7 or later. Columns signup_date, users, retained, retention, ordered by signup date. retention is a fraction from 0 to 1, like 0.5, not a percent.

Level 3. CONVERSION_BY_COUNTRY: per country, the share of users with at least one purchase. Columns country, users, buyers, conversion, ordered by country, with conversion a fraction from 0 to 1. Every country with users shows, even one with no buyers. A user who bought twice is still one buyer.

Level 4. NEVER_PURCHASED: the users who never made a purchase, as user_id, ordered. The events table can hold a guest purchase, with no user_id.

Things worth saying: how you'd catch each bug without knowing the answer (a sanity check on a number you know, a row count before and after a join, a country that vanished, a subquery run alone), and which of these an AI assistant gets wrong most often.

solution.py
Run the tests to see which pass.