QSourceAI.
Menu

SQL Interviews: Joins, Window Functions and Query Reasoning

Learn to reason about data before typing a query.

Illustrated guide: SQL Interviews: Joins, Window Functions and Query Reasoning

Strong SQL candidates explain the shape and correctness of a result, not only the syntax.

Start with the grain

Define what one row represents in each table. Orders are often one-to-many with customers; joining them before aggregation changes counts. State the grain of your expected output before writing SQL. Clarify whether duplicates, null values and tied ranks are meaningful. A short clarification saves more time than an elaborate query that answers the wrong question.

Know why a join works

An inner join preserves matched rows while a left join also keeps unmatched left rows. Explain how filtering on a right-side column in WHERE can unintentionally turn a left join into an inner join. Practise ROW_NUMBER, RANK and LAG with PARTITION BY and ORDER BY; state a deterministic tie-breaker for latest-row problems.

Validate with small data

Predict the output for three customers, two orders, a duplicate and one missing match. Check counts and null behavior before optimizing. When performance matters, talk about filters, join order, partitions and query plans in the actual engine instead of declaring one pattern universally fastest.

A realistic interview drill

Give yourself five rows in customers and seven in orders, including one customer with no orders and one with two orders on the same day. First calculate total spending per customer. Then find each customer's latest order and customers who have never ordered. For every query, say the number of rows you expect before executing it. When the interviewer asks about performance, ask which engine and dataset size are involved before discussing indexes or partitions. In a columnar warehouse, partition pruning and scan size may dominate; in an OLTP database, a selective composite index may be more useful. This distinction shows you understand that query tuning depends on the physical execution model. Finally, explain how you would test the query against duplicates, null values and ties. Interviewers can follow the reasoning even if you make a small syntax mistake.

PUT IT INTO WORDS

A practical example

To find the latest order per customer, use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, order_id DESC), then filter rn = 1. Say which row wins when dates tie.

Try this today

Create two miniature tables with missing matches and duplicate keys. Write an inner join, left join and top-two-per-group query. Explain the expected row counts before executing them.

Before you move on

  • State the output grain
  • Handle duplicates deliberately
  • Test with edge cases
YOUR REAL-TIME INTERVIEW CO-PILOT

Real questions. Answers built around you.

Practise SQL explanations in QSourceAI using your own database project notes.

Try QSourceAI for Windows ↗