KatInterview

SQL Window Functions, Join Cardinalities, Dedup, and Pandas Merges

SQL & DataModel answer
MediumModel answerSQL & Datasqlpandaswindow-functions

Last updated

Work through ten interconnected SQL and pandas tasks spanning aggregations with NULL handling, join types, set operations, window functions, views, duplicate management, and indexing strategy.

You are given the following schema and sample data. Answer every sub-question below. Assume ANSI SQL unless you make a dialect-specific choice (explain it). Use PostgreSQL where the standard leaves ambiguity.

Schema

  • customers(customer_id PK, name)
  • orders(order_id PK, customer_id FK→customers, order_date DATE, amount DECIMAL(10,2))
  • order_items(item_id PK, order_id FK→orders, product_id FK→products, qty INT, price DECIMAL(10,2))
  • products(product_id PK, name, category)
  • web_orders(order_id, customer_id, amount) — no PK, may contain duplicate rows
  • store_orders(order_id, customer_id, amount) — no PK
  • employees(emp_id PK, name, salary INT)

Sample data

customers: (1,Alice) (2,Bob) (3,Carol)
orders: (101,1,2025-08-28,120.00) (102,1,2025-08-30,80.00) (103,2,2025-08-29,50.00) (105,3,2025-08-30,NULL)
order_items: (1,101,10,1,120.00) (2,102,11,2,40.00) (3,103,12,1,50.00)
products: (10,Phone,Electronics) (11,Cable,Electronics) (12,Book,Media)
web_orders: (201,1,50.00) (202,1,50.00) (202,1,50.00)
store_orders: (301,1,50.00) (202,1,50.00) (302,2,50.00)
employees: (1,Alice,100) (2,Bob,200) (3,Carol,300) (4,Dave,300)

Pandas DataFrames (for Task 10):

df_a: id→[1,2,3] city→[SF,NYC,LA]
df_b: id→[2,3,4] spend→[80,20,10]
df_c: id→[3] tag→[vip]

Tasks

  1. Aggregations and NULLs. Write a query computing per-customer COUNT(*), COUNT(amount), SUM(amount), AVG(amount), MIN(order_date), MAX(order_date). Show how the NULL in orders.amount for customer 3 changes each result. Explain COUNT(column) vs COUNT(*) and why AVG ignores NULLs rather than treating them as zero. Separately, compute total revenue from order_items using SUM(qty*price) and compare it to SUM(orders.amount); explain any mismatch and provide a query to detect per-order inconsistencies.

  2. Joins. (a) INNER JOIN customers↔orders listing customers who have orders. (b) LEFT JOIN that includes zero-order customers with 0 as their total. (c) FULL OUTER JOIN and explain which rows appear on only one side. (d) CROSS JOIN products with the distinct set of categories, then show how to restrict it. Give queries and representative output rows.

  3. UNION vs UNION ALL. Combine web_orders and store_orders into one result of (order_id, customer_id, amount). (a) Using UNION ALL, report total row count and how many extra rows are duplicates by order_id. (b) Using UNION (distinct), list the deduplicated rows. (c) Return only order_id values present in both sources without using INTERSECT.

  4. Window functions. (a) For each customer, rank orders by amount descending and return only the top-ranked row using ROW_NUMBER. (b) Compute a running total of amount per customer ordered by order_date; show where partitions reset. (c) For August 2025, compute each customer's monthly spend with SUM(amount) OVER(PARTITION BY customer_id) and then rank customers by spend using DENSE_RANK. Explain why a window function does not collapse rows the way GROUP BY does.

  5. Views. Create a view top_spenders_2025_08(customer_id, total_amount) over orders. Is it updatable, and under what conditions? What happens if the base table gains a NOT NULL column or a referenced column is dropped? Compare plain views vs materialized views for a closed month, and show how to refresh a materialized view in your chosen RDBMS.

  6. Hide duplicates at read time. Return one row per distinct (order_id, customer_id, amount) from web_orders without modifying the table. Show both a DISTINCT approach and a ROW_NUMBER filtering approach; compare performance and determinism.

  7. Delete duplicates safely. Remove true duplicate rows from web_orders keeping the lowest ROW_NUMBER ranked by (order_id, customer_id, amount) with a reproducible tie-breaker. Show the DELETE with a CTE inside a transaction.

  8. Nth highest salary. Given employees(name, salary) and a parameter :n, return the Nth highest distinct salary. Show outputs for n=1, 2, 3 on the sample and explain behavior when n exceeds the number of distinct salaries.

  9. Efficiency. Propose indexes for the above workloads (e.g., orders(customer_id, order_date), order_items(order_id), covering indexes). Rewrite one query to be sargable. Explain when EXISTS beats IN and when a window function replaces a self-join. Describe how to verify improvements via execution plans and timing.

  10. Pandas. Using df_a, df_b, and df_c, specify exact calls (with how=, on=, axis=, ignore_index=, validate=) to: (a) left-join spend onto cities; (b) inner-join both frames then right-join to keep only ids in df_b; (c) stack df_a vertically with a new rows frame; (d) align on index instead of a column; (e) explain when concat vs merge is appropriate.

Hints

Hint 1

COUNT(*) counts all rows; COUNT(column) skips NULLs, and AVG divides by the count of non-NULL values only.

Hint 2

When a LEFT JOIN finds no match, every column from the joined table is NULL — use COALESCE to surface zeros.

Hint 3

ROW_NUMBER with PARTITION BY assigns sequential ranks per group without collapsing rows, which is why you need DISTINCT or a subquery before DENSE_RANK across groups.

Hint 4

Identical duplicate rows have no natural key — use PostgreSQL's ctid or a SQL Server CTE-delete as the tie-breaker.