smartyfy.mrindigi.com

Databases & SQL Master Course — 189. SQL Interview Problem Solving

Lesson 189 SQL Interview Problem Solving

Prerequisites and objectives

Complete Lesson 188 and review the earlier concepts named in this lesson. You will solve a latest-row-per-account problem by defining grain, tie policy, and missing-account behavior before choosing syntax. Review window ranking, joins, and correlated existence tests. The exercise rewards an explained, testable solution rather than memorizing a particular interview query.

Restate the problem as an output contract

Return exactly one row per account, including accounts without events. For accounts with events, choose the greatest event minute; if several events share that minute, choose the greatest event identity. Return the amount from that chosen event row. The identity tie-breaker is an explicit deterministic policy, not a claim about real-world chronology.

Ask whether the interviewer or stakeholder wants one winner or every tied latest event. Both are legitimate questions, but they produce different row counts. Also ask whether accounts without events should be absent, present with NULL, or separately classified. Resolving these details often matters more than selecting a compact SQL idiom.

The fixture makes ambiguity visible: account A has two events at minute twenty with different amounts, account B has one event, and account C has none. A solution tested only on unique timestamps and active accounts would not expose its tie or preservation behavior.

CREATE TABLE lab_account189(id TEXT PRIMARY KEY NOT NULL);
CREATE TABLE lab_event189(id INTEGER PRIMARY KEY,account TEXT NOT NULL,minute INTEGER NOT NULL,amount INTEGER NOT NULL);
INSERT INTO lab_account189 VALUES('A'),('B'),('C');
INSERT INTO lab_event189 VALUES(1,'A',10,100),(2,'A',20,200),(3,'A',20,150),(4,'B',5,90);
CREATE VIEW lab_latest189 AS WITH ranked AS (
SELECT id,account,minute,amount,ROW_NUMBER() OVER(PARTITION BY account ORDER BY minute DESC,id DESC) AS rn FROM lab_event189)
SELECT a.id AS account,r.id AS event_id,r.minute,r.amount FROM lab_account189 a LEFT JOIN ranked r ON r.account=a.id AND r.rn=1;
Observed latest-row contract
Account Chosen event Amount
A 3 at minute 20 150
B 4 at minute 5 90
C None NULL

Rank complete rows, then select a winner

ROW_NUMBER partitions events by account and orders each partition by descending minute and descending identity. The event primary key makes the full ordering unique. Filtering to rank one then selects a complete row, keeping its amount attached to its identity rather than aggregating attributes independently.

The outer account relation preserves C with a left join. The rank-one condition belongs in the join predicate in this formulation. Moving it to WHERE would reject the NULL-extended row for C and violate the one-row-per-account requirement. Explain that placement rather than treating it as stylistic formatting.

Do not combine MAX(minute) and MAX(amount) and assume both came from the same event. Aggregate values are computed independently. In this fixture, the chosen latest event under the tie policy has amount one hundred fifty, while A’s maximum amount is two hundred from another tied event.

Exercise 1

Produce the deterministic latest row for every account.

Worked solution
-- Connection A
SELECT account,event_id,minute,amount FROM lab_latest189 ORDER BY account;

The result has three rows because the account table defines the population. A’s event three wins the declared tie, and its own amount is returned. C remains present with missing event fields, which is different from an amount of zero.

Exercise 2

Expose the ambiguity of joining only to MAX(minute).

Worked solution
-- Connection A
WITH m AS (SELECT account,MAX(minute) AS minute FROM lab_event189 GROUP BY account) SELECT e.account,e.id,e.amount FROM lab_event189 e JOIN m ON m.account=e.account AND m.minute=e.minute ORDER BY e.account,e.id;

The timestamp-only join returns both latest A events. That is correct for an all-ties contract and wrong for the requested single-winner contract. Calling it a duplicate bug without asking the intended tie policy would miss the actual specification issue.

Exercise 3

Express the same event-winner rule as no better event exists.

Worked solution
-- Connection A
SELECT e.account,e.id,e.minute,e.amount FROM lab_event189 e WHERE NOT EXISTS (SELECT 1 FROM lab_event189 newer WHERE newer.account=e.account AND (newer.minute>e.minute OR (newer.minute=e.minute AND newer.id>e.id))) ORDER BY e.account;

The anti-existence predicate uses the same lexicographic ordering as the window solution. It returns event winners only, so a complete account report still needs the separate account population and outer join. Logical equivalence should be checked at the same output grain, not assumed from similar row values.

Exercise 4

Add a later event and verify which complete row replaces the winner.

Worked solution
-- Connection A
BEGIN;
INSERT INTO lab_event189 VALUES(5,'A',21,80);
SELECT event_id,minute,amount FROM lab_latest189 WHERE account='A';
ROLLBACK;

The new event wins because its minute is later, even though its amount is smaller. A correct latest-row query is not a maximum-amount query. Rollback returns A to event three and provides a compact regression test for the chosen ordering.

Explain correctness before discussing performance

Start a solution walkthrough with input grain, output grain, eligibility, ordering, and edge cases. Then show why each query layer preserves those properties. This is more persuasive than presenting dense syntax and hoping the expected sample output happens to appear.

For performance, consider an access path beginning with account and the ordering fields, but verify the actual plan and workload. A window scan and an anti-existence strategy can behave differently as data size, skew, and indexes change. Avoid universal claims that one syntax is always faster.

Portability also matters. Window functions are available in SQLite 3.25.0 and later, while engine-specific shortcuts may have different tie or NULL-ordering rules. State the target dialect and assumptions rather than silently translating a remembered PostgreSQL or MySQL solution into SQLite.

NULL event times require a policy not needed by this non-NULL fixture. Should unknown times be excluded, ranked after known events, or treated as a quality exception? Explicitly deciding prevents engine-default NULL ordering from becoming an accidental business rule.

Turn the answer into a reusable test

Maintain cases for no events, one event, tied maximum times, different amounts, a later smaller amount, and several accounts. Check both selected identities and row count. A test that checks only the maximum timestamp cannot detect an amount drawn from the wrong row.

During an interview, narrate a small counterexample to an attractive wrong approach. Here the two tied A events explain both why MAX-time joins can return multiple rows and why independently maximizing amount does not select a coherent record. That reasoning transfers to many deduplication and latest-state tasks.

Pitfalls and summary

Specify whether ties produce one row or several, preserve the required population, and keep selected attributes attached to a selected identity. Optimize only after the output contract and edge-case tests are correct, and explain deterministic tie-breaking without pretending it proves chronology.

Knowledge check

Question 1

Which event wins for account A initially?

  1. Event three: minute twenty, then greatest identity
  2. Event two because its amount is greatest
  3. Event one because it was inserted first
  4. Both events two and three under the single-winner contract
Answer and explanation

A. The declared ordering is minute descending, then identity descending.

Question 2

Why can MAX(minute) plus MAX(amount) be misleading?

  1. The row with the greatest amount must also have the greatest identity
  2. Grouping by account chooses one whole source row automatically
  3. The aggregate output preserves the source-row relationship between maxima
  4. The maxima can come from different event rows
Answer and explanation

D. Independent aggregates do not select a coherent event record.

Question 3

Why keep rn=1 in the LEFT JOIN condition here?

  1. To include every tied latest event instead of one winner
  2. To preserve accounts without events
  3. To filter out accounts with no matching event
  4. To make missing event amounts equal zero
Answer and explanation

B. A WHERE predicate on the missing ranked row would exclude the NULL-extended account.

Question 4

What does a greatest-identity tie-breaker establish?

  1. The true physical order of simultaneous events in every source
  2. The largest amount among tied events
  3. Deterministic selection under an explicit policy
  4. A guarantee that timestamps are accurate
Answer and explanation

C. Uniqueness can support repeatability without proving chronology.

Question 5

Which test best catches selecting amount independently from the latest row?

  1. Add a later event with a smaller amount
  2. Add an account with just one event and no ties
  3. Give every event of an account the same amount
  4. Add an index without changing the test data
Answer and explanation

A. The correct winner changes even though the maximum amount does not.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references