Add lesson 6: Subqueries

Mira Kovac 1 year ago
parent fead64216e commit b2c74c55fd9bc48f14a3b7f9c556546dd4fc4012
3 changed files with 37 additions and 0 deletions
+21-0lessons/06-subqueries/README.md ADDED
@@ -0,0 +1,21 @@
1+# Lesson 6: Subqueries
2+
3+This lesson covers subqueries. You'll read a short explanation, try three small exercises and finish with a quiz.
4+
5+Full lesson: [https://glibcode.net/courses/sql-essentials/lessons/6](https://glibcode.net/courses/sql-essentials/lessons/6)
6+
7+## Files
8+
9+- `subqueries.sql`: subqueries in WHERE and FROM
10+
11+## Run it
12+
13+```sh
14+sqlite3 shop.db < ../../setup/schema.sql
15+sqlite3 shop.db < ../../setup/seed.sql
16+sqlite3 shop.db < subqueries.sql
17+```
18+
19+## Exercises
20+
21+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/06-subqueries/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 6
2+
3+1. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original.
4+2. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to?
5+3. Rewrite the main part so it runs twice with two different inputs, without copying the code.
+11-0lessons/06-subqueries/subqueries.sql ADDED
@@ -0,0 +1,11 @@
1+-- Products more expensive than the average
2+SELECT name, price
3+FROM products
4+WHERE price > (SELECT AVG(price) FROM products);
5+
6+-- Each customer's biggest order
7+SELECT c.name, big.max_total
8+FROM customers AS c
9+JOIN (SELECT customer_id, MAX(total) AS max_total
10+ FROM orders GROUP BY customer_id) AS big
11+ ON big.customer_id = c.id;