SQL and Python together
In some interviews the Python code talks to the same database as the SQL part. This task practises the split: SQL filters the data and returns a short result, Python does the logic that is awkward in SQL, and the parameters reach the database safely. It builds on Python and SQL and on the filters from Revenue reports.
P11. SQL + Python together: longest sales streak
Section titled “P11. SQL + Python together: longest sales streak”A merchant wants to know their best streak: how many days in a row they had sales. In many interview editors your Python code can query the same database as the SQL part, so this task uses both.
The function gets a database connection con, a merchant id and a date range. Use SQL to get the days on which this merchant had at least one paid sale (revenue_usd > 0, no test purchases). Pass the parameters with ? placeholders, not with an f-string. Then, in Python, find the longest run of consecutive days.
Return (length of the run, first day of the run). If several runs have the same length, return the earliest one. No sales at all gives (0, None).
sales on September 1, 2, 5, 6, 7 and 10 → (3, date(2026, 9, 5)) # the 5th, 6th and 7th in a row
Full statement (as in the task file)
In many interview editors the Python code can query the same database as the SQL part. Practise that here.
longest_streak(con, merchant_id="mer_01", first_day=date(2026, 9, 1), last_day=date(2026, 9, 29))
-> (3, date(2026, 9, 21)) # 3 days in a row with at least one paid sale, starting on Sep 21
- Use SQL to get the DAYS on which the merchant had at least one paid transaction (revenue_usd > 0, test purchases excluded) between first_day and last_day inclusive (day of start_time, UTC). Pass the parameters to the query safely: `con.execute(sql, [param1, param2, ...])` with `?` placeholders. Never build the SQL string with f-strings or +.
- Then, in Python, find the longest run of consecutive days. Return (length, first_day_of_that_run).
- Several runs of the same length -> the earliest one. No sales at all -> (0, None).
The same call with SQLAlchemy: conn.execute(sa.text("… WHERE p.merchant_id = :mer"), {"mer": merchant_id}).Ask first
Say each question out loud before you code. Open the interviewer's answer only after you asked.
Type the questions you would ask the interviewer, and say each one out loud. The task's questions and their answers open when you end the mock.
Why not do it all in SQL?
You can (gaps and islands), but here we practise SQL + Python. Say which part you would keep in SQL on a big table, and why.
Which days count?
Days (UTC, by start_time) with at least one paid sale: revenue_usd > 0, test purchases excluded. last_day is included.
Two runs of the same length?
Return the earliest one.
No sales at all?
Return (0, None).
def longest_streak(con, merchant_id, first_day, last_day):
raise NotImplementedError("your code")
Run executes the file top to bottom, like python file.py. Check imports it as a module and runs the tests.
Hint: what the interviewer would nudge
Let SQL return only what you need: the distinct days with a paid sale, sorted. The streak is then one loop over a list of dates.
Say it: SQL filters and returns distinct days; Python finds the longest run in one pass. Parameters are bound, never formatted into the string.
Reference solution
from datetime import timedelta
DAYS_WITH_SALES = """ SELECT DISTINCT CAST(t.start_time AS DATE) AS day FROM transactions t JOIN products p ON p.id = t.product_id WHERE p.merchant_id = ? AND NOT t.is_test AND t.revenue_usd > 0 AND t.start_time >= ? AND t.start_time < ? ORDER BY day"""
def longest_streak(con, merchant_id, first_day, last_day): rows = con.execute(DAYS_WITH_SALES, [merchant_id, first_day, last_day + timedelta(days=1)]).fetchall() days = [r[0] for r in rows] # sorted, unique: the heavy work stays in SQL best_len, best_start = 0, None run_len, run_start = 0, None previous = None for day in days: if previous is not None and day == previous + timedelta(days=1): run_len += 1 else: run_len, run_start = 1, day if run_len > best_len: # strictly greater: the earliest run wins ties best_len, best_start = run_len, run_start previous = day return best_len, best_startWalkthroughTry the task first: the walkthrough is most useful after your own attempt.
What it is for. “The best streak of days with sales.” SQL returns a short list of days, and the streak logic is easier to write in Python.
Steps.
- SQL:
SELECT DISTINCT CAST(t.start_time AS DATE)throughproductsto the merchant, withNOT is_test,revenue_usd > 0, the date range andORDER BY day. The parameters go in as?placeholders. - Python: one pass over the sorted days. If a day is the previous day + 1, the current run grows; otherwise a new run starts. Keep the best run and its first day.
Traps.
last_dayis included, so the SQL needsstart_time < last_day + 1 day: passlast_day + timedelta(days=1).- Parameters only through
?, never through f-strings or+. This prevents SQL injection, and the database can reuse the plan. Two tests check this. One runs your function on a connection that records every query, and fails if the merchant id or a date is inside the SQL text. The other reads your source code, and fails if an f-string,+,%or.format()builds a string that looks like SQL. - With runs of the same length, keep the earliest: the comparison is strictly
>. - No sales at all gives
(0, None), so start the best run with those values.
Check. For mer_01 from 1 to 29 September, SQL returns 14 days, and the answer is (3, date(2026, 9, 21)): 21, 22 and 23 September.
Worth saying. On a big table the filter and DISTINCT stay in the database: it sends 14 rows, not every transaction. The streak can also be found in SQL with the “gaps and islands” pattern; mention it, even if you write it in Python.
Complexity. The Python part is O(d) for d days with sales. The SQL part is one range scan; an index on (product_id, start_time) would serve it on a big table.
In other editors. With SQLAlchemy the same rule uses named parameters: conn.execute(sa.text("… WHERE p.merchant_id = :mer"), {"mer": merchant_id}).
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.