# CMU15-445 Notes

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/db-notes-cmu15-445/>). I am continuously working to improve the translation.

# Relational Model & Algebra

## Basic Concepts

Relational databases:

- Separate relations from content, i.e., the presentation form is the same, while the internal physical storage structure is encapsulated
- Guarantee that data satisfies specific constraints
- Provide APIs for modification

Relation: an unordered collection of data, representing a series of attributes of some entity (think of it as a highly abstract data structure)

Record/tuple: an instantiation of a relation

Foreign Key: a field stored in the current table that points to the ID of another table.

Foreign Table: the target table being pointed to (in the diagram, that would be `Artist` and `Album`).

Constraints: e.g., the uniqueness of primary keys

Date Manipulation Languages (DML):

- Procedural: you need to specify step by step how to compute the result
- Non-Procedural: you specify the result you want without caring about the process

We focus on the latter, which is closely related to relational algebra.

## Relational Algebra

Seven basic operations: select, projection, union, intersection, difference, product, join

select: filter the table according to given predicate logic

projection: specifies how you want to present the result, selecting the desired attributes (columns)

union: takes the common attributes and merges relations

intersection: intersection

product: Cartesian product

join: find the parts with the same primary value and connect them together

...

In short, relational algebra can describe how to operate on a database. Sometimes different algebraic expressions yield the same result, but performance may vary depending on the database's storage method. — Thus SQL came into being.

> Although relational databases were designed to be set-based in the original papers, today's SQL is based on multi ordered sets -> bags.

### Extra

Document data models: JSON XML

# Modern SQL

Aggregates: Functions that return a single value from a bag of tuples: AVG(col), MIN(col), MAX(col), SUM(col), COUNT(col)

GROUP BY: groups tuples

HAVING: let's start with a wrong example

```sql
SELECT AVG(s.gpa) AS avg_gpa, e.cid
FROM enrolled as e, student AS s
WHERE e.sid = s.sid
AND avg_gpa > 3.9
GROUP BY e.cid
```

The `AND avg_gpa > 3.9` here is wrong, because aggregate computation happens after the query is computed (**you need to understand the execution order of SQL statements here**). The correct approach:

```sql
SELECT AVG(s.gpa) AS avg_gpa, e.cid
FROM enrolled as e, student AS s
WHERE e.sid = s.sid
GROUP BY e.cid
HAVING avg_gpa > 3.9
```

> The logical order in which the database actually executes:
>
> 1. **FROM & JOIN**: first join the tables together, forming a large mass of raw data.
> 2. **WHERE**: **right here!** The database scans the raw data row by row. If a row doesn't meet the condition (e.g., `e.sid != s.sid`), it's simply thrown away.
>     - *Reason for the error*: at this point the database hasn't started "grouping" yet, let alone computed the "average". If you ask it to filter by `avg_gpa > 3.9`, it will be completely baffled: **"What is avg_gpa? I haven't computed it yet!"**
> 3. **GROUP BY**: group the remaining rows into piles by `cid`.
> 4. **Compute aggregates**: compute `AVG(gpa)` within each pile.
> 5. **HAVING**: **its turn!** The database looks at the computed averages and throws away the "piles" that don't meet the standard.
> 6. **SELECT**: finally, display the remaining results.

Strings: the SQL standard is not case-sensitive, and strings are wrapped in **single quotes**.

**But every database system differs, and I don't want to document the details here.**

LIKE: used for string matching

'%' matches any substrings, '_' match any one character.

There are also many other miscellaneous string functions.

As for dates, almost all mainstream databases lack a unified standard in this area.

Window Functions:

Example:

```sql
SELECT FUNC-NAME(...) OVER(...) FROM tableName
```

Inside `FUNC-NAME()` you can use Aggregation Functions or Special Functions; the so-called Special Functions are `ROW_NUMBER()` and `RANK()`.

Inside `OVER()` you fill in `PARTITION BY` or `ORDER BY`

A SELECT statement with window functions cannot directly use a WHERE clause.

The advantage of JOIN over nested queries: the latter usually has poor time complexity; optimizing it into a JOIN is generally better.

> Let's use the most classic scenario, one that appears constantly in interviews and real-world development: **"find the student with the highest GPA in each department"**.
>
> Suppose we have two tables:
>
> 1. **`student`** (sid, name, dept_id)
> 2. **`enrolled`** (sid, gpa)
>
> ------
>
> ### ❌ Bad Example: Correlated Subquery
>
> This approach is very intuitive: for every student, I look up the maximum GPA in their department, then check whether they are that top scorer.
>
> SQL
>
> ```sql
> SELECT s.name, s.dept_id, e.gpa
> FROM student AS s
> JOIN enrolled AS e ON s.sid = e.sid
> WHERE e.gpa = (
>     -- 子查询：每一行都要重新跑一遍
>     SELECT MAX(e2.gpa)
>     FROM student AS s2
>     JOIN enrolled AS e2 ON s2.sid = e2.sid
>     WHERE s2.dept_id = s.dept_id
> );
> ```
>
> **Why is it bad?**
>
> - **Row-by-row scanning**: if the school has 10,000 students, the database has to execute the inner `SELECT MAX` 10,000 times.
> - **Repeated computation**: the maximum for the same department is computed hundreds or thousands of times over.
> - **Complexity**: this is known in databases as an $O(N^2)$ operation — double the data, and the time quadruples.
>
> ------
>
> ### ✅ Good Example: Using JOIN (or a CTE temporary table)
>
> We change our approach: first compute "the highest score in each department" in one go to get a small list, then directly match the student table against this list.
>
> SQL
>
> ```sql
> -- 先算出每个系的最高分清单
> WITH DeptMaxGpa AS (
>     SELECT s2.dept_id, MAX(e2.gpa) AS max_gpa
>     FROM student AS s2
>     JOIN enrolled AS e2 ON s2.sid = e2.sid
>     GROUP BY s2.dept_id
> )
> -- 然后直接做一次高效的 JOIN
> SELECT s.name, s.dept_id, e.gpa
> FROM student AS s
> JOIN enrolled AS e ON s.sid = e.sid
> JOIN DeptMaxGpa AS dmg ON s.dept_id = dmg.dept_id AND e.gpa = dmg.max_gpa;
> ```
>
> **Why is it fast?**
>
> - **Computed only once**: no matter how many students you have, each department's maximum is computed only once.
> - **Uses indexes**: the final `JOIN` can leverage the database's Hash Join algorithm, which is extremely fast.
> - **Batch processing**: databases are best at set-to-set operations, not row-by-row judgments.
>
> ------
>
> ### 🚀 Ultimate Evolution: Using a Window Function
>
> If you've already mastered the window functions we just discussed, the code becomes even more concise with excellent performance:
>
> SQL
>
> ```sql
> SELECT name, dept_id, gpa
> FROM (
>     SELECT s.name, s.dept_id, e.gpa,
>            RANK() OVER (PARTITION BY s.dept_id ORDER BY e.gpa DESC) as rnk
>     FROM student AS s
>     JOIN enrolled AS e ON s.sid = e.sid
> ) AS ranked_students
> WHERE rnk = 1;
> ```
>
> **Its power:**
>
> - **Single scan**: the database only needs to read the data once and sort it in memory.
> - **Clear semantics**: at a glance you can see you're ranking by department and taking the first.
>
> ------
>
> ### Summary: The Essence of Optimization
>
> 1. **Reduce the number of scans**: if one pass over the table suffices, never scan twice.
> 2. **Turn "serial" into "parallel"**: avoid making the subquery depend on variables from the outer query (i.e., avoid "correlation").
> 3. **Trust the power of sets**: always prioritize transforming the problem into "joins between tables".

Nested queries also have ALL, ANY, IN, EXISTS — let an LLM explain:

> These four keywords are the "logical gatekeepers" of SQL nested queries; they specifically handle the relationship between the **main query** and **the set of values returned by the subquery**.
>
> Simply put, when the subquery returns more than one number (i.e., a list), you need these four brothers to help make the decision.
>
> ------
>
> ### 1. ALL (all must be satisfied)
>
> **Logic:** The condition holds only when the main query's value satisfies **every** value in the subquery's result.
>
> - **Example:** `WHERE gpa > ALL (SELECT gpa FROM students WHERE dept_id = 'CS')`
> - **In plain words:** Your GPA must be higher than **everyone's** in the CS department (i.e., you're even stronger than the CS department's top student).
>
> ------
>
> ### 2. ANY (satisfy at least one)
>
> **Logic:** The condition holds as long as the main query's value satisfies **at least one** value in the subquery's result.
>
> - **Example:** `WHERE gpa > ANY (SELECT gpa FROM students WHERE dept_id = 'CS')`
> - **In plain words:** Your GPA just needs to be higher than **any one person's** in the CS department (i.e., as long as you're not the CS department's worst, you win).
> - **Trivia:** `ANY` and `SOME` are completely equivalent in SQL; since `ANY` is more commonly used, `SOME` is often forgotten.
>
> ------
>
> ### 3. IN (existence check)
>
> **Logic:** Checks whether the main query's value **equals** one of the values in the subquery's result list.
>
> - **Example:** `WHERE sid IN (SELECT sid FROM enrolled WHERE cid = '15-445')`
> - **In plain words:** Check whether your ID is on that "15-445 enrollment list".
> - **Equivalence:** `IN` is actually equivalent to `= ANY`.
>
> ------
>
> ### 4. EXISTS (whether there are results)
>
> **Logic:** It's the most special one — it doesn't care about the specific values the subquery returns; it only cares whether the subquery **returned any rows** (whether the set is empty).
>
> - **Example:** `WHERE EXISTS (SELECT * FROM enrolled WHERE sid = s.sid AND cid = '15-445')`
> - **In plain words:** The database asks: "Hey, is this student on that list?" If yes, even just one row, it counts as success.
> - **Power:** As we discussed earlier, `EXISTS` combined with "correlated subqueries" is very powerful, because it stops scanning as soon as it finds the first matching row (short-circuit evaluation), sometimes performing better than `IN`.
>
> ------
>
> ### Summary Comparison Table
>
> | **Keyword**  | **Core Logic**       | **Similar Human Language**            |
> | ------------ | -------------------- | ------------------------------------- |
> | **`ALL`**    | Must beat everyone   | "Are you stronger than each of them?" |
> | **`ANY`**    | Beat just one        | "Are you stronger than any of them?"  |
> | **`IN`**     | Exact match          | "Are you on the list?"                |
> | **`EXISTS`** | Existence check      | "Is there a record about you on the list?" |

LATERAL JOIN: the for-loop in SQL



Common table expression (CTE): **before executing the main query, first define a temporary table and give it a name.**

For example:

```sql
SELECT name FROM student
WHERE gpa > (SELECT AVG(gpa) FROM student)
```

Using a CTE makes the logic clearer:

```sql
WITH SchoolAvg AS (
	SELECT Avg(gpa) AS avg_gpa FROM student
)
SELECT s.name
FROM student AS s, SchoolAvg as sa
WHERE s.gpa > sa.gpa
```
