Developer Guides, Cheat Sheets & Tools

SQL course - Part 15: PUTTING IT ALL TOGETHER

Part index Prerequisites Previous Full course

🏁 PART 15 — PUTTING IT ALL TOGETHER


66. Anti-patterns, cheat sheets, exercises, and the capstone

[!NOTE] No 🧭 In practice block in this chapter, and that is deliberate. Chapters 1–65 each teach a technique, so “how / when / where / when not / best practices” applies to each of them. This chapter is not a technique — it is an anti-pattern list, two cheat sheets, a question bank, 40 exercises, a capstone brief, a study plan, a glossary, and a checklist. Each section says in its own opening how to use it. The one piece of guidance that would apply to all of them: attempt the exercises before reading the solutions in §66.4b, because reading a solution produces a feeling of competence that writing one produces for real.

🎚️ Level ⏱️ Time 🎯 After this chapter you can…
🟢🟡🔴 All levels Keep as a reference Spot the 32 classic mistakes · Translate any task between MSSQL and MySQL · Practise with 40 exercises · Build a complete project · Look up any term

[!NOTE] 📌 In plain words: The finish line. This chapter gathers everything into things you can keep beside you: the mistakes to avoid, a one-page MSSQL-vs-MySQL cheat sheet, interview questions, practice exercises, a full project to build, a 35-day plan, and a glossary of every term in the guide.


66.1 🚫 The 32 SQL anti-patterns

[!NOTE] 📌 Each one below is a mistake you will meet in real codebases — often in your own. Learn to spot them on sight.

🔴 Design anti-patterns
# Anti-pattern Why it hurts Do this instead
1 Comma-separated values in a column ('1,5,12') Cannot join, index, or constrain it A bridge table (Chapter 53)
2 column1, column2, column3 repeating groups Breaks the day someone needs a fourth One row per value
3 No primary key No reliable way to identify or update a row Always define one
4 A wide or changing primary key (email as PK) Duplicated in every index; breaks when it changes Surrogate INT PK + UNIQUE on the natural key
5 FLOAT for money Silent rounding errors that compound DECIMAL(10,2)
6 EAV (entity-attribute-value) for everything Every query becomes a self-join nightmare Real columns; JSON for rarely used details
7 No foreign keys (“the app handles it”) The app always has a bug eventually Declare the constraints
8 Storing computable values without a plan They drift out of sync silently Compute on read, or denormalize with verification (Chapter 52)
9 Mixed date formats / local times Unrecoverable ambiguity Store UTC, ISO format
10 Inconsistent naming (custID, customer_id, CustomerId) Every query needs a lookup One convention, documented
🔴 Query anti-patterns
# Anti-pattern Why it hurts Do this instead
11 SELECT * in production code Breaks covering indexes, moves useless data, breaks on schema change Name your columns
12 Functions on indexed columns (YEAR(date) = 2026) Stops the index being used SARGable ranges (Chapter 48)
13 Leading wildcard LIKE '%x%' Always a full scan Full-text index, or restructure
14 NOT IN with a nullable subquery Silently returns zero rows NOT EXISTS
15 DISTINCT to hide a bad join Masks the bug and adds a sort Fix the join
16 Implicit type conversion (WHERE phone = 947755501) Converts the whole column, no index Match the types
17 Old comma joins (FROM a, b WHERE ...) One forgotten condition = every row paired with every row (a cartesian product) Explicit JOIN ... ON
18 Filtering a LEFT JOIN in WHERE Silently becomes an INNER JOIN Put the condition in ON
19 Aggregating two one-to-many joins together Fan-out multiplies your totals Total each side first, then join
20 Cursors for data transformation 100x slower than a set-based statement Think in sets (Chapter 59)
🔴 Operational anti-patterns
# Anti-pattern Why it hurts Do this instead
21 UPDATE/DELETE with no WHERE Instant, irreversible mass damage SELECT first; transaction; safe-update mode
22 String concatenation into SQL SQL injection Parameterize (Chapter 55)
23 The app connects as sa/root One bug becomes total compromise Least privilege
24 Backups never tested You discover they are broken during the disaster Monthly restore drills
25 Indexing everything “just in case” Every write pays for every index Index for measured queries; audit for unused ones
26 Read-modify-write from the application Silent lost updates; no error is ever raised One guarded UPDATE, or a version column (Chapter 63)
27 Retrying a non-idempotent operation Double charges, duplicate orders A client-supplied idempotency key + UNIQUE (Chapter 63)
28 N+1 queries from an ORM 500 round trips where one join would do Eager-load, or project what you need (Chapter 65)
29 Schema changed by hand in production Environments diverge; nothing is reviewable or repeatable Versioned migrations in Git (Chapter 64)
30 A breaking migration deployed in one step Old app servers error during every rollout Expand–contract (Chapter 64)
31 VARCHAR + a legacy code page for user text Non-Latin characters become ??, silently and permanently NVARCHAR / _UTF8 🟥 · utf8mb4 🟦 (Chapter 60)
32 A local timestamp with no zone recorded Ambiguous twice a year and unfixable afterwards Store UTC; convert at the edge (Chapter 61)

66.2 📋 MSSQL vs MySQL — the complete cheat sheet

Basics
Task 🟥 MSSQL 🟦 MySQL
Limit rows SELECT TOP 10 ... ... LIMIT 10
Page results OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY LIMIT 10 OFFSET 20
String concat 'a' + 'b' or CONCAT() CONCAT() only
Quote identifiers [table name] `table name`
Current date/time GETDATE(), SYSDATETIME() NOW(), CURRENT_TIMESTAMP
Today’s date CAST(GETDATE() AS DATE) CURDATE()
Auto number IDENTITY(1,1) AUTO_INCREMENT
Last inserted ID SCOPE_IDENTITY() LAST_INSERT_ID()
Rows affected @@ROWCOUNT ROW_COUNT()
NULL replacement ISNULL(x, y) IFNULL(x, y)
Portable NULL replacement COALESCE(x, y) COALESCE(x, y)
Conditional shorthand IIF(c, a, b) IF(c, a, b)
String length LEN(s) CHAR_LENGTH(s)
Substring position CHARINDEX(find, text) LOCATE(find, text)
Left pad RIGHT(REPLICATE('0',n)+s, n) LPAD(s, n, '0')
Aggregate strings STRING_AGG(x, ',') GROUP_CONCAT(x)
Split a string STRING_SPLIT(s, ',') SUBSTRING_INDEX(s, ',', n)
Random order ORDER BY NEWID() ORDER BY RAND()
Cast CAST(x AS VARCHAR(10)) CAST(x AS CHAR)
Safe cast TRY_CAST(x AS INT) (none — filter with REGEXP)
Format a date FORMAT(d, 'yyyy-MM-dd') DATE_FORMAT(d, '%Y-%m-%d')
Add days DATEADD(DAY, 7, d) d + INTERVAL 7 DAY
Date difference DATEDIFF(DAY, start, end) DATEDIFF(end, start)
Last day of month EOMONTH(d) LAST_DAY(d)
Current UTC time SYSUTCDATETIME() UTC_TIMESTAMP()
Convert time zone dt AT TIME ZONE 'UTC' AT TIME ZONE 'tz' CONVERT_TZ(dt,'UTC','tz')
Force a collation col COLLATE Latin1_General_CS_AS col COLLATE utf8mb4_0900_as_cs
Unicode text NVARCHAR, or VARCHAR + a _UTF8 collation VARCHAR under utf8mb4
Median PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) OVER () (none — use ROW_NUMBER)
Named window WINDOW w AS (...) (2022+) WINDOW w AS (...) (8.0+)
Structure and objects
Task 🟥 MSSQL 🟦 MySQL
Show databases SELECT name FROM sys.databases SHOW DATABASES
Show tables SELECT * FROM sys.tables SHOW TABLES
Describe a table sp_help 'orders' DESCRIBE orders
Show the DDL sp_helptext / script it in SSMS SHOW CREATE TABLE orders
Show indexes SELECT * FROM sys.indexes SHOW INDEX FROM orders
Modify a column ALTER TABLE t ALTER COLUMN c TYPE ALTER TABLE t MODIFY COLUMN c TYPE
Rename a column EXEC sp_rename 't.c', 'new', 'COLUMN' ALTER TABLE t RENAME COLUMN c TO new
Create or replace a view CREATE OR ALTER VIEW CREATE OR REPLACE VIEW
Temp table CREATE TABLE #t (...) CREATE TEMPORARY TABLE t (...)
Table variable DECLARE @t TABLE (...) (none)
Sequence CREATE SEQUENCE (imitate with a table)
Computed column AS (expr) PERSISTED AS (expr) STORED
Materialized view Indexed view (SCHEMABINDING) (none — use a table + job)
Full outer join FULL OUTER JOIN (imitate with UNION)
Top-N per group CROSS APPLY JOIN LATERAL ... ON TRUE
Pivot PIVOT operator (use CASE)
Upsert MERGE INSERT ... ON DUPLICATE KEY UPDATE
Row history Temporal tables (SYSTEM_VERSIONING = ON) (triggers, or SCD Type 2)
Row version token ROWVERSION column (an INT version column)
Idempotent DDL IF NOT EXISTS (SELECT 1 FROM sys.columns ...) Check information_schema, then PREPARE the DDL (there is no ADD COLUMN IF NOT EXISTS)
Procedural code
Task 🟥 MSSQL 🟦 MySQL
Delimiter change Not needed (GO separates batches) DELIMITER $$ ... $$ DELIMITER ;
Declare a variable DECLARE @x INT; DECLARE x INT; (routines only)
Session variable DECLARE @x INT; SET @x = 1; SET @x = 1;
Assign from a query SELECT @x = col FROM t SELECT col INTO x FROM t
If IF ... BEGIN ... END IF ... THEN ... END IF;
While WHILE ... BEGIN ... END WHILE ... DO ... END WHILE;
Call a procedure EXEC usp_name @p = 1 CALL usp_name(1)
Raise an error THROW 50001, 'msg', 1 SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='msg'
Catch errors BEGIN TRY ... BEGIN CATCH DECLARE EXIT HANDLER FOR SQLEXCEPTION
Dynamic SQL EXEC sp_executesql @sql, @params, ... PREPARE stmt FROM @sql; EXECUTE stmt USING @p;
Administration
Task 🟥 MSSQL 🟦 MySQL
Execution plan SET SHOWPLAN_ALL ON / Ctrl+M EXPLAIN / EXPLAIN ANALYZE
I/O statistics SET STATISTICS IO ON EXPLAIN ANALYZE / performance_schema
Update statistics UPDATE STATISTICS t ANALYZE TABLE t
Rebuild an index ALTER INDEX ... REBUILD OPTIMIZE TABLE t
Consistency check DBCC CHECKDB CHECK TABLE t
Running sessions sys.dm_exec_requests performance_schema.processlist
Kill a session KILL 57 KILL 57
Backup BACKUP DATABASE ... TO DISK mysqldump / XtraBackup
Restore RESTORE DATABASE ... FROM DISK mysql < dump.sql
Create a user CREATE LOGIN + CREATE USER CREATE USER 'u'@'host'
Grant GRANT SELECT ON t TO u GRANT SELECT ON db.t TO 'u'@'h'
Show permissions sys.database_permissions SHOW GRANTS FOR 'u'@'h'
Schedule a job SQL Server Agent Event Scheduler / cron
Query history / plan regression Query Store performance_schema + sys views
Lock a row for update WITH (UPDLOCK) FOR UPDATE
Skip locked rows WITH (READPAST) SKIP LOCKED (8.0+)
Named application lock sp_getapplock GET_LOCK()
Lock wait timeout SET LOCK_TIMEOUT 5000 innodb_lock_wait_timeout = 5
Change feed for ETL Change Tracking / CDC binlog (ROW format)

66.3 🧠 The interview question bank

🌱 Beginner — click to expand
  1. What is the difference between WHERE and HAVING?
  2. Explain INNER JOIN vs LEFT JOIN with an example.
  3. What is a primary key? How does it differ from a unique constraint?
  4. What does NULL mean, and why does = NULL never work?
  5. DELETE vs TRUNCATE vs DROP — give the full comparison.
  6. What is a foreign key and what does it protect against?
  7. Explain GROUP BY. What must appear in the SELECT list?
  8. What is the difference between UNION and UNION ALL?
  9. Why should you avoid SELECT * in application code?
  10. What does DISTINCT do, and why is it often a warning sign?
  11. Write a query to find the second-highest price in a table.
  12. Write a query to find duplicate emails.
  13. What is an index, in one sentence? What does it cost?
  14. What are the five families of SQL commands (DDL, DML, DQL, DCL, TCL)?
  15. Explain CHAR vs VARCHAR.
🚀 Intermediate — click to expand
  1. Explain the logical order of query execution and one bug it explains.
  2. What is a CTE? How does it differ from a temp table?
  3. Explain window functions. How do they differ from GROUP BY?
  4. ROW_NUMBER vs RANK vs DENSE_RANK — with tied values.
  5. How do you get the top N rows per group? Give two methods.
  6. What is a correlated subquery? When is it slow?
  7. Explain EXISTS vs IN vs a JOIN for existence checks.
  8. What is a self join? Give a real use case.
  9. What are the ACID properties? Explain each in one sentence.
  10. What is a deadlock and how do you prevent one?
  11. Explain the four isolation levels and what each prevents.
  12. What is normalization? Explain 1NF, 2NF, 3NF.
  13. When would you deliberately denormalize?
  14. What is a covering index?
  15. Explain clustered vs non-clustered indexes.
  16. Why does WHERE YEAR(date) = 2026 perform badly?
  17. What is a stored procedure? When would you use one?
  18. What is a trigger, and why are experienced engineers cautious about them?
  19. What is a view? Can you always update through one?
  20. How do you implement an upsert in each engine?
🏆 Advanced — click to expand
  1. What is SARGability? Give three non-SARGable patterns and their fixes.
  2. Explain parameter sniffing and three ways to address it.
  3. How does the optimizer choose a plan? What role do statistics play?
  4. Explain the three physical join algorithms and when each is chosen.
  5. What is the fan-out problem when joining two one-to-many children?
  6. When would you partition a table, and when would you not?
  7. Explain SCD Type 2 and why the fact table stores a surrogate key.
  8. Explain MVCC and how MySQL’s default isolation differs from MSSQL’s.
  9. What does READ_COMMITTED_SNAPSHOT change, and why does it matter?
  10. Why are MSSQL scalar UDFs a performance risk? What is the fix?
  11. Design a keyset pagination scheme and explain why it beats OFFSET.
  12. How would you find and safely delete duplicate rows in a 500M-row table?
  13. What is the difference between a logical and a physical backup?
  14. Explain RPO and RTO and how they drive a backup schedule.
  15. You are told “the database is slow.” Walk through your diagnostic process.
  16. What is a lost update, and why does raising the isolation level not fix it?
  17. Compare optimistic and pessimistic concurrency. When is each correct?
  18. What makes an operation idempotent, and why does every retryable API need it?
  19. Explain the N+1 problem and two ways to detect it in a running system.
  20. What is a collation? Give one bug caused by getting it wrong.
  21. Why is 🟦 MySQL’s utf8 charset a trap? What should you use?
  22. How do you store a timestamp so it is still unambiguous in ten years?
  23. Write a “one local day” filter that stays SARGable against a UTC column.
  24. What are temporal tables, and what do they not record?
  25. Explain expand–contract and why a one-step column rename causes an outage.
  26. What is Query Store for, and when would you force a plan?
  27. How would you delete 50 million rows from a live table?

[!TIP] 💡 For question 50, the expected answer: check whether it is all queries or one; look at wait statistics to find the resource under pressure; find the top queries by total elapsed time; get the plan for the worst one; look for scans, bad estimates, and lookups; check whether statistics are current and indexes exist; verify it is not blocking or a hardware limit. Measure, then change one thing, then measure again.


66.4 🏋️ 40 practice exercises on ShopDB

Level 1 — Basics (1-10)
  1. List all products, most expensive first.
  2. Find all customers in the UK or Germany.
  3. Show orders placed in March 2026 (use a SARGable range).
  4. Find products below their reorder level.
  5. List every distinct country customers come from.
  6. Show the 5 cheapest non-discontinued products.
  7. Find customers whose email is at example.com.
  8. Show orders that have not shipped.
  9. List products priced between 100 and 500.
  10. Count customers per loyalty tier.
Level 2 — Joins and aggregation (11-20)
  1. Show every order with its customer name and sales rep name.
  2. List each product with its category and supplier names.
  3. Find total revenue per category.
  4. Show the top 5 customers by lifetime spend.
  5. Find products that have never been ordered.
  6. Show every customer including those with zero orders (correctly displaying 0).
  7. Find orders with no captured payment.
  8. Show each employee with their manager’s name (include the CEO).
  9. Count orders per status, with each as a percentage of the total.
  10. Find categories with more than 3 products and an average price above 200.
Level 3 — Subqueries, CTEs, windows (21-30)
  1. Find products priced above their own category’s average.
  2. Show each customer’s most recent order.
  3. Find the top 2 best-selling products in each category.
  4. Build a running total of revenue by month.
  5. Show month-over-month revenue change as an amount and a percentage.
  6. Rank customers by spend within their country.
  7. Build the full org chart with indentation levels.
  8. Find gaps in the order_id sequence.
  9. Calculate each category’s share of total revenue, plus a cumulative percentage (Pareto).
  10. Find customers whose spend is above the overall customer average.
Level 4 — Advanced (31-40)
  1. Build a monthly revenue pivot with categories as columns.
  2. Generate every date in the first half of 2026 and show daily revenue with zeros for quiet days.
  3. Find the average number of days between each customer’s consecutive orders.
  4. Write a stored procedure that places an order atomically, checking stock.
  5. Write a trigger that logs every price change.
  6. Create an indexed view / summary table of category sales.
  7. Find every foreign key column in ShopDB that lacks an index.
  8. Write a safe dynamic search procedure with four optional filters.
  9. Implement SCD Type 2 on a customer dimension and simulate a city change.
  10. Identify the three slowest queries you have written in this guide and tune them.

66.4b 🔑 Solutions to exercises 1–30

⚠️ Try each one first. A solution you read produces a feeling of competence; a solution you wrote produces the real thing. If you are stuck, read only the 💡 hint line before the query.

How these were checked: every query below was executed against a freshly built ShopDB on SQL Server 2025 Express (17.0.4025.3), and the row counts and values shown are the real output. The MySQL variants are given where the syntax differs, but were not executed — see What was verified, and what was not.

Before you start: rebuild ShopDB (§4.3 → §4.5 → §4.6) so your data matches these answers. Earlier chapters add and drop columns, and a leftover change will shift the numbers.

Level 1 — Basics (1–10)

1. List all products, most expensive first.

-- ✅ Works in BOTH
SELECT product_name, unit_price
FROM products
ORDER BY unit_price DESC;

18 rows, starting WorkStation X17 | 2450.00, UltraBook Pro 14 | 1499.00, UltraBook Air 13 | 999.00.

💡 Note that Zenith Phone 12 Mini and VisionPanel 32 4K both cost 749.00. Their relative order is not defined — add a tie-breaker (ORDER BY unit_price DESC, product_name) whenever you need a stable, repeatable order. This matters far more than beginners expect; see §16.


2. Find all customers in the UK or Germany.

-- ✅ Works in BOTH
SELECT full_name, country
FROM customers
WHERE country IN ('UK', 'Germany')
ORDER BY country, full_name;
full_name country
Hannah Weiss Germany
John Baker UK

💡 IN is shorthand for country = 'UK' OR country = 'Germany'. Only two rows — that is correct for this data, not a mistake in your query.


3. Show orders placed in March 2026 (SARGable).

-- ✅ Works in BOTH
SELECT order_id, order_date
FROM orders
WHERE order_date >= '2026-03-01'
  AND order_date <  '2026-04-01'
ORDER BY order_date;
order_id order_date
1007 2026-03-03
1008 2026-03-12
1009 2026-03-21

💡 This is the point of the exercise. WHERE MONTH(order_date) = 3 returns the same rows and cannot directly seek a normal index on order_date for the month condition, because wrapping the column in a function makes the predicate non-SARGable (§48). The half-open range >= start AND < next_start is the SARGable form, and using < for the upper bound means you never have to think about whether the month has 28, 30, or 31 days — or about time components hiding at 23:59:59.997.


4. Find products below their reorder level.

-- ✅ Works in BOTH
SELECT product_name, units_in_stock, reorder_level
FROM products
WHERE units_in_stock < reorder_level
ORDER BY product_name;
product_name units_in_stock reorder_level
ArchiveDrive 8TB 4 10
Legacy Netbook 10 0 5
Stream Cam 4K 9 10

💡 You can compare two columns, not just a column with a literal. That is what makes this a business rule rather than a hard-coded threshold.


5. List every distinct country customers come from.

-- ✅ Works in BOTH
SELECT DISTINCT country FROM customers ORDER BY country;

12 rows: Czechia, Denmark, Germany, India, Italy, Japan, Nigeria, Singapore, Spain, Sri Lanka, UAE, UK.

💡 Twelve customers, twelve countries — one each. Keep that in mind for exercise 26, where it makes every customer rank 1 in their own country.


6. Show the 5 cheapest non-discontinued products.

-- 🟥 MSSQL
SELECT TOP (5) product_name, unit_price
FROM products
WHERE discontinued = 0
ORDER BY unit_price ASC, product_name;
-- 🟦 MySQL
SELECT product_name, unit_price
FROM products
WHERE discontinued = 0
ORDER BY unit_price ASC, product_name
LIMIT 5;
product_name unit_price
Silent Mouse Pro 45.00
PodMic USB 99.00
NanoSSD 1TB 109.00
MechKey RGB Keyboard 129.00
Stream Cam 4K 159.00

💡 TOP/LIMIT without ORDER BY returns an arbitrary five rows — the engine is free to give you any five. “Cheapest” only means something once you have said how to sort.


7. Find customers whose email is at example.com.

-- ✅ Works in BOTH
SELECT full_name, email
FROM customers
WHERE email LIKE '%@example.com'
ORDER BY full_name;

All 12 customers — every seeded address uses that domain.

⚠️ A leading % makes this non-SARGable: the engine cannot seek, so it scans every row. Fine on 12 rows, and a real problem on 12 million. If you genuinely need to search by domain at scale, store the domain in its own column and index it. See §48.


8. Show orders that have not shipped.

-- ✅ Works in BOTH
SELECT order_id, order_date, status
FROM orders
WHERE ship_date IS NULL
ORDER BY order_id;
order_id order_date status
1004 2026-02-09 Cancelled
1009 2026-03-21 Paid
1013 2026-05-06 Pending
1017 2026-06-15 Refunded
1020 2026-07-19 Paid
1022 2026-08-14 Pending

⚠️ IS NULL, never = NULL. ship_date = NULL returns zero rows and no error, because comparing anything to NULL yields unknown, not true (§15). This is the most common silent bug in beginner SQL.

💡 Note the result mixes genuinely-unshipped orders with Cancelled and Refunded ones. A business question is rarely answered by one column — you would usually add AND status NOT IN ('Cancelled','Refunded').


9. List products priced between 100 and 500.

-- ✅ Works in BOTH
SELECT product_name, unit_price
FROM products
WHERE unit_price BETWEEN 100 AND 500
ORDER BY unit_price;

10 rows, from NanoSSD 1TB | 109.00 to VisionPanel 27 QHD | 399.00.

💡 BETWEEN is inclusive at both ends. That is safe here, and dangerous with dates and times: BETWEEN '2026-03-01' AND '2026-03-31' silently excludes anything at 2026-03-31 00:00:01. Use the half-open range from exercise 3 for anything with a time component.


10. Count customers per loyalty tier.

-- ✅ Works in BOTH
SELECT loyalty_tier, COUNT(*) AS customers
FROM customers
GROUP BY loyalty_tier
ORDER BY customers DESC, loyalty_tier;
loyalty_tier customers
Bronze 5
Gold 3
Silver 3
Platinum 1

💡 COUNT(*) counts rows; COUNT(column) counts non-NULL values of that column. They differ the moment nulls appear, and the difference is a common source of wrong totals (§25).

Level 2 — Joins and aggregation (11–20)

11. Every order with its customer name and sales rep name.

-- 🟥 MSSQL (MySQL concatenation variant explained below)
SELECT o.order_id,
       c.full_name AS customer,
       COALESCE(e.first_name + ' ' + e.last_name, '(none)') AS sales_rep
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id
LEFT  JOIN employees AS e ON e.employee_id = o.employee_id
ORDER BY o.order_id;

23 rows, beginning 1000 | Amara Silva | Priya Raman.

💡 Why INNER for the customer and LEFT for the employee. orders.customer_id is NOT NULL, so every order has a customer — an inner join loses nothing. orders.employee_id is nullable (a web order has no sales rep), so an inner join there would silently drop those orders. Match the join type to the column’s nullability, every time.

🟦 MySQL: + does not concatenate strings. Use CONCAT_WS(' ', e.first_name, e.last_name), and IFNULL(...) in place of COALESCE(...) if you prefer (both work in MySQL).


12. Each product with its category and supplier names.

-- ✅ Works in BOTH
SELECT p.product_name,
       c.category_name,
       COALESCE(s.company_name, '(none)') AS supplier
FROM products AS p
INNER JOIN categories AS c ON c.category_id = p.category_id
LEFT  JOIN suppliers  AS s ON s.supplier_id = p.supplier_id
ORDER BY p.product_name;
product_name category_name supplier
ArchiveDrive 8TB Storage Baltic Components
Budget Phone A3 Smartphones Lanka Distributors
Concert Over-Ear Audio EuroSound GmbH
… … …

💡 Same rule as exercise 11: products.category_id is NOT NULL (inner), products.supplier_id is nullable (left).


13. Total revenue per category.

-- ✅ Works in BOTH
SELECT c.category_name,
       CAST(SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS DECIMAL(12,2)) AS revenue
FROM order_items AS oi
JOIN products   AS p ON p.product_id  = oi.product_id
JOIN categories AS c ON c.category_id = p.category_id
GROUP BY c.category_name
ORDER BY revenue DESC;
category_name revenue
Laptops 13223.35
Smartphones 5874.55
Monitors 3719.10
Audio 2053.85
Storage 1311.00
Peripherals 1200.00

⚠️ Use order_items.unit_price, not products.unit_price. The order line records the price at the time of sale; the product table holds today’s price. Joining to products for the price would silently restate history every time someone changes a price. This is exactly the deliberate duplication explained in §4.6 and §52.


14. Top 5 customers by lifetime spend.

-- 🟥 MSSQL (MySQL: drop TOP (5) and add LIMIT 5 at the end)
SELECT TOP (5)
       c.full_name,
       CAST(SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS DECIMAL(12,2)) AS lifetime_spend
FROM customers   AS c
JOIN orders      AS o  ON o.customer_id = c.customer_id
JOIN order_items AS oi ON oi.order_id   = o.order_id
GROUP BY c.customer_id, c.full_name
ORDER BY lifetime_spend DESC;
full_name lifetime_spend
Mei Chen 7976.45
John Baker 4040.15
Fatima Al-Sayed 3459.20
Grace Adeyemi 3388.00
Kenji Watanabe 2887.65

💡 Group by customer_id as well as full_name. Two customers could share a name; grouping by the key keeps them separate and tells the engine the name is functionally dependent on it.


15. Products that have never been ordered.

-- ✅ Works in BOTH
SELECT p.product_name
FROM products AS p
WHERE NOT EXISTS (
    SELECT 1 FROM order_items AS oi WHERE oi.product_id = p.product_id
)
ORDER BY p.product_name;

One row: Legacy Netbook 10.

⚠️ Prefer NOT EXISTS over NOT IN here. If the subquery column ever contains a NULL, NOT IN returns no rows at all — silently, with no error, because x NOT IN (1, NULL) evaluates to unknown rather than true. NOT EXISTS is immune. See §30.

💡 The LEFT JOIN … WHERE oi.product_id IS NULL anti-join is an equally valid third form.


16. Every customer, including those with zero orders, showing 0 correctly.

-- ✅ Works in BOTH
SELECT c.full_name, COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.full_name
ORDER BY order_count DESC, c.full_name;

12 rows, from Mei Chen | 4 down to several with 1. In this data every customer has ordered at least once, so no zero appears — but the query is still the correct one, and here is how to prove it to yourself:

-- ✅ Works in BOTH: add a customer with no orders, then re-run exercise 16
INSERT INTO customers (full_name, email, city, country, signup_date, loyalty_tier)
VALUES ('Test Nobody', 'nobody@example.com', 'Nowhere', 'UK', '2026-09-01', 'Bronze');

Re-run the query and Test Nobody | 0 appears at the bottom. Then remove it, or rebuild from §4.3–4.5.

⚠️ COUNT(o.order_id), never COUNT(*). With a LEFT JOIN, an unmatched customer still produces one row — with all the orders columns NULL. COUNT(*) counts that row and reports 1; COUNT(o.order_id) skips NULLs and correctly reports 0. This single character is the whole exercise.


17. Orders with no captured payment.

-- ✅ Works in BOTH
SELECT o.order_id, o.status
FROM orders AS o
WHERE NOT EXISTS (
    SELECT 1 FROM payments AS pay
    WHERE pay.order_id = o.order_id
      AND pay.status   = 'Captured'
)
ORDER BY o.order_id;
order_id status
1004 Cancelled
1013 Pending
1017 Refunded
1022 Pending

💡 The AND pay.status = 'Captured' belongs inside the subquery. Move it outside and you change the question from “has no captured payment” to something that also matches orders whose payment rows exist but failed — a different, and usually wrong, answer.


18. Every employee with their manager’s name, including the CEO.

-- 🟥 MSSQL; MySQL: use CONCAT(e.first_name, ' ', e.last_name)
-- and COALESCE(CONCAT(m.first_name, ' ', m.last_name), '(no manager)')
SELECT e.first_name + ' ' + e.last_name AS employee,
       COALESCE(m.first_name + ' ' + m.last_name, '(no manager)') AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;
employee manager
Sarah Mitchell (no manager)
David Okafor Sarah Mitchell
Priya Raman David Okafor
… …

💡 This is a self join: one table joined to itself under two aliases. The aliases are not optional styling — without them the engine cannot tell which first_name you mean. “Including the CEO” is the hint that it must be a LEFT join, since Sarah Mitchell.manager_id is NULL.


19. Orders per status, with each as a percentage of the total.

-- ✅ Works in BOTH (window functions: MSSQL 2012+, MySQL 8.0+)
SELECT status,
       COUNT(*) AS n,
       CAST(100.0 * COUNT(*) / SUM(COUNT(*)) OVER () AS DECIMAL(5,1)) AS pct
FROM orders
GROUP BY status
ORDER BY n DESC, status;
status n pct
Delivered 15 65.2
Paid 2 8.7
Pending 2 8.7
Shipped 2 8.7
Cancelled 1 4.3
Refunded 1 4.3

💡 SUM(COUNT(*)) OVER () looks impossible and is not. Aggregation runs first, producing one row per status; the window function then runs over those grouped rows, summing the six counts to 23. Understanding that ordering is what makes window functions click (§33).

⚠️ 100.0, not 100. With integer 100, 100 * 15 / 23 is integer division in SQL Server and yields 65 with the fraction discarded before the cast. One decimal point changes the whole expression to decimal arithmetic.


20. Categories with more than 3 products and an average price above 200.

-- ✅ Works in BOTH
SELECT c.category_name,
       COUNT(*) AS product_count,
       CAST(AVG(p.unit_price) AS DECIMAL(10,2)) AS avg_price
FROM products   AS p
JOIN categories AS c ON c.category_id = p.category_id
GROUP BY c.category_name
HAVING COUNT(*) > 3 AND AVG(p.unit_price) > 200
ORDER BY avg_price DESC;
category_name product_count avg_price
Laptops 4 1311.75

💡 HAVING, not WHERE. WHERE filters individual rows before grouping; HAVING filters the groups after. A condition on COUNT(*) or AVG(...) can only go in HAVING, because those values do not exist until the grouping has happened (§26).

Level 3 — Subqueries, CTEs, window functions (21–30)

21. Products priced above their own category’s average.

-- ✅ Works in BOTH
SELECT p.product_name, p.unit_price, c.category_name
FROM products   AS p
JOIN categories AS c ON c.category_id = p.category_id
WHERE p.unit_price > (
    SELECT AVG(p2.unit_price)
    FROM products AS p2
    WHERE p2.category_id = p.category_id     -- correlated to the outer row
)
ORDER BY c.category_name, p.unit_price DESC;

10 rows, including WorkStation X17 | 2450.00 | Laptops and Concert Over-Ear | 349.00 | Audio.

💡 This is a correlated subquery: it references p.category_id from the outer query, so it is conceptually re-evaluated per row. The window-function form is usually clearer and lets the engine do a windowed aggregate; compare plans before assuming it is faster:

-- ✅ Works in BOTH — same answer, physical plan depends on the engine
WITH priced AS (
    SELECT p.product_name, p.unit_price, c.category_name,
           AVG(p.unit_price) OVER (PARTITION BY p.category_id) AS cat_avg
    FROM products AS p
    JOIN categories AS c ON c.category_id = p.category_id
)
SELECT product_name, unit_price, category_name
FROM priced
WHERE unit_price > cat_avg
ORDER BY category_name, unit_price DESC;

Note the WHERE must live outside the CTE — you cannot filter on a window function in the same SELECT that computes it, because window functions are evaluated after WHERE.


22. Each customer’s most recent order.

-- ✅ Works in BOTH
WITH ranked AS (
    SELECT o.customer_id, o.order_id, o.order_date,
           ROW_NUMBER() OVER (PARTITION BY o.customer_id
                              ORDER BY o.order_date DESC, o.order_id DESC) AS rn
    FROM orders AS o
)
SELECT c.full_name, r.order_id, r.order_date
FROM ranked AS r
JOIN customers AS c ON c.customer_id = r.customer_id
WHERE r.rn = 1
ORDER BY c.full_name;

12 rows — one per customer — beginning Amara Silva | 1016 | 2026-06-04.

💡 The , o.order_id DESC tie-breaker matters. Two orders on the same date would otherwise make the “most recent” arbitrary and the result non-repeatable.

💡 ROW_NUMBER versus RANK: ROW_NUMBER always gives exactly one row per partition; RANK gives all tied rows the same number, so rn = 1 could return two orders. Choose by whether ties should produce one row or several.


23. Top 2 best-selling products in each category.

-- ✅ Works in BOTH
WITH sales AS (
    SELECT p.category_id, p.product_name, SUM(oi.quantity) AS units
    FROM order_items AS oi
    JOIN products AS p ON p.product_id = oi.product_id
    GROUP BY p.category_id, p.product_name
),
ranked AS (
    SELECT s.*,
           ROW_NUMBER() OVER (PARTITION BY s.category_id
                              ORDER BY s.units DESC, s.product_name) AS rn
    FROM sales AS s
)
SELECT c.category_name, r.product_name, r.units
FROM ranked AS r
JOIN categories AS c ON c.category_id = r.category_id
WHERE r.rn <= 2
ORDER BY c.category_name, r.rn;
category_name product_name units
Audio PodMic USB 4
Audio StudioBuds Wireless 4
Laptops UltraBook Pro 14 4
Laptops UltraBook Air 13 3
… … …

💡 Two stacked CTEs make the stages explicit: aggregate first, then rank. You can also rank aggregates in the same grouped query with ROW_NUMBER() OVER (... ORDER BY SUM(oi.quantity) DESC, p.product_name); aggregation precedes window evaluation.

💡 Audio has a genuine tie at 4 units, broken alphabetically by the , s.product_name clause. To keep ties together, replace the ranking expression with RANK() OVER (PARTITION BY s.category_id ORDER BY s.units DESC); remove s.product_name from the ranking order. A rank-2 tie can then return more than two rows.


24. Running total of revenue by month.

-- 🟥 MSSQL
WITH monthly AS (
    SELECT DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1) AS month_start,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount))      AS revenue
    FROM orders AS o
    JOIN order_items AS oi ON oi.order_id = o.order_id
    GROUP BY DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1)
)
SELECT month_start,
       CAST(revenue AS DECIMAL(12,2)) AS revenue,
       CAST(SUM(revenue) OVER (ORDER BY month_start
                               ROWS UNBOUNDED PRECEDING) AS DECIMAL(12,2)) AS running_total
FROM monthly
ORDER BY month_start;

🟦 MySQL: replace DATEFROMPARTS(YEAR(x), MONTH(x), 1) with DATE_FORMAT(o.order_date, '%Y-%m-01').

month_start revenue running_total
2026-01-01 6379.15 6379.15
2026-02-01 2597.20 8976.35
2026-03-01 4059.10 13035.45
2026-04-01 2492.50 15527.95
2026-05-01 3495.75 19023.70
2026-06-01 3291.00 22314.70
2026-07-01 3101.05 25415.75
2026-08-01 1966.10 27381.85

⚠️ Write ROWS UNBOUNDED PRECEDING explicitly. The default frame when you supply ORDER BY is RANGE UNBOUNDED PRECEDING, which groups all rows with an equal sort value into the same frame. Month starts are unique here so both give the same answer — but on a column with duplicates, RANGE silently produces a different running total. Making the frame explicit is a habit worth forming (§34).

💡 Grouping by the first day of the month rather than by a '2026-01' string keeps the values sortable as real dates and avoids a text sort that would put 2026-10 before 2026-2.


25. Month-over-month revenue change, amount and percentage.

-- 🟥 MSSQL (MySQL: as in exercise 24, swap DATEFROMPARTS for DATE_FORMAT)
WITH monthly AS (
    SELECT DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1) AS month_start,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount))      AS revenue
    FROM orders AS o
    JOIN order_items AS oi ON oi.order_id = o.order_id
    GROUP BY DATEFROMPARTS(YEAR(o.order_date), MONTH(o.order_date), 1)
)
SELECT month_start,
       CAST(revenue AS DECIMAL(12,2)) AS revenue,
       CAST(revenue - LAG(revenue) OVER (ORDER BY month_start) AS DECIMAL(12,2)) AS change_amount,
       CAST(100.0 * (revenue - LAG(revenue) OVER (ORDER BY month_start))
            / NULLIF(LAG(revenue) OVER (ORDER BY month_start), 0) AS DECIMAL(6,1)) AS change_pct
FROM monthly
ORDER BY month_start;
month_start revenue change_amount change_pct
2026-01-01 6379.15 NULL NULL
2026-02-01 2597.20 -3781.95 -59.3
2026-03-01 4059.10 1461.90 56.3
2026-04-01 2492.50 -1566.60 -38.6
2026-05-01 3495.75 1003.25 40.3
2026-06-01 3291.00 -204.75 -5.9
2026-07-01 3101.05 -189.95 -5.8
2026-08-01 1966.10 -1134.95 -36.6

💡 The first row is NULL, and that is right. January has no previous month, so LAG returns NULL and the arithmetic propagates it. Do not “fix” this with COALESCE(..., 0) — a 0% change is a claim that revenue was flat, which is false. NULL correctly says “unknown”.

⚠️ NULLIF(prev, 0) prevents a divide-by-zero. If a month ever had zero revenue, the percentage would otherwise raise Msg 8134. NULLIF turns the 0 into NULL, and NULL division yields NULL instead of an error.


26. Rank customers by spend within their country.

-- ✅ Works in BOTH
WITH spend AS (
    SELECT c.customer_id, c.full_name, c.country,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total
    FROM customers   AS c
    JOIN orders      AS o  ON o.customer_id = c.customer_id
    JOIN order_items AS oi ON oi.order_id   = o.order_id
    GROUP BY c.customer_id, c.full_name, c.country
)
SELECT country, full_name,
       CAST(total AS DECIMAL(12,2)) AS total,
       RANK() OVER (PARTITION BY country ORDER BY total DESC) AS rank_in_country
FROM spend
ORDER BY country, rank_in_country;

12 rows — and every one has rank_in_country = 1, because ShopDB happens to hold exactly one customer per country (exercise 5). The query is correct; the data simply gives it nothing to rank.

💡 Prove it works by adding a second UK customer with an order, or test the logic by partitioning on something with repeats instead — PARTITION BY c.loyalty_tier produces genuine rankings of 1, 2, 3 with this data. Verifying a query against data that cannot exercise it is a habit worth breaking early.


27. The full org chart with indentation levels.

-- 🟥 MSSQL (MySQL 8.0+: identical, but write WITH RECURSIVE org AS ...)
WITH org AS (
    -- Anchor: everyone with no manager
    SELECT employee_id, first_name, last_name, manager_id, 0 AS lvl
    FROM employees
    WHERE manager_id IS NULL

    UNION ALL

    -- Recursive step: everyone who reports to someone already found
    SELECT e.employee_id, e.first_name, e.last_name, e.manager_id, o.lvl + 1
    FROM employees AS e
    JOIN org AS o ON o.employee_id = e.manager_id
)
SELECT lvl,
       REPLICATE('    ', lvl) + first_name + ' ' + last_name AS org_chart
FROM org
ORDER BY lvl, org_chart;
lvl org_chart
0 Sarah Mitchell
1     Amara Nwosu
1     David Okafor
1     Elena Petrova
2         Marco Rossi
2         Priya Raman
2         Tom Becker
2         Yuki Sato

💡 This recursive CTE has two parts joined by UNION ALL: an anchor that does not reference the CTE, and a recursive member that does. More complex CTEs may have multiple anchor or recursive members. Get the anchor wrong and you get no rows; get the join direction wrong and you walk the tree upward instead of downward.

🟦 MySQL: REPLICATE is REPEAT, and + concatenation is CONCAT. MySQL also requires the RECURSIVE keyword, and caps depth at cte_max_recursion_depth (default 1000).

⚠️ A cycle in the data — A manages B, B manages A — loops forever. SQL Server stops at 100 levels by default (OPTION (MAXRECURSION n) changes it); MySQL uses the setting above. If your hierarchy comes from user input, assume a cycle will eventually appear.


28. Find gaps in the order_id sequence.

-- 🟥 MSSQL 2022+ (GENERATE_SERIES)
WITH bounds AS (SELECT MIN(order_id) AS lo, MAX(order_id) AS hi FROM orders)
SELECT n.value AS missing_order_id
FROM bounds AS b
CROSS APPLY GENERATE_SERIES(b.lo, b.hi) AS n
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.order_id = n.value)
ORDER BY n.value;

Result on a freshly built ShopDB: no rows. Order IDs run 1000–1022 with no gaps — so the honest answer to this exercise is “there are none”, and a query returning nothing is the correct result, not a failure.

Prove the query actually works by creating a gap and removing it again:

-- 🟥 MSSQL: make a gap, look for it, then undo everything
BEGIN TRANSACTION;

DELETE FROM payments    WHERE order_id = 1005;
DELETE FROM order_items WHERE order_id = 1005;   -- children first: FK order matters
DELETE FROM orders      WHERE order_id = 1005;

WITH bounds AS (SELECT MIN(order_id) AS lo, MAX(order_id) AS hi FROM orders)
SELECT n.value AS missing_order_id
FROM bounds AS b
CROSS APPLY GENERATE_SERIES(b.lo, b.hi) AS n
WHERE NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.order_id = n.value);
-- returns: 1005

ROLLBACK TRANSACTION;    -- 🔑 puts all three tables back

The ROLLBACK is what makes this safe to run on your practice database — see §42.

On SQL Server 2019/2022 without GENERATE_SERIES, generate the numbers from a system catalog:

-- 🟥 MSSQL 2016+ : no GENERATE_SERIES needed
WITH nums AS (
    SELECT TOP (100)
           ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1
           + (SELECT MIN(order_id) FROM orders) AS n
    FROM sys.all_objects
)
SELECT n AS missing_order_id
FROM nums
WHERE n <= (SELECT MAX(order_id) FROM orders)
  AND NOT EXISTS (SELECT 1 FROM orders AS o WHERE o.order_id = n)
ORDER BY n;

💡 A different, often better approach needs no number series at all — compare each row with the next using LEAD:

-- ✅ Works in BOTH (MSSQL 2012+, MySQL 8.0+)
WITH seq AS (
    SELECT order_id, LEAD(order_id) OVER (ORDER BY order_id) AS next_id
    FROM orders
)
SELECT order_id + 1 AS gap_starts, next_id - 1 AS gap_ends
FROM seq
WHERE next_id > order_id + 1
ORDER BY order_id;

This reads only the table itself and scales to any range, where the numbers approach must materialise every value between the bounds.

⚠️ Gaps in an IDENTITY/AUTO_INCREMENT column are normal and expected. A rolled-back transaction consumes its number permanently. Never treat such a column as a gapless counter — if you need one, see §41.


29. Each category’s share of revenue, plus a cumulative percentage (Pareto).

-- ✅ Works in BOTH
WITH cat AS (
    SELECT c.category_name,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS revenue
    FROM order_items AS oi
    JOIN products    AS p ON p.product_id  = oi.product_id
    JOIN categories  AS c ON c.category_id = p.category_id
    GROUP BY c.category_name
)
SELECT category_name,
       CAST(revenue AS DECIMAL(12,2))                              AS revenue,
       CAST(100.0 * revenue / SUM(revenue) OVER () AS DECIMAL(5,1)) AS pct_of_total,
       CAST(100.0 * SUM(revenue) OVER (ORDER BY revenue DESC ROWS UNBOUNDED PRECEDING)
            / SUM(revenue) OVER () AS DECIMAL(5,1))                 AS cumulative_pct
FROM cat
ORDER BY revenue DESC;
category_name revenue pct_of_total cumulative_pct
Laptops 13223.35 48.3 48.3
Smartphones 5874.55 21.5 69.7
Monitors 3719.10 13.6 83.3
Audio 2053.85 7.5 90.8
Storage 1311.00 4.8 95.6
Peripherals 1200.00 4.4 100.0

💡 Two different windows in one SELECT. SUM(revenue) OVER () — no ORDER BY, no frame — is the grand total on every row. SUM(revenue) OVER (ORDER BY revenue DESC ROWS UNBOUNDED PRECEDING) is the running total. Being able to read the difference between those two OVER clauses is the single most useful window-function skill.

💡 This is a Pareto chart: the top two categories account for 69.7% of revenue. That is the question a business actually asks, and it is one query away.


30. Customers whose spend is above the overall customer average.

-- ✅ Works in BOTH
WITH spend AS (
    SELECT c.customer_id, c.full_name,
           SUM(oi.unit_price * oi.quantity * (1 - oi.discount)) AS total
    FROM customers   AS c
    JOIN orders      AS o  ON o.customer_id = c.customer_id
    JOIN order_items AS oi ON oi.order_id   = o.order_id
    GROUP BY c.customer_id, c.full_name
)
SELECT full_name, CAST(total AS DECIMAL(12,2)) AS total
FROM spend
WHERE total > (SELECT AVG(total) FROM spend)
ORDER BY total DESC;
full_name total
Mei Chen 7976.45
John Baker 4040.15
Fatima Al-Sayed 3459.20
Grace Adeyemi 3388.00
Kenji Watanabe 2887.65
Amara Silva 2423.00

⚠️ “Average customer spend” is not AVG(oi.unit_price * …). You must aggregate per customer first, then average those totals. Averaging the line items directly gives the average line value, a completely different number. Naming the CTE spend and reusing it twice makes the intent unmistakable.

💡 A CTE can be referenced more than once in the same statement — here in the FROM and again in the subquery. Whether the engine evaluates it once or twice is its choice; if the cost matters, check the execution plan (§47).

Level 4 — Advanced (31–40)

These ten are build exercises rather than single queries: each asks you to design a procedure, a trigger, an index, or a dimension table, and there are several defensible answers to every one. Rather than a single “right” solution, use the chapter that covers each and the checklist in §66.9 to grade your own work.

# Task Read first The thing to get right
31 Monthly revenue pivot, categories as columns §35 MSSQL PIVOT needs a fixed column list; a dynamic one needs §59
32 Every date in H1 2026 with zeros for quiet days §31 A calendar table LEFT JOINed to sales — the zeros come from the join, not from the data
33 Average days between each customer’s orders §34 LAG(order_date) per customer, then average the differences; customers with one order yield NULL
34 Stored procedure placing an order atomically §37, §42 One transaction, stock checked and decremented inside it, TRY…CATCH with ROLLBACK
35 Trigger logging every price change §39 Triggers fire per statement, not per row — use inserted/deleted, never a scalar variable
36 Indexed view / summary table of category sales §36, §46 MSSQL indexed views need SCHEMABINDING and COUNT_BIG(*); MySQL has no equivalent — use a summary table
37 Foreign key columns lacking an index §46 Query the system catalog; an unindexed FK makes parent deletes scan the child table
38 Safe dynamic search with four optional filters §59, §55 Parameterise every value. sp_executesql with parameters, never string concatenation
39 SCD Type 2 on a customer dimension §53 valid_from / valid_to / is_current; a change closes the old row and inserts a new one
40 Tune your three slowest queries §47, §48 Measure before and after; a change you did not measure is not a tuning

🎓 The honest standard for Level 4: your answer is good if it survives being run twice, handles the empty case, and does not corrupt data when a concurrent session runs it at the same moment. That last one is what separates exercise SQL from production SQL.


66.5 🎓 The capstone project: build a complete system

[!IMPORTANT] 🎯 Goal: design, build, populate, query, secure, and tune a full database from scratch. This is the exercise that turns knowledge into skill.

📚 The brief: a Library Management System

A city library needs a database. The requirements:

  • The library holds titles (a book, identified by ISBN) and multiple physical copies of each.
  • Members join, have a membership tier, and can be suspended.
  • A member borrows a copy for 14 days and may renew twice.
  • Overdue items accrue a fine of 0.50 per day, capped at the item’s replacement cost.
  • Members can reserve a title that is fully out on loan, joining a queue.
  • Books have authors (a book may have several; an author writes several books) and belong to genres.
  • Staff process loans and returns; each has a role and a branch.
  • The library has multiple branches; copies belong to a branch and can be transferred.
  • Management needs reports: most-borrowed titles, overdue lists, member activity, branch comparison, fine revenue.
📋 Your deliverables
Phase Deliverable
1. Design An ER (entity-relationship) diagram; a 3NF logical model; every relationship identified (note the many-to-many ones)
2. Build CREATE TABLE scripts for both MSSQL and MySQL, with all constraints named by convention
3. Populate Seed data: 6 branches, 20 staff, 200 members, 300 titles, 800 copies, 2000 loans spanning 2 years
4. Query The 10 reports listed below
5. Objects 3 views, 3 stored procedures, 1 trigger, 2 functions
6. Integrity Transactions for borrow/return; correct handling of the reservation queue
7. Performance Index strategy with justification; plans before and after for 3 slow queries
8. Security Roles for member-facing app, librarian, manager, and reporting; least privilege applied
9. Operations Backup strategy meeting a 15-minute RPO; a written restore runbook
10. Analytics A star schema for loan analysis, loaded from the operational tables
📊 The 10 required reports
  1. Titles currently on loan, with borrower and due date.
  2. Overdue loans with the fine accrued to date.
  3. Top 20 most-borrowed titles in the last 12 months.
  4. Members who have never borrowed anything.
  5. Branch comparison: loans, unique members, average loan duration.
  6. Monthly loan volume with a 3-month moving average.
  7. The reservation queue per title, in position order.
  8. Members with outstanding fines above 10.00.
  9. Author popularity: total loans across all their titles.
  10. Copies not borrowed in over 2 years (candidates for withdrawal).
🎯 The self-assessment

You have genuinely completed this project when you can:

  • ☑️ Explain every design decision, including the ones you rejected
  • ☑️ Show that no business rule can be broken by raw SQL, not just by the app
  • ☑️ Point at each index and name the query it serves
  • ☑️ Restore the database to a point in time from your own runbook
  • ☑️ Hand the schema to another developer who can use it without asking you questions

66.6 📅 Your 35-day learning plan

Days Focus Chapters Daily goal
1 Setup and orientation 1–4 Both engines installed; ShopDB built and verified
2–3 Query fundamentals 5, 13, 14 Write 20 SELECTs from memory
4 NULL and sorting 15, 16, 17 Understand three-valued logic (TRUE, FALSE, UNKNOWN) completely
5–6 Data types and tables 6, 7, 8 Design and build a 5-table schema of your own
7 Constraints 9, 10, 11 Every constraint type used and deliberately broken
8–9 Writing data 12, 18, 19 Insert, update, delete safely inside transactions
10–11 Functions 20, 21, 22, 23 Build a data-cleaning query and a date report
12 Conditional logic 24 Master conditional aggregation
13–14 Aggregation 25, 26, 27 Answer 10 real business questions
15–17 🔥 Joins 28, 29 All join types; deliberately hit and fix every trap
18–19 Subqueries and CTEs 30, 31, 32 Write a recursive org chart from scratch
20–22 🔥 Window functions 33, 34, 35 Top-N per group, running totals, LAG/LEAD, pivots
23 Views and procedures 36, 37 Build a view layer and 3 procedures
24 Functions and triggers 38, 39, 40, 41 Build an audit trail
25 Transactions 42, 43, 44, 45 Reproduce a deadlock; write retry logic
26–27 🔥 Performance 46, 47, 48, 49, 50 Read 10 execution plans; tune 5 queries
28 Design 51, 52, 53 Normalize a messy schema to 3NF; build a star schema
29 Security and operations 54, 55, 56, 57 Set up roles; take and restore a backup
30 Modern data 58, 59 JSON queries; rewrite a cursor as a set operation
31 Text and time 60, 61 Break a column with the wrong collation; build a per-user local-time report
32 History and change 62 Make a table temporal; reconstruct it as of last Tuesday
33 Concurrency 63 Reproduce a lost update, then fix it three different ways
34 Engineering practice 64, 65 Build a migration runner; find and fix an N+1
35 Review 66 Anti-patterns, the question bank, start the capstone

[!TIP] 💡 How to actually make this work:

  • Type every example by hand. Copy-paste teaches your clipboard, not you.
  • Break things deliberately. Then read the error message properly. Errors are the fastest teacher in SQL.
  • Keep a personal snippets file. Every time you solve something, save the query with a one-line comment.
  • The 🔥 days are the ones that matter most. Joins, window functions, and performance are what separate someone who “knows SQL” from someone who is genuinely good at it. Spend extra time there without guilt.

66.7 📖 Glossary

Term Meaning
ACID Atomicity, Consistency, Isolation, Durability — the four transaction guarantees
Aggregate A function collapsing many rows into one value (SUM, COUNT, AVG)
Allow-list A fixed list of permitted values (such as column names) that user input is checked against
Anti-join Finding rows with no match (LEFT JOIN ... IS NULL or NOT EXISTS)
API Application programming interface — the agreed way one program asks another for data or actions
Backfill Populating a newly added column for existing rows — a batch job, not a migration
Batch A group of SQL statements sent to the server together; in MSSQL, GO separates batches
B-tree The balanced tree structure behind almost every index
Cardinality The number of distinct values in a column; also the estimated row count
Cartesian product Every row of A paired with every row of B — usually an accident
Change Tracking / CDC Engine features that record which rows changed (and, for CDC, their old and new values)
CI Continuous integration — automatically testing every change as soon as it is saved
Clustered index The table itself, physically ordered by the index key
Collation The rules deciding how text sorts and compares — case, accents, and language order
Column One fact stored for every row, such as email
Connection pool A set of open database connections an application reuses, instead of opening a new one per request
Covering index An index containing every column a query needs, so the table is never read
CRUD Create, Read, Update, Delete
CSV A plain text file with one row per line and commas between values — opens in Excel
CTE Common Table Expression — a named subquery defined with WITH
Database The whole organized container of tables — ShopDB in this guide
DBA Database administrator — the person who keeps databases running, safe, and fast
DDL / DML / DQL / DCL / TCL The five command families (Chapter 2)
Deadlock Two transactions each blocking the other; the engine kills one
Denormalization Deliberately duplicating data to speed up reads
Dirty read Reading uncommitted data that may be rolled back
DMV Dynamic management view — a built-in MSSQL system view that reports what the server is doing
DST Daylight saving time — clocks moving forward or back one hour each year
Engine The database software itself — here, SQL Server or MySQL
ETL Extract, transform, load — copying data out of one system, cleaning it, and loading it into another
Execution plan The engine’s chosen strategy for running a query
Expand–contract Splitting a breaking schema change into additive, migrate, and remove phases
Fact / dimension table The measurement table and its descriptive lookups in a star schema
Fan-out Row multiplication caused by joining two one-to-many children
Foreign key A column referencing a key in another table
GUID / UUID A 128-bit identifier with version-dependent generation; some UUID versions encode time rather than randomness, e.g. 3f2504e0-4f89-11d3-9a0c-0305e82c3301
Heap A table with no clustered index
Idempotent Safe to run more than once — the second run changes nothing
Index A sorted lookup structure that finds rows fast, like the index at the back of a book
Index seek / scan Jumping to specific rows vs reading everything
InnoDB MySQL’s default storage engine — the part that actually stores the data. Always use it
Isolation level How much concurrent interference a transaction tolerates
JSON A text format for structured data, e.g. {"name": "Amara", "city": "Colombo"}
Key lookup Going back to the table because the index lacked a needed column
Latency Waiting time — how long one request takes
Lost update Two writers both save, and one silently overwrites the other. No error is raised
Migration A versioned script, kept in Git, that changes the database structure (Chapter 64)
MVCC Multi-Version Concurrency Control — nonlocking reads can use snapshots; locking reads and writes can still block
N+1 One query for a list, plus one more per row returned — an application-side performance bug
Normalization Structuring tables so each fact is stored exactly once
NULL “No value / unknown” — not zero and not an empty string (Chapter 15)
OLTP / OLAP Transaction processing (many small writes) vs analytical processing (large reads)
Optimistic concurrency Detecting a conflict at write time with a version token, instead of locking
ORM A code library that writes SQL for your application, e.g. Entity Framework or Hibernate
Page The fixed-size block that data is stored in — 8 KB in SQL Server, 16 KB in MySQL
Parameter sniffing Reusing a cached plan built for an unrepresentative parameter value
Partitioning Splitting one table into physical pieces by a key
Percentile The value below which a given fraction of rows fall — P50 is the median
Pessimistic concurrency Locking a row at read time so nobody else can change it
Phantom read New rows appearing between two identical queries in one transaction
Predicate A condition that is true or false for each row, e.g. country = 'UK' in a WHERE
Primary key The unique, non-null identifier of a row
Query A question (or instruction) you send to the database, written in SQL
Query Store 🟥 On-disk history of queries, plans, and runtime statistics, surviving restarts
RBAR “Row By Agonizing Row” — the anti-pattern of looping instead of set operations
Referential integrity The guarantee that every foreign key points at a row that exists
Replica A copy of a database, kept up to date, on another server
Row One single item in a table, such as one customer
ROWVERSION 🟥 An 8-byte value the engine increases on every update — the standard optimistic-concurrency token
RPO / RTO How much data you can lose / how long you can be down
SARGable A condition that can use an index to jump straight to the matching rows
Savepoint A bookmark inside a transaction that you can roll back to without undoing everything
SCD Slowly Changing Dimension — how a data warehouse handles changing attributes
Schema The structure of a database; in MSSQL, also a named container for objects
Session Your connection to the database — settings and temporary tables belong to it
Set-based Operating on whole sets of rows at once, the way SQL is designed to work
Sharding Splitting data across separate servers
SQL Structured Query Language — the language used to talk to relational databases
Star schema A central fact table surrounded by flat dimension tables
Statistics Summary data about value distribution, used by the optimizer
Stored procedure A saved, named SQL program that you run by name (Chapter 37)
Subquery A query written inside another query
Surrogate key A meaningless generated identifier (an IDENTITY / AUTO_INCREMENT ID)
T-SQL Transact-SQL — Microsoft SQL Server’s version of SQL
Table One list of one kind of thing, in rows and columns — like a spreadsheet tab
Temporal table 🟥 A current/history table pair retaining prior updated or deleted versions while versioning is enabled; retention and query semantics still matter
Throughput How much work gets done per second
TLS Encryption for network connections — the padlock you see in a web browser
Transaction A group of changes that all succeed or all fail
Trigger Code that runs automatically on insert, update, or delete
UDF / TVF User-defined function / table-valued function — your own function that returns one value, or a whole table (Chapter 38)
Upsert Insert if new, update if existing
UTC Coordinated Universal Time — useful for instants; local schedules also need a time-zone ID, and dates may need no zone
utf8mb4 🟦 MySQL’s real UTF-8 charset. The one named utf8 is a broken three-byte subset
View A saved query that behaves like a table
Window function A calculation across related rows that does not collapse them
Write-ahead log Changes written to a log before the data files, guaranteeing durability

66.8 🔗 Where to go next

Official documentation
Resource What it is
Microsoft Learn — SQL Server documentation The authoritative SQL Server reference (learn.microsoft.com/sql)
MySQL Reference Manual The authoritative MySQL reference (dev.mysql.com/doc)
Microsoft Learn — T-SQL reference Every function and statement, with examples
MySQL Performance Blog (Percona) Deep, practical MySQL tuning
Tools worth learning
Tool Why
SSMS / VS Code with the MSSQL extension The MSSQL workhorses (Azure Data Studio was retired in February 2026)
MySQL Workbench Official MySQL GUI with an ER modeller
DBeaver One client for both engines — ideal for this guide
Percona Toolkit pt-online-schema-change, pt-query-digest — essential MySQL ops tooling
Ola Hallengren’s Maintenance Solution The community-standard MSSQL backup/index/check scripts
Brent Ozar’s First Responder Kit sp_Blitz, sp_BlitzCache — instant MSSQL health diagnosis
Flyway / Liquibase Version-controlled database migrations (Chapter 64)
sqlfluff A SQL linter and formatter for both engines — wire it into a pre-commit hook
tSQLt The unit-testing framework for T-SQL
gh-ost / pt-online-schema-change Online schema changes on large MySQL tables without locking
Topics beyond this guide
  • Columnstore indexes and data warehousing for large-scale reporting
  • In-Memory OLTP (MSSQL) for extremely fast writes
  • Replication and high availability — Always On availability groups, MySQL group replication
  • PostgreSQL — the third engine every SQL professional should meet
  • Cloud databases — Azure SQL, Amazon RDS/Aurora, Google Cloud SQL
  • Data engineering — dbt, Airflow, Snowflake, BigQuery (all SQL-first)
  • Change-data streaming — Debezium, Kafka Connect, and event-driven architectures

66.9 ✅ The professional checklist

Print this. Run through it before any schema goes to production.

📐 Design
  • ☐ Every table has a primary key
  • ☐ Primary keys are narrow, stable, and never updated
  • ☐ Every relationship has a foreign key constraint
  • ☐ Every foreign key column is indexed (especially MSSQL)
  • ☐ Naming convention documented and applied consistently
  • ☐ NOT NULL by default; every nullable column justified
  • ☐ Money is DECIMAL; dates are UTC; phones are strings
  • ☐ No comma-separated lists, no col1/col2/col3
  • ☐ Business rules enforced by constraints, not only in the app
  • ☐ Denormalized values have maintenance and verification scripts
  • ☐ Soft-delete strategy decided and applied consistently
  • ☐ Collation and character set chosen deliberately, before the first row
  • ☐ Every timestamp column stores UTC, and its name says so
✍️ Queries
  • ☐ No SELECT * in application code
  • ☐ All conditions SARGable (index-friendly)
  • ☐ Explicit JOIN ... ON, never comma joins
  • ☐ LEFT JOIN conditions in the right clause
  • ☐ No DISTINCT masking a join problem
  • ☐ NOT EXISTS instead of NOT IN on subqueries
  • ☐ Date ranges use the half-open pattern
  • ☐ ORDER BY present wherever order matters
  • ☐ Deep paging uses keyset, not OFFSET
  • ☐ Large writes are batched
  • ☐ No COLLATE or time-zone conversion applied to an indexed column in WHERE
  • ☐ Concurrent writes use a guarded UPDATE or a version token, never read-then-write
⚡ Performance
  • ☐ Slow queries identified from real measurements, not guesswork
  • ☐ Execution plans reviewed for the top 10 queries
  • ☐ No unused indexes; no redundant duplicates
  • ☐ Statistics updated on a schedule
  • ☐ Estimated vs actual row counts checked on critical queries
  • ☐ A performance baseline captured, so you can tell what “slow” means
  • ☐ 🟥 Query Store enabled, and confirmed still READ_WRITE
  • ☐ Every forced plan recorded, with a reason and a review date
  • ☐ Query count per application request logged, with an N+1 alert
🛡️ Security and operations
  • ☐ Every query parameterized
  • ☐ Least privilege applied; no app uses sa/root
  • ☐ Permissions granted through roles
  • ☐ Connections encrypted; sensitive data encrypted at rest
  • ☐ Passwords hashed in the application
  • ☐ Backups automated, monitored, off-site, and encrypted
  • ☐ A restore has actually been performed and timed
  • ☐ RPO and RTO agreed with the business
  • ☐ Consistency checks (DBCC CHECKDB / CHECK TABLE) scheduled
  • ☐ Monitoring and alerting configured for space, blocking, and backup failure
  • ☐ Connection pool sized for the server, counting every service together
  • ☐ Connect, command, and lock timeouts all set explicitly
  • ☐ Retries cover only transient errors, with backoff and jitter
  • ☐ Anything a client can retry has an idempotency key
🚚 Delivery
  • ☐ Every schema change is a versioned script in Git
  • ☐ Migrations are immutable once merged, idempotent, and checksummed
  • ☐ Breaking changes go through expand–contract, never one step
  • ☐ Migrations tested against a restored production copy, and timed
  • ☐ Constraint and regression tests run in CI
  • ☐ Naming and formatting conventions documented and linted automatically
  • ☐ Nobody does routine work in a production query window

🎓 You made it

You started this guide not knowing what a row was. You now know how to design a schema that protects itself, query it in ways most developers never learn, tune it when it slows down, secure it against the attacks that break real companies, and restore it when the worst happens.

The five things worth remembering above all else

  1. 🧠 Think in sets, not loops. This is the mindset shift that changes everything.
  2. 🛡️ Let the database protect your data. Constraints do not have bad days; application code does.
  3. 📏 Measure before you optimize. Read the plan. Guessing wastes days.
  4. 🔒 Parameterize everything, always. There is no acceptable exception.
  5. 💾 A backup you have not restored is not a backup.

A beginner asks: “How do I write this query?”

A professional asks: “What question is the business really asking? What must always be true about this data? How will this behave at a thousand times the volume? What happens when two people do this at once? And how do I get it back if it goes wrong?”

That shift — from syntax to responsibility — is the whole journey. This guide exists to make it as short as possible.

Now close the guide, open a query window, and go build something. 🚀


The Complete SQL Guide — MSSQL & MySQL By Gehan Fernando

Read it once. Use it forever. Break things on purpose.


Python application foundations · C# application foundations

Learning paths · Documentation index

Part index Prerequisites Previous Full course