SQL fundamentals
37 questions in 12 subtopics.
SELECT, filtering and sorting
Table orders(id bigint, customer_id bigint, status text, totalnumeric(12,2), created_at timestamptz). Write a query that returns the 20 most recent orders over 100.00 with status PAID or SHIPPED placed in the last 30 days, newest first, and explain why your result is stable between runs.A developer writes WHERE status = 'PAID' OR status = 'SHIPPED' AND total > 100 and is surprised that small PAID orders appear. Explain the bug and fix it.An admin search screen builds WHERE clauses from up to 12 optional filters and sorts by any column the user clicks. Queries are fast for some combinations and take 30 seconds for others on a 200 million row table. How do you approach this as the service owner?Product wants an export of any filtered list in the admin UI, which today can request 50 million rows. Design how the backend runs these queries without hurting OLTP traffic.NULL and three-valued logic
Explain three-valued logic in SQL. What do NULL = NULL, NULL <> 1, and NOT (NULL = 1) evaluate to, and how does WHERE treat each result?This query returns no rows even though many customers have never ordered: SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders). What is wrong and how do you fix it?A team models 'unknown', 'not applicable' and 'not yet entered' all as NULL in a customer table with 40 nullable columns, and reports keep disagreeing. How would you review and improve this schema?Tony Hoare called the null reference a billion-dollar mistake, and SQL NULL has its own long history of confusion. How would you set long-term policy for nulls across data models, APIs and Java code in a large company?Aggregation, GROUP BY and HAVING
Usingorders(customer_id, status, total, created_at), write one query that returns, per customer, the number of orders, the number of cancelled orders and the total spent on non-cancelled orders in 2025, only for customers who spent more than 1000.MySQL 8.4 rejects SELECT customer_id, email, COUNT(*) FROM orders JOIN customers USING (customer_id) GROUP BY customer_id with an ONLY_FULL_GROUP_BY error, but an old MySQL 5.6 server accepted it. Explain why and what correct options exist.A dashboard query aggregates 300 million order_items rows per day and region every time the page loads, taking 40 seconds. What options do you consider and how do you choose?DDL and data types
Choose column types for a payments table in PostgreSQL: amount, currency, created time, external reference, status. Explain why you avoid float for money and timestamp without time zone for events.You must change anorders.id column from int to bigint because it will overflow in about four months. The table has 1.5 billion rows and takes heavy writes. How do you do it without a long outage?Across 50 services, column types for the same concepts differ: amounts as float, numeric and varchar; times as timestamp and timestamptz; ids as int and uuid. How would you set and enforce data type standards without stalling teams?SQL has been declared obsolete several times: by object databases, XML databases, NoSQL and now by LLM-generated queries. As a senior technical leader, why has SQL lasted, and what does that mean for how you invest in skills and tooling over the next ten years?INSERT, UPDATE, DELETE and MERGE
Write a single UPDATE that setsproducts.price from a staging table price_updates(product_id, new_price) for only those rows, in PostgreSQL and in MySQL, and return the changed ids where possible.Explain the SQL MERGE statement as supported in PostgreSQL 15 and later. How does it differ from INSERT ... ON CONFLICT, and when would you prefer each?A nightly job runs DELETE FROM events WHERE created_at < now() - interval '90 days' on a 2 billion row PostgreSQL table. It runs for hours, replicas fall behind and the table never shrinks on disk. What is happening and what would you change?Regulators and customers increasingly demand that you can prove who changed data and that deleted personal data is really gone. How do you balance audit history, soft deletes and hard deletes across a company's databases?Upsert
Write an idempotent upsert forpage_views(page_id, day, views) that adds 1 to views or inserts a new row with 1, in PostgreSQL and MySQL 8.4. What must exist for it to work?A Spring service upserts with INSERT ... ON CONFLICT DO NOTHING and then SELECTs the row to get its id. Under load some requests get no row back from the SELECT, and the sequence has big gaps. Explain both effects and a better pattern.Several teams sync reference data from external systems into PostgreSQL with hand-written upserts, and incidents keep happening: lost updates from out-of-order messages, deadlocks, and rows that should have been deleted. What shared approach would you propose?Your company is choosing between letting services write directly to shared reference tables with upserts and having one owning service publish reference data as events. What are the long-term trade-offs and what would you decide?Set operations UNION, INTERSECT and EXCEPT
What is the difference between UNION and UNION ALL, and what do INTERSECT and EXCEPT return? Give an example where using UNION instead of UNION ALL is a bug.You migrated customers from a legacy tableold_customers(email, name) to customers(email, name). Write queries to find rows missing in the new table, extra rows, and rows whose name differs, and say how you would run this on 80 million rows.CASE expressions
Write a query overcustomers(id, created_at, last_order_at) that labels each customer as 'new' (created in the last 30 days), 'active' (ordered in the last 90 days), 'lapsed' (ordered before that) or 'never ordered', and counts customers per label.A query uses ORDER BY CASE WHEN :sort = 'name' THEN name WHEN :sort = 'created' THEN created_at END and fails with a type error in PostgreSQL, and in MySQL it sorts dates as text. Explain and fix.Logical query processing order
In what logical order does SQL evaluate FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT? Use it to explain why WHERE cannot reference a SELECT alias but ORDER BY can.A LEFT JOIN from customers to orders with WHERE o.created_at >= '2025-01-01' returns only customers with recent orders, not all customers. Explain using logical processing order and fix it.Your engineering organisation has many Java developers who mostly use JPA and rarely write SQL, and production incidents often trace back to misunderstood SQL semantics. How would you raise SQL competence across 30 teams?DISTINCT and its cost
A query joining customers to orders returned duplicate customers, so a developer added SELECT DISTINCT. It now takes 8 seconds. What is the real problem and how would you rewrite it?How do databases execute DISTINCT andCOUNT(DISTINCT col) internally, and why is COUNT(DISTINCT user_id) over a billion rows slow and memory hungry? What alternatives exist?TRUNCATE vs DELETE vs DROP
Compare TRUNCATE, DELETE without WHERE, and DROP TABLE: what each removes, locking, transactions, triggers, identity values and foreign keys, in PostgreSQL and MySQL.Integration tests reset the database between tests with TRUNCATE on 120 tables and the suite has become slow and occasionally deadlocks. What would you change?String, date and numeric functions
Write a query that reports monthly revenue for 2025 fromorders(total numeric, created_at timestamptz) in the Europe/Berlin time zone, with months that have no orders shown as 0.This query is slow and also misses rows: WHERE LOWER(email) = LOWER(?) AND DATE(created_at) = '2025-06-01' AND ROUND(amount) = 10. Explain each problem.Your company serves customers in 40 countries. Reports, invoices and searches differ because of time zones, collations, decimal rounding and case rules spread across Java code and SQL. What platform-level conventions would you set?No question matches these choices.