SQL Window Functions, Join Cardinalities, Dedup, and Pandas Merges
SQL & DataModel answerLast 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 rowsstore_orders(order_id, customer_id, amount)— no PKemployees(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
-
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 inorders.amountfor customer 3 changes each result. ExplainCOUNT(column)vsCOUNT(*)and whyAVGignores NULLs rather than treating them as zero. Separately, compute total revenue fromorder_itemsusingSUM(qty*price)and compare it toSUM(orders.amount); explain any mismatch and provide a query to detect per-order inconsistencies. -
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.
-
UNION vs UNION ALL. Combine
web_ordersandstore_ordersinto one result of(order_id, customer_id, amount). (a) Using UNION ALL, report total row count and how many extra rows are duplicates byorder_id. (b) Using UNION (distinct), list the deduplicated rows. (c) Return onlyorder_idvalues present in both sources without usingINTERSECT. -
Window functions. (a) For each customer, rank orders by
amountdescending and return only the top-ranked row usingROW_NUMBER. (b) Compute a running total ofamountper customer ordered byorder_date; show where partitions reset. (c) For August 2025, compute each customer's monthly spend withSUM(amount) OVER(PARTITION BY customer_id)and then rank customers by spend usingDENSE_RANK. Explain why a window function does not collapse rows the wayGROUP BYdoes. -
Views. Create a view
top_spenders_2025_08(customer_id, total_amount)overorders. 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. -
Hide duplicates at read time. Return one row per distinct
(order_id, customer_id, amount)fromweb_orderswithout modifying the table. Show both aDISTINCTapproach and aROW_NUMBERfiltering approach; compare performance and determinism. -
Delete duplicates safely. Remove true duplicate rows from
web_orderskeeping the lowestROW_NUMBERranked by(order_id, customer_id, amount)with a reproducible tie-breaker. Show the DELETE with a CTE inside a transaction. -
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. -
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 whenEXISTSbeatsINand when a window function replaces a self-join. Describe how to verify improvements via execution plans and timing. -
Pandas. Using
df_a,df_b, anddf_c, specify exact calls (withhow=,on=,axis=,ignore_index=,validate=) to: (a) left-join spend onto cities; (b) inner-join both frames then right-join to keep only ids indf_b; (c) stackdf_avertically with a new rows frame; (d) align on index instead of a column; (e) explain whenconcatvsmergeis 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
A strong candidate covers four themes: NULL-aware aggregation, join and set cardinality, window-vs-aggregate thinking, and safe data changes. PostgreSQL is the dialect of choice.
1. Aggregations and NULLs
SELECT customer_id,
COUNT(*) AS row_count,
COUNT(amount) AS non_null_amt,
SUM(amount) AS total_spend,
AVG(amount) AS avg_spend,
MIN(order_date) AS first_order,
MAX(order_date) AS last_order
FROM orders
GROUP BY customer_id;
Customer 3 has one row but COUNT(amount) is 0, SUM is NULL, and AVG is NULL. COUNT(*) counts every row regardless of NULLs; COUNT(col) skips NULLs. AVG computes SUM(non-null)/COUNT(non-null), so NULLs are excluded from both numerator and denominator — they are not treated as zero. To force zero semantics, use AVG(COALESCE(amount,0)).
Reconciliation: SUM(qty*price) from order_items yields 250.00 (120 + 80 + 50). SUM(orders.amount) also yields 200.00 from non-NULL amounts plus a NULL — the totals match here only because order 105 has a NULL header and no line items. Detect per-order mismatches:
WITH line_totals AS (
SELECT order_id, SUM(qty * price) AS items_total
FROM order_items GROUP BY order_id
)
SELECT COALESCE(o.order_id, lt.order_id) AS order_id,
o.amount, lt.items_total
FROM orders o
FULL JOIN line_totals lt ON lt.order_id = o.order_id
WHERE o.amount IS DISTINCT FROM lt.items_total;
Order 105 shows up as a mismatch (NULL header, no line items).
2. Joins
-- (a) customers who placed at least one order
SELECT DISTINCT c.customer_id, c.name
FROM customers c JOIN orders o USING (customer_id);
-- (b) include zero-order customers
SELECT c.customer_id, c.name,
COUNT(o.order_id) AS order_count,
COALESCE(SUM(o.amount), 0) AS total
FROM customers c LEFT JOIN orders o USING (customer_id)
GROUP BY c.customer_id, c.name;
-- (c) full outer join
SELECT c.customer_id, o.order_id
FROM customers c FULL JOIN orders o USING (customer_id);
-- (d) cross join with categories
SELECT p.name, k.category
FROM products p
CROSS JOIN (SELECT DISTINCT category FROM products) k;
In (b), Carol appears with order_count = 1 (order 105 exists but has a NULL amount; COUNT(o.order_id) still counts the row because order_id is non-NULL) and total = 0 via COALESCE. In (c), all rows match because the FK is enforced; a customer with no orders would show NULL on the orders side. In (d), the Cartesian product yields 3×2 = 6 rows; adding WHERE p.category = k.category restricts it to the 3 matching rows, effectively making it an inner join.
3. UNION vs UNION ALL
-- (a) UNION ALL with duplicate count
WITH combined AS (
SELECT * FROM web_orders
UNION ALL
SELECT * FROM store_orders
)
SELECT COUNT(*) AS total_rows,
COUNT(*) - COUNT(DISTINCT order_id) AS duplicate_rows
FROM combined;
-- total_rows = 6, duplicate_rows = 2 (order 202 appears three times total)
-- (b) UNION (distinct) deduplicates
SELECT order_id, customer_id, amount FROM web_orders
UNION
SELECT order_id, customer_id, amount FROM store_orders;
-- returns 4 rows: 201, 202, 301, 302
-- (c) common order_ids without INTERSECT
SELECT DISTINCT w.order_id
FROM web_orders w
WHERE EXISTS (SELECT 1 FROM store_orders s WHERE s.order_id = w.order_id);
-- returns 202
UNION inserts a sort or hash dedup step. Default to UNION ALL unless you specifically need deduplication.
4. Window functions
-- (a) top order per customer
SELECT order_id, customer_id, amount, order_date
FROM (
SELECT o.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY amount DESC NULLS LAST, order_id
) AS rn
FROM orders o
) t WHERE rn = 1;
-- returns 101 (Alice, 120), 103 (Bob, 50), 105 (Carol, NULL)
-- (b) running total
SELECT customer_id, order_id, order_date, amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY order_date, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders;
-- Alice: 120 → 200; Bob: 50; Carol: NULL (partition resets per customer)
-- (c) monthly spend rank
WITH monthly AS (
SELECT DISTINCT customer_id,
SUM(amount) OVER (PARTITION BY customer_id) AS spend
FROM orders
WHERE order_date >= DATE '2025-08-01'
AND order_date < DATE '2025-09-01'
)
SELECT customer_id, spend,
DENSE_RANK() OVER (ORDER BY spend DESC NULLS LAST) AS rank
FROM monthly;
-- (1, 200, 1), (2, 50, 2), (3, NULL, 3)
PostgreSQL sorts NULLs first under DESC, so NULLS LAST is essential. The explicit ROWS frame in (b) prevents RANGE from treating same-date rows as peers. Window functions compute per-row values over a set of related rows without reducing row count; GROUP BY collapses each group to one row. That is why (c) needs DISTINCT before DENSE_RANK — the window keeps all rows, and we collapse manually.
5. Views
CREATE VIEW top_spenders_2025_08 (customer_id, total_amount) AS
SELECT customer_id, SUM(amount)
FROM orders
WHERE order_date >= DATE '2025-08-01'
AND order_date < DATE '2025-09-01'
GROUP BY customer_id;
This view is not updatable because it uses aggregation. A view is updatable only when it reads from a single base table with no GROUP BY, aggregates, DISTINCT, window functions, or set operations. If the base table gains a NOT NULL column with no default, inserts through an updatable view fail. If a referenced column is dropped, PostgreSQL refuses the drop unless CASCADE is used (which drops the view); SQL Server with SCHEMABINDING prevents the drop entirely.
A closed month rarely changes, so a materialized view is ideal — fast reads at the cost of storage and staleness:
CREATE MATERIALIZED VIEW mv_top_spenders_2025_08 AS
SELECT * FROM top_spenders_2025_08;
CREATE UNIQUE INDEX ON mv_top_spenders_2025_08 (customer_id);
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_top_spenders_2025_08;
The unique index enables CONCURRENTLY, which avoids blocking readers during refresh.
6. Hide duplicates at read time
-- DISTINCT approach
SELECT DISTINCT order_id, customer_id, amount FROM web_orders;
-- ROW_NUMBER approach
SELECT order_id, customer_id, amount FROM (
SELECT w.*,
ROW_NUMBER() OVER (
PARTITION BY order_id, customer_id, amount
ORDER BY order_id
) AS rn
FROM web_orders w
) t WHERE rn = 1;
DISTINCT is simpler and usually faster (single hash aggregate). ROW_NUMBER costs a sort but lets you pick which row survives by defining a total order, which matters when you need to carry extra columns or choose by recency.
7. Delete duplicates safely
BEGIN;
WITH ranked AS (
SELECT ctid,
ROW_NUMBER() OVER (
PARTITION BY order_id, customer_id, amount
ORDER BY ctid
) AS rn
FROM web_orders
)
DELETE FROM web_orders w
USING ranked r
WHERE w.ctid = r.ctid AND r.rn > 1;
-- verify, then COMMIT or ROLLBACK
ctid is PostgreSQL's physical row identifier and serves as a deterministic tie-breaker for otherwise identical rows. In SQL Server, you can DELETE directly from the CTE. Always wrap in a transaction so you can verify row counts before committing.
8. Nth highest salary
SELECT (
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET :n - 1
) AS nth_highest;
For n=1: 300. For n=2: 200. For n=3: 100. When n exceeds the number of distinct salaries (4 distinct values → n=5), the subquery returns NULL. Using DISTINCT ensures ties (Carol and Dave both at 300) are treated as a single rank.
9. Efficiency
Key indexes: orders(customer_id, order_date) supports per-customer temporal queries and window partitions; order_items(order_id) speeds the reconciliation join; a covering index like orders(customer_id, order_date, amount) avoids heap lookups for spend calculations.
Sargable rewrite — instead of WHERE EXTRACT(MONTH FROM order_date) = 8, use WHERE order_date >= DATE '2025-08-01' AND order_date < DATE '2025-09-01' so the index on order_date is usable.
EXISTS outperforms IN when the subquery returns a large result set, because EXISTS short-circuits on the first match. IN is fine for small lists. A window function like ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ...) replaces a self-join for top-N-per-group queries — it avoids the O(n²) cost of joining a table to itself. Verify with EXPLAIN ANALYZE to compare seq scans vs index scans, sort methods, and actual timings.
10. Pandas
import pandas as pd
# (a) left-join spend onto cities
df_a.merge(df_b, on='id', how='left', validate='one_to_one')
# (b) inner-join then right-join to keep only df_b ids
inner = df_a.merge(df_b, on='id', how='inner', validate='one_to_one')
inner.merge(df_b, on='id', how='right', validate='one_to_one')
# equivalently: df_a.merge(df_b, on='id', how='right')
# (c) stack vertically with new rows
new_rows = pd.DataFrame({'id': [5], 'city': ['SEA']})
pd.concat([df_a, new_rows], axis=0, ignore_index=True)
# (d) align on index instead of column
df_a_idx = df_a.set_index('id')
df_b_idx = df_b.set_index('id')
df_a_idx.join(df_b_idx, how='left')
# (e) concat vs merge
# Use concat to stack frames vertically or horizontally by position/index.
# Use merge for relational joins keyed by column values (inner, left, right, outer).
validate='one_to_one' catches unexpected duplicates at runtime. ignore_index=True resets the index after concatenation so you do not get duplicate labels. join is a convenience wrapper around merge that defaults to joining on indexes rather than columns.