Joins and subqueries
35 questions in 10 subtopics.
Inner joins
Tables:customers(id, name, city), orders(id, customer_id, total, created_at). Write SQL that lists each customer name with the number of orders and total spent in 2025, only for customers who ordered at least once in 2025.A report joins orders to order_lines and to payments, then sums orders.total. The totals are two to three times too high. Explain why and fix it.Is there a difference between putting a condition in the ON clause and in the WHERE clause of an inner join? What about an outer join? Give an example with orders and a status filter.Analysts across the company write reports joining 12 core tables and frequently get fan-out and wrong joins. Would you give them views, a semantic layer, denormalised reporting tables, or training? Explain the decision.Your company has 15 years of reports, each with its own join logic for revenue, and finance found three different revenue numbers in one board meeting. How do you fix this at the organisational level?Left, right and full outer joins
Explain LEFT, RIGHT and FULL OUTER JOIN with a small example, and say why many teams avoid RIGHT JOIN. Does MySQL 8.4 support FULL OUTER JOIN?Write SQL that lists every product with its total quantity sold in the last 30 days, showing 0 for products that sold nothing. Tables:products(id, name), order_lines(product_id, qty, sold_at).You must reconcile a payments table in your database with a daily settlement file loaded into settlements(ref, amount). Write the query that finds missing on either side and amount mismatches, and describe how you would run it on 50 million rows.An ORM-generated query with five LEFT JOINs for optional relationships has become the slowest query in a service. Developers say all joins are needed for the screen. How would you approach it?Self joins
Tableemployees(id, name, manager_id, salary). Write SQL that lists employees who earn more than their manager, with both names.Table employees(id, name, manager_id). Write a PostgreSQL query that returns the full reporting chain under a given manager with depth, and protect it against cycles in bad data.A product catalogue stores categories as a self-referencing parent_id table, and queries for all products under a category are slow and complex. Compare adjacency list, closure table, materialised path and nested sets, and recommend one.Cross joins and cartesian products
What does a CROSS JOIN produce, and give one legitimate use. How does an accidental cartesian product usually appear in a query?Write SQL that produces daily sales per store for every day of March 2026, showing 0 for days without sales. Tables:stores(id), sales(store_id, sold_on, amount). Use PostgreSQL.A deploy added one filter to a reporting query, and the database ran out of temp space within minutes and other services timed out. The new query had FROM orders o, regions r WHERE o.created_at > :d AND r.active. What happened, and what guardrails would you add?Semi-joins and anti-joins with EXISTS
Write two queries: customers who placed at least one order, and customers who never placed one, using EXISTS and NOT EXISTS. Why is EXISTS preferred over JOIN with DISTINCT for the first?How do PostgreSQL and MySQL execute EXISTS and NOT EXISTS subqueries? What plan nodes do you expect, and when can they be slow?A nightly job finds accounts with no activity in 2 years using LEFT JOIN activity ... WHEREactivity.id IS NULL over 300 million activity rows, and it now runs for 4 hours. How would you make it fast and safe?NOT IN and NULL pitfalls
This query returns no rows, but you know some customers have no orders: SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders). Explain why and fix it.Explain how NULL behaves in =, <>, IN, NOT IN,COUNT(col), COUNT(*), GROUP BY and unique constraints in PostgreSQL. Which of these surprise developers most?NULL-related bugs keep reaching production in reporting and data services across teams. What standards for schema design, SQL review and testing would you introduce?Correlated subqueries
Write a correlated subquery that returns each order whose total is above the average total of that customer's orders, then rewrite it with a window function.A Spring Data JPA query for a list page uses a correlated subquery in the select list to fetch each customer's latest order date. The page takes 8 seconds for 5,000 customers. How do you diagnose and fix it?What does LATERAL (PostgreSQL) or CROSS APPLY (SQL Server) add over a correlated subquery, and when is it the best tool for a top-N-per-group query?Derived tables
What is a derived table, and how does it differ from a CTE and a view? Show an example where a derived table is needed.After upgrading from PostgreSQL 11 to 17, a query using WITH recent AS (SELECT ... FROM events WHERE ...) SELECT ... became much slower, while others became faster. What changed and how do you control it?Your company's SQL has grown into thousand-line queries with nested derived tables and CTEs embedded in Java strings across hundreds of services. What long-term strategy would you set for complex SQL: where it lives, how it is tested, and who owns it?Join algorithms: nested loop, hash and merge
Describe nested loop, hash and merge joins. For each, give the case where the planner is likely to pick it.A hash join in PostgreSQL shows Batches: 64 and the query writes large temp files. Explain what that means and how work_mem and hash_mem_multiplier affect it.EXPLAIN ANALYZE shows a Nested Loop with rows=1 estimated on the outer side but actual rows=480000, and the query takes 90 seconds. What is the root cause and what can you do?A query that joins a 2 billion row fact table with a 100 million row table runs well on PostgreSQL in one region but badly on a sharded setup. What does distribution change about join strategies?MySQL lacked hash joins until 8.0.18, and optimizer capabilities still differ widely between PostgreSQL, MySQL, Oracle and SQL Server. When your company chooses which relational databases to standardise on for the next decade, how much weight should optimizer and join capabilities get against operations, skills and cost?Joins vs subqueries performance
Is a JOIN always faster than a subquery? Explain how modern optimizers treat IN, EXISTS and joins, and how you would decide in practice.In a code review, a developer replaces EXISTS with a JOIN plus DISTINCT for 'performance'. The query is used on a 40 million row table. What do you check before approving?Database performance folklore (avoid subqueries, avoid joins, always denormalise) spreads through your engineering organisation and drives poor designs. How would you replace folklore with evidence at company scale?No question matches these choices.