Advanced SQL
32 questions in 10 subtopics.
Common table expressions
Rewrite this nested query as a query with CTEs and explain what you gained: SELECT * FROM (SELECT customer_id,SUM(total) s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id) t JOIN customers c ON c.id = t.customer_id WHERE t.s > (SELECT AVG(s) FROM (SELECT SUM(total) s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id) x).A report query got 50 times slower after someone split it into CTEs on PostgreSQL 11, and got fast again after upgrading to PostgreSQL 16. Explain why, and when a materialized CTE is still the right choice.Using a data-modifying CTE in PostgreSQL, move all orders older than two years from orders to orders_archive in one statement, and explain the consistency guarantees and limits.Some teams write 400-line SQL reports with dozens of CTEs that nobody else understands, while others ban raw SQL in favour of JPA. As a principal engineer, how would you set guidance for when advanced SQL is the right tool in Java services?Recursive CTEs
Tableemployees(id, name, manager_id). Write a recursive CTE that returns every employee under manager 42 with their depth, and protect it against cycles in bad data.Write a recursive CTE that generates every date between two dates in MySQL 8.4, and use it to show daily signups including days with zero signups.A product category tree with 200,000 nodes is read on every page and updated a few times a day. Compare adjacency list with recursive CTEs, materialized path (ltree), nested sets and a closure table for this use.Graph-shaped data (org charts, supply chains, permissions, fraud rings) keeps appearing in your relational systems, and some teams want a graph database. As the senior technical leader, how do you decide between recursive SQL, SQL/PGQ graph queries and a separate graph database?Ranking window functions
What is the difference between a window function and GROUP BY? Show a query that lists each order with its customer's total spend and the order's share of that total.Return the top 3 highest-paid employees per department fromemployees(id, dept_id, salary), and explain how ROW_NUMBER, RANK and DENSE_RANK differ when two people have the same salary.A deduplication job keeps the latest row per customer_email from a 400 million row staging table using ROW_NUMBER() OVER (PARTITION BY customer_email ORDER BY updated_at DESC) and deleting rows with rn > 1. It runs out of temp space. What do you change?A leaderboard for 30 million players uses RANK() OVER (ORDER BY score DESC) on every request and the database CPU is at 90 percent. How would you redesign it?Aggregate window functions and frames
Fromdaily_sales(day date, amount numeric), compute a running total for the year and a 7-day moving average. Explain what frame each uses by default and why you would spell it out.LAST_VALUE(price) OVER (PARTITION BY product_id ORDER BY changed_at) returns the current row's price instead of the latest price. Explain and give two fixes.Finance asks for account balances at any point in time from a ledger of 5 billion entries. A query with SUM(amount) OVER (PARTITION BY account ORDER BY posted_at) works on small accounts but not at scale. How would you design this?Analytics workloads moved from OLTP databases to warehouses, then to lakehouses with SQL engines on object storage. As the senior technical leader, what does that history tell you about where window-heavy analytical SQL should run in your company, and how do you avoid fragmented logic across systems?LAG and LEAD
Fromlogins(user_id, login_at), find users who logged in on at least 3 consecutive days using LAG or a related technique.An IoT table readings(device_id, ts, value) has 10 billion rows. Product wants alerts when a value changes by more than 20 percent from the previous reading, and a report of how long each device stayed in each state. How would you use LAG and LEAD here, and what would you run in SQL versus in a stream processor?LATERAL joins
Return each customer with their three most recent orders using a LATERAL join in PostgreSQL, and explain why a plain join with LIMIT cannot do this.When is a LATERAL top-N query faster than aROW_NUMBER window query, and when is it slower? Reason about plan shapes and data distribution.Your company is deciding whether to standardise data access in Java services on JPA only, on jOOQ or plain SQL with JdbcClient, or to allow both. Over ten years, what are the costs and risks of each choice?Pivoting and unpivoting
Fromsales(region, quarter, amount) with quarter values Q1 to Q4, produce one row per region with columns q1 to q4. Write it portably, then mention engine-specific options.A legacy table metrics(day, cpu_avg, mem_avg, disk_avg) must be turned into rows (day, metric, value) for a new charting service. Write the unpivot in PostgreSQL and explain the performance of each approach.JSON in SQL
Tableevents(id, payload jsonb). Write PostgreSQL queries to find events where payload->'user'->>'country' = 'DE', and to extract the items array into rows. What index supports the first query?A team stores most order attributes in a single jsonb column to avoid migrations. A year later, reports are slow, data has inconsistent keys, and a field rename broke billing. How would you review this design and what would you change?Your company runs both PostgreSQL and MySQL 8.4 and teams want to store JSON in both. Compare JSON support relevant to performance and correctness, and set guidance.Relational databases have added JSON, full-text search and vector search, and some argue one PostgreSQL can replace document stores, search engines and vector databases. How would you set a long-term data platform strategy around this claim?Full-text search in SQL
Implement product search on name and description in PostgreSQL that handles word stems, ranks results and is fast on 5 million rows. Show the column, index and query.Search in your Spring Boot shop uses MySQL FULLTEXT indexes. Product wants typo tolerance, synonyms, facets and per-language stemming. When would you stay in the database and when would you move to Elasticsearch or OpenSearch?Grouping sets, ROLLUP and CUBE
What is the difference between ROLLUP and CUBE? For GROUP BY CUBE (a, b, c), how many grouping combinations are produced, and why can that be expensive?Write one query oversales(region, product, amount) that returns totals per region and product, per region, and a grand total. Then explain how to tell subtotal rows from rows where product is genuinely NULL.BI teams run ROLLUP and CUBE reports directly on the production PostgreSQL primary and slow down checkout. Design a reporting architecture that keeps SQL for analysts but protects OLTP.No question matches these choices.