# Database System Concepts - Notes 1

> 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-note-1/>). I am continuously working to improve the translation.

Textbook: Database System Concepts

Reference blogs:

- [Kisechan's Blog](https://blog.kisechan.space/2025/notes-database-1/)
- [Database Notes | 独角恋歌](https://revival-of-hope.github.io/2026/03/14/数据库笔记/)

Coverage: Textbook Chapters 1–5, roughly database fundamentals + SQL

# Chapter 1 Intro

## What is a DBMS

What is DBMS (Database System Management System)? :

- A collection of related data
- A collection of **programs for accessing that data**

A database is the **collection of related data** here; databases were invented to fill in the shortcomings of the original file systems.

## Shortcomings of File Systems / Purpose of Database Systems

1. Data redundancy: multiple people create different files containing the same data, and different copies of a piece of data can be inconsistent.
2. Difficult data access: lack of standardization
3. Lack of integrity constraints: no unified mechanism to keep data valid
4. No support for concurrent access
5. Insecure
6. Atomicity problems: traditional file systems cannot guarantee transaction integrity, easily producing half-finished data
7. Data islands: data is scattered across files in different formats, making it hard to write retrieval programs, because the data is fragmented.

## View of Data / Perspectives on Data

A view of data means **looking at and managing data from different angles**. The data itself is the same, but different people / levels focus on different aspects of it.

|   Perspective   |                     Focus                     |               Example               |
| :------: | :--------------------------------------------: | :------------------------------: |
| Physical view |        **How data is stored on disk**, storage details        |  File organization, index structures, disk block management  |
| Logical view |       **How data is organized and related**, structured representation       |           Tables, columns, foreign keys           |
| User view | **What data users need to see**, how to hide irrelevant information | Show only student names and grades, not student IDs |

### Data Abstraction

Data abstraction: different expressions of the view of data. It allows users to operate on data at different levels without having to care about the underlying physical storage structure or complex logical relationships.

Three levels of data abstraction:

- Physical level
    - The organizational structure of data on physical storage media, involving file organization, indexes, storage structures (B+ trees, etc.), optimizing storage efficiency and access speed.
- Logical level
    - Describes the logical constraints of data, such as relations and tables
- View level
    - Hiding tailored to different users; for example, some users cannot see certain tables while others can

### Data Models

A data model is a tool for describing **data, data relationships, data semantics, and consistency constraints**

> A collection of conceptual tools for describing **data, data relationships, data semantics, and consistency constraints**.

> **What are consistency constraints?**
>
> A kind of "rule" of the database that ensures data always remains **accurate, complete, and valid** when updated.
>
> Classifying consistency constraints:
>
> - Entity integrity: ensures every row is unique -> primary key constraint
> - Domain integrity: constrains the data type and range of a specific column, e.g., a column cannot be empty (NOT NULL constraint), a column has a default value (default constraint), age cannot be negative (CHECK constraint)
> - Referential integrity -> foreign key constraint
> - Other user-defined constraints

A data model consists of three parts: **data structures** (data entities and their relationships), **data operations** (CRUD), and **data constraints**.

The main data models are:

| Data Model           | Explanation                                  |
| ------------------ | ------------------------------------- |
| Relational model           | Data is stored in two-dimensional tables                    |
| Entity-Relationship model      | E-R diagrams, used in the design phase                   |
| Object-based data model | OOP, treating data as objects (with attributes and methods) |
| Semi-structured data model   | Data not in fixed tables, e.g., JSON, XML     |
| Network data model       | A network graph, connected via complex pointers          |
| Hierarchical data model       | Tree-shaped                                |

### Instances and Schemas

Instances: The collection of information stored in the database at a particular moment is called an instance of the database.

Schema: The overall design of the database is called the database schema. It is divided into the **physical schema** and the **logical schema**, corresponding to the physical level and the logical level.

> [!Tip]
>
> Physical data has independence: modifying the physical schema does not affect the logical schema. For example: a table originally stored sequentially is changed to be stored with a B+ tree, but the logical schema used to write SQL does not need to be modified.

| Concept |                             Explanation                             |
| :--: | :----------------------------------------------------------: |
| Schema | **The structural blueprint of the database**. E.g., which tables exist, what types the fields are, how foreign keys relate (a "fixed structure"). |
| Instance |            **The actual data content stored in the database at a given moment**            |

## Database Languages

Database languages: languages used to communicate with the DBMS. Main purposes:

1. Define data structures (tables, fields, constraints)
2. CRUD

Database languages consist of **DDL and DML**. SQL includes both of these languages.

- DDL: Data Definition Language, the language for defining the database schema; it can also specify consistency constraints and authorize users, e.g., `create table` in SQL
- DML: Data Manipulation Language, for **CRUD**

## Database Users and Adminstrators

It's basically self-explanatory.

## History

Skipped



**The Summary at the end of the textbook is quite good for review.**

# Chapter 2 Introduction to the Relational Model

## Structure of Relational Databases

### Tables

A relational database consists of a collection of **tables**, and **each table is a relation**.

> A relational database consists of a collection of tables, each of which is assigned a **unique name**.

A table consists of a **header** (Schema) — column names and data types — and a **body** (Instance) — the actual **data rows**.

### Relation Schema

A relation schema is the structural definition of a table, including:

- Table name
- Attribute names, data types
- Integrity constraints

### Relation Instance

The specific data of a table at a given moment

|    Concept    |                     Meaning                     |             Example              |
| :--------: | :------------------------------------------: | :---------------------------: |
|    Relation    |                A **two-dimensional table**                |        Student table, employee table         |
|  Relation schema  |  The **structural definition** of a table (field names, data types, constraints)  |    Student (student ID, name, age)     |
|  Relation instance  |    The **data content** of the table at some point in time (several rows)    | At a certain moment, the student table has 5 records |
|     Table     | **The structure that actually stores data**; the manifestation of a "relation" |         The `Student` table          |
| Relational database |       A database system **composed of a set of related tables**       |  Student table, course table, enrollment table, etc.   |

### Tuple

> In mathematical terminology, a **tuple** is simply **a sequence(or list) of values**. A relationship between n values is represented mathematically by an n-tuple of values, that is, a tuple with n values, which corresponds to a row in a table.

### Attribute

**attribute** refers to a column of a table.

**domain of an attribute:** For each attribute of a relation, there is a set of permitted values. 

**atomic:** If the values of a domain can still be split into smaller meaningful units logically / in usage, then it is not atomic.

### Keys

A key is an attribute used to uniquely identify or establish relationships, divided into the following:

#### super key

A set of one or more attributes, which may contain redundant attributes.

It uniquely identifies a tuple within a relation.

#### candidate key

The minimal set of attributes that identifies a tuple; a table can have multiple candidate keys.

#### primary key

A unique identifier chosen from among the candidate keys.

Not NULL, values unique.

#### foreign key

An attribute in this relation/table that happens to be the primary key of another relation, thereby establishing relationships between tables.

### Schema Diagram

A schema diagram is a **graphical tool** that shows the structure and connections among the relations (tables) in a relational database.

- Each rectangle represents a relation (table);
- Each rectangle lists the attributes (fields) of that table;
    - Primary keys are usually underlined;
    - Foreign keys usually have arrows pointing to the primary keys they reference;
- Arrows represent the **reference relationships** from foreign keys to primary keys.

> We use a two-headed arrow, instead of a single-headed arrow, to indicate a referential integrity constraint that is not a foreign-key constraints.
>
> Meaning unclear, left as TODO, skipped

<img src="https://image.wendaining.top/6a1df3f7-9fa8-45f5-9a70-0b2e29357107.png" alt="figure" style="zoom: 67%;" />

## Relational Algebra

Data Manipulation Languages (DML):

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

- **SQL** is the most typical **non-procedural language**: you only need to describe the data you want to query, and the database system takes care of how to execute the query.
- **Relational algebra** is a kind of **procedural language**. You need to obtain data through a series of operations, such as selection, projection, join, etc.

Relational algebra has 8 basic operations, and the results of the operations are **all tables**:

|       Operation       |   Symbol   |                 Description                 |                      Example                      |             Function             |
| :--------------: | :------: | :----------------------------------: | :--------------------------------------------: | :------------------------------: |
|      union       | $\cup$  |  Take all tuples from two relations (merge with deduplication)  |                   $R \cup S$                   |      Merge two relations with the same structure      |
|   intersection   | $\cap$  |       Take the tuples common to both relations         |                   $R \cap S$                   |      Find data contained in both relations    |
|    difference    |    $-$    |      Get the tuples belonging only to the first relation      |                    $R - S$                     | Remove from $R$ all tuples that also belong to $S$   |
|      select      | $\sigma$ |   Select tuples (rows) from a relation that satisfy a condition   |         ${\sigma}_{age>30}(Employee)$          |       Select employees older than 30       |
|    projection    |  $\Pi$   | Select specific attributes (columns) from a relation (with deduplication) |        ${\Pi}_{name,salary}(Employee)$        |       Show only the name and salary fields       |
| Cartesian-Product | $\times$ |              Compute the Cartesian product              |                  $R \times S$                  |           Used to construct joins           |
|       join       | $\bowtie$ |      Join tuples from two relations by condition     |           $R \bowtie_{R.a=S.a} S$             |      Combine two tables by common attributes    |
|    assignment    | $\leftarrow$ |      Assign the result of an operation to a relation variable      | $T \leftarrow {\sigma}_{age>30}(Employee)$ |      Save intermediate results for later operations  |
|      rename      |  $\rho$  |      Rename a relation or attribute          |      ${\rho}_{E(name,salary)}(Employee)$      |   Rename a relation or column for later reference   |

Among them, union, intersection, difference, and Cartesian-Product are just plain set operations. Some additional points:

- Prerequisites for union, intersection, and difference:
    1. The two input relations have the same number of attributes
    2. When the attributes correspond, the corresponding attributes in the two relations have the same types (**i.e., they don't need to have the same names**)
- The Cartesian product requires *r*  ∩ *s*=∅

There's not much to say about assignment and rename

select and projection are also easy to understand: select picks specific rows, projection picks specific columns

**join is more complicated**:

A plain join, called an equi-join, does not remove the duplicate columns. For example:
<img src="https://image.wendaining.top/image-20260401224037665.png" alt="figure 2.13" style="zoom: 67%;" />

Here the `ID` column used for matching still exists.

This leads to the natural join, which removes the duplicate columns on top of the ordinary join above — quite natural, hence the name. It is usually written directly as $\bowtie$.

**Natural joins do not produce records containing null**

How to produce records containing null? There are Left Outer Join, Right Outer Join, and Full Outer Join. Consider the two relations of a course roster (course - student ID) and student enrollment (student - course): from the student's perspective, courses not enrolled in are not needed; from the registrar's perspective, one needs to know which courses have no one enrolled.

# Chapter 3 Introduction to SQL

## Overview of the SQL

The SQL language has several parts:

- DDL: the DDL part in SQL provides commands for defining relation schemas, deleting relations, and modifying relation schemas.
- DML: the DML part in SQL provides the ability to query info from the databse and to insert tuples into, delete tuples from, and modify tuples in the database.

-> Data-definition operates on the schema; data-manipulation operates on instances.

- Integrity: ensures the data entered conforms to the rules

## Data Definition

Data definition is SQL's ability to **define the database structure and its metadata**; it is the first step of database design, involving table structure, data types, constraint rules, storage strategies, etc.

### Basic Types

Data types specify the value range, precision, and operations of values.

|      Data Type      |                   Meaning                    |
| :----------------: | :---------------------------------------: |
|     `CHAR(n)`      | Fixed-length string, occupies n characters, padded with spaces |
|    `VARCHAR(n)`    |       Variable-length string, maximum length n        |
|  `INT`, `INTEGER`  |            Integer (usually 4 bytes)            |
|     `SMALLINT`     |           Small integer (usually 2 bytes)           |
|   `NUMERIC(p,d)`   |    Exact decimal, p total digits, d decimal digits     |
|       `REAL`       |          Single-precision floating point (approximate)           |
| `DOUBLE PRECISION` |               Double-precision floating point                |
|     `FLOAT(n)`     |   Floating point with precision n, where n is the number of significant binary digits   |

> Each type may include a special value called the **null** value. A null value indicates an absent value that may exist but be unknown or that may not exist at all. In certain cases, we may wish to prohibit null values from being entered, as we shall see shortly.

For strings, `VARCHAR` is actually always recommended, because variable-length and fixed-length arrays may not behave as expected when compared.

> even if the same value “Avi” is stored in the attributes A and B above, a comparison A=B may return false. We recommend you always use the varchar type instead of the char type to avoid these problems.

### Basic Schema Defination

**Relation schema**: describes the structure of a table: table name + attributes (column names) + data types of the attributes.

```sql
CREATE TABLE Student (
    ID INT,
    Name VARCHAR(50),
    Age INT
    PRIMARY KEY(ID)
);
```

Note that types come **after** the names.

#### Integrity Constraints

Mainly includes (only these are mentioned here):

- Primary key (`PRIMARY KEY`)
- Not null (`NOT NULL`)
- Foreign key (`FOREIGN KEY`)
- Check conditions (`CHECK`)

```sql
CREATE TABLE Course (
    CourseID INT,
    CourseName VARCHAR(100) NOT NULL,
    TeacherID INT,
    PRIMARY KEY(CourseID)
    FOREIGN KEY (TeacherID) REFERENCES Teacher(ID)
);
```

> **Integrity constraints** are **rules** set at the **logical level** of the database to ensure data correctness, validity, and consistency. The main types include:
>
> - **Entity integrity**:
>     - The primary key (`PRIMARY KEY`) cannot be `NULL` and uniquely identifies a record.
> - **Referential integrity**:
>     - A foreign key (`FOREIGN KEY`) must reference an existing record in the primary table, preventing "dangling pointers".
> - **Domain integrity**:
>     - The data type and value range of each field (e.g., `CHECK`, `NOT NULL`, the data type itself).
> - **User-defined integrity**:
>     - Business rules set by the developer themselves (e.g., salary must be greater than 0).
>
> For example:
>
> ```sql
> CREATE TABLE Student (
>     ID INT PRIMARY KEY,               -- 实体完整性
>     Age INT CHECK (Age >= 0),         -- 域完整性
>     ClassID INT,
>     FOREIGN KEY (ClassID) REFERENCES Class(ID) -- 参照完整性
> );
> ```
>
> **Consistency constraints** usually refer to the rule that data must **satisfy all of the database's integrity constraints** before and after database operations — the database is in a "**consistent state**". It emphasizes that the overall state of the database does not contain illegal or conflicting data before and after a transaction executes.
>
> - It is not a "separate type of constraint", but rather **the combined result of multiple integrity constraints**.
> - Consistency constraints emphasize the maintenance of data consistency by **transaction operations**.
>
> ------
>
> |     Aspect     |                        Integrity Constraints                        |                          Consistency Constraints                          |
> | :------------: | :------------------------------------------------------: | :----------------------------------------------------------: |
> |    Conceptual nature    |                    A concrete rule mechanism                    |               A resulting state (whether all constraints are satisfied)               |
> |   Point in time   |          Constraint rules are defined when creating/altering tables and remain in effect           |        Usually judged before and after a transaction whether the database still satisfies integrity constraints        |
> | Can it be defined individually | Can be written explicitly (e.g., `PRIMARY KEY`, `CHECK`, `FOREIGN KEY`) |     Cannot be defined individually; it is an overall assessment of whether multiple integrity rules are violated     |
> |      Example      |            `CHECK (age >= 0)`, `FOREIGN KEY`             | Inserting a non-existent foreign key value breaks consistency (i.e., violates a specific integrity constraint) |
> |      Relationship      |                 Integrity constraints are **concrete rules**                 | Consistency is an **overall state result**; whether integrity constraints are "violated" determines whether consistency holds |

#### Creating a Relation Schema

Basic format:

```sql
CREATE TABLE r (
    A1 D1,
    A2 D2,
    ...
    An Dn,
    -- 完整性约束
    完整性约束1,
    完整性约束2,
    ...
);
```

#### Deleting a Relation Schema

```sql
drop table r
```

#### Modifying a Relation Schema

```sql
alter table r add A D
-- 添加一个名为 A 类型为 D 的字段，注意这里也是**类型后置**
alter table r drop A
-- 删除字段 A
```

```sql
delete from r
-- 保留关系 r，但是删除 r 中的所有 tuples
```

## SQL Queries

It's basically a complete guide to `SELECT` usage. There's not much to explain here; I feel you get it by writing more. I'll just note some key points as a summary.

```sql
select A from r where p
```

Equivalent to the relational algebra
$$
\Pi_{A}(\sigma_p(r))
$$
#### A Complete SQL Query Statement:

```sql
SELECT [DISTINCT|ALL] column_list
FROM table_list
[WHERE condition]
[GROUP BY group_columns]
[HAVING group_condition]
[ORDER BY sort_columns [ASC|DESC]]
[LIMIT n]   -- 有些方言如 MySQL 支持，限制查询数量
```

|    Clause    |                           Description                           |
| :--------: | :----------------------------------------------------------: |
| `DISTINCT` |                    Deduplicate, keeping only unique results.                    |
|   `ALL`    |                No deduplication, keep all results. (Default)                |
| `GROUP BY` | Grouping; categorizes results by a column, usually used with aggregate functions (e.g., `SUM`, `COUNT`). |
|  `HAVING`  | Filters the grouped results (similar to `WHERE`, but applied after grouping, **meaning `HAVING` must be used together with `GROUP BY`**). |
| `ORDER BY` |        Specifies the sort order of results (ascending `ASC` / descending `DESC`).        |
|  `LIMIT`   | Limits the number of rows returned (e.g., `LIMIT 10` returns at most 10 rows). **Only supported by some dialects**. |

#### The `AS` Keyword

A keyword for **defining aliases**, used to give a **column name or table name** a temporary new name, making query results more readable.

#### Strings

String constants are enclosed in single quotes.

When a string contains a single quote, it must be doubled:

```sql
SELECT 'Hello World'; -- 正常字符串
SELECT 'It''s OK';     -- 字符串中包含单引号
```

#### `CASE`

Used for conditional branching

```sql
CASE
    WHEN 条件1 THEN 结果1
    WHEN 条件2 THEN 结果2
    ...
    ELSE 默认值
END
```

#### The `LIKE` Operator

Matches using wildcards:

| Wildcard |              Function              |                             Example                             |
| :----: | :----------------------------: | :----------------------------------------------------------: |
|  `%`   | Matches a substring of any length (including the empty string) | `'A%Z'` matches `'AZ'`, `'%A%Z%'` matches `'天下トーイツA to Z☆'` |
|  `_`   |        Matches any single character        |                    `'A_Z'` matches `'ABZ'`                    |

If you need to match `_` or `%` themselves, use the `ESCAPE` keyword to define an escape character:

```sql
-- 查找包含文字 "ab%cd%" 的字段
SELECT col
FROM table
WHERE col LIKE 'ab#%cd#%' ESCAPE '#';
-- # 是自定义的转义字符，这样 #% 就会被解释为实际的 % 字符，而不是通配符。
```

**SQL has no built-in escape character; users must define their own**

#### Concatenating Strings

Use `||`.

#### Case Conversion

`LOWER()` `UPPER()`

#### Data Duplication

In standard relational algebra, **relations are sets** and duplicate tuples are not allowed; but in SQL, the default query result is a **multiset**, also called a **bag**, which allows duplicates.

```sql
SELECT branch_name FROM loan;

-- 如果表 loan 中有多个贷款来自同一家银行，比如 "Perryridge" 出现了 3 次，那么这个查询结果就会返回 3 个 "Perryridge"，不会自动去重。
-- 只有使用 DISTINCT 关键字才会去重
```

#### Multi-Relation Queries

Let me explain `from` here: without a `where`, a huge Cartesian product is generated, which performs poorly. Generally, filtering first and then joining performs much better.

#### Predicates in where

```sql
where salary between 9000 and 11000
```

Equivalent to

```sql
where salary <= 11000 and salary >= 9000
```

The above is clearer.

**`<>` means not equal!!! Not `!=`**

#### Tuple Unpacking / Matching

SQL supports tuple matching similar to Python

```sql
where (instructor.ID, dept name) = (teaches.ID, 'Biology');
```

Equivalent to

```sql
where instructor.ID= teaches.ID and dept name = 'Biology';
```

This syntax can be used in `where (...) in cte`, which is very handy.

#### Set Operations

SQL's **set operations** (`UNION`, `INTERSECT`, `EXCEPT`) deduplicate by default like mathematical sets, but also provide `ALL` versions to keep duplicates.

Usage example:

```SQL
SELECT ... FROM R
UNION -- 换成 INTERSECT EXCEPT都可以
SELECT ... FROM S
```

If you want to keep duplicates, you must explicitly use the `ALL` keyword.

|      Operation       |                         Explanation                         |
| :-------------: | :--------------------------------------------------: |
|   `UNION ALL`   |                   Keeps all duplicate results                   |
| `INTERSECT ALL` | Keeps duplicates with count equal to the **minimum** number of occurrences of the same tuple in the two sets |
|  `EXCEPT ALL`   |                Removes occurrences **one by one**                |

For example, given two query results:

- Query 1 returns `{a, a, b}`
- Query 2 returns `{a, b, b}`

|      Operation       |       Result        |                         Explanation                          |
| :-------------: | :---------------: | :---------------------------------------------------: |
|     `UNION`     |     `{a, b}`      |                       Merge with deduplication                        |
|   `UNION ALL`   | `{a, a, a, b, b}` |                     Keep all duplicates                      |
|   `INTERSECT`   |     `{a, b}`      |               Both `a` and `b` appeared; deduplicated               |
| `INTERSECT ALL` |     `{a, b}`      |               The minimum count of `a` is 1, and of `b` is 1                |
|    `EXCEPT`     |       `{}`        |            Both `a` and `b` appear in both; all removed             |
|  `EXCEPT ALL`   |       `{a}`       | Two `a`s are kept (`a` appears twice in the first, once in the second; the difference is kept) |

#### Handling of null

Any arithmetic operation involving null yields null.

Comparisons involving null cause problems, so SQL introduces a third logical value: **`unknown`**

| **Operator (AND)** | **TRUE**    | **FALSE** | **UNKNOWN** |
| ---------------- | ----------- | --------- | ----------- |
| **TRUE**         | TRUE        | FALSE     | **UNKNOWN** |
| **FALSE**        | FALSE       | FALSE     | **FALSE**   |
| **UNKNOWN**      | **UNKNOWN** | **FALSE** | **UNKNOWN** |

| **Operator (OR)** | **TRUE** | **FALSE**   | **UNKNOWN** |
| --------------- | -------- | ----------- | ----------- |
| **TRUE**        | TRUE     | TRUE        | **TRUE**    |
| **FALSE**       | TRUE     | FALSE       | **UNKNOWN** |
| **UNKNOWN**     | **TRUE** | **UNKNOWN** | **UNKNOWN** |

- **AND**: like "fault-finding"; as long as there is a `FALSE`, the result is `FALSE`; if there is no `FALSE` but there is an `UNKNOWN`, the result is `UNKNOWN`.
- **OR**: like "looking for highlights"; as long as there is a `TRUE`, the result is `TRUE`; if there is no `TRUE` but there is an `UNKNOWN`, the result is `UNKNOWN`.
- **UNKNOWN**: it is like a black hole; unless it encounters a `FALSE` (in AND) or `TRUE` (in OR) that can directly determine the result, it keeps the result `UNKNOWN`.

#### Aggregate Functions

SQL provides some aggregate functions, which operate on a group of data and return a **single value**:

|    Function    |         Meaning          |
| :--------: | :-------------------: |
|  `AVG(x)`  |        Average         |
|  `MIN(x)`  |        Minimum         |
|  `MAX(x)`  |        Maximum         |
|  `SUM(x)`  |         Sum          |
| `COUNT(*)` | Total number of rows (including `NULL`) |
| `COUNT(x)` |  Number of non-`NULL` values   |

`GROUP BY` groups results by fields, usually used together with aggregate functions

```sql
SELECT branch_name, AVG(balance)
FROM account
GROUP BY branch_name;

-- 每个 branch_name 是一个组
-- 每组分别计算平均 balance
```

The `HAVING` clause filters the grouped results:

```sql
SELECT branch_name, AVG(balance)
FROM account
GROUP BY branch_name
HAVING AVG(balance) > 1200;

-- 首先 GROUP BY 将 account 表按 branch_name 分组
-- 再用 HAVING 过滤掉平均余额不大于 1200 的组
```

### Nested Subqueries

> A subquery is a **select-from-where** expression that is nested within another query. A common use of subqueries is to perform tests for set membership, make set comparisons, and determine set cardinality by nesting subqueries in the where clause.

e.g.

```sql
SELECT ...
FROM ...
WHERE 某列 OPERATOR (SELECT ... FROM ... WHERE ...);

-- 其中的 (SELECT ...) 就是一个 子查询。
```
#### For Implementing Set Operations

This point is important: if a requirement **takes the form of a set operation, it can be solved with nested queries**.

```sql
select distinct course_id
from section
where semester = 'Fall' and year = 2017 and
course_id in (
	select course_id
    from section
    where semester = 'Spring' and year = 2018
)
```

This step can actually also be implemented with intersect:

```sql
(select course_id
from section
where semester = 'Fall' and year = 2017)
intersect
(select course_id
from section
where semester = 'Spring' and year = 2018
)
```

If you change `in` to `not in`, it becomes `except`.

#### some all exists unique

"greater than at least one": in SQL, use `some`:

```sql
select name
from instructor
where salary > some (
    select salary
    from instructor
    where dept_name = 'Biology'
)
```

`< > <= >= = <>` can all be combined with `some`. Among them, `= some` is equivalent to `in`, while `<> some` is **not equivalent** to `not in`.

"greater than all": in SQL, use `all`:

```sql
select name
from instructor
where salary > all (
    select salary
    from instructor
    where dept_name = 'Biology'
)
```

Following the same rule as `some`, among them `<> all` is equivalent to `not in`, while `= all` is **not equivalent** to `in`.

`exists` is used to check whether the result of a subquery is non-empty (exists)

```sql
-- 找出既有存款又有贷款的顾客
SELECT DISTINCT customer_name
FROM borrower AS R
WHERE EXISTS (
    SELECT *
    FROM depositor AS S
    WHERE S.customer_name = R.customer_name
);
```

Of course, there is also `not exists`.

`unique` is used to check whether the result of a subquery contains duplicate tuples; if it does, it returns `FALSE`, and otherwise `TRUE`. **It returns TRUE even when the result is empty**.

One application scenario is using `not unique` to find attributes that appear more than 2 times

```sql
-- 找出在 Perryridge 有多个存款账户的顾客
SELECT T.customer_name
FROM depositor AS T
WHERE NOT UNIQUE (
    SELECT R.customer_name
    FROM account AS S, depositor AS R
    WHERE T.customer_name = R.customer_name
      AND R.account_number = S.account_number
      AND S.branch_name = 'Perryridge'
);
```

**Here you can see that a subquery can access relations from the outer layer.**

> Modern SQL rarely uses `UNIQUE`; `GROUP BY` + `HAVING` is used more often. For example, for the case above:
>
> ```sql
> SELECT customer_name
> FROM depositor D, account A
> WHERE D.account_number = A.account_number
>   AND A.branch_name = 'Perryridge'
> GROUP BY customer_name
> HAVING COUNT(*) > 1;
> ```

#### Subqueries in the From Clause

```sql
SELECT ...
FROM (SELECT ... FROM ...) AS 别名(列名1, 列名2, ...)

-- 也可以写成：

SELECT ...
FROM (SELECT ... FROM ...) AS 别名
```

**You must give the subquery an alias, otherwise an error will be thrown**

#### with Subqueries

Makes nested subqueries more elegant to write

#### Scalar Subqueries

> the subquery returns only one tuple containing a single attribute; such sub-queries are called scalar subqueries.

- That is: containing only one row and one column

```sql
select dept_name,
        (select count(*)
          from instructor
          where department.dept_name = instructor.dept_name)
        as num_instructors
from department;
```

**Using a scalar subquery for a single computation**

```sql
(select count (*) from teaches) / (select count (*) from instructor);
-- 在某些数据库中会由于没有 from 语句而报错
select (select count (*) from teaches) / (select count (*) from instructor) from dual;
-- 提供了一个 dummy relation 来提供 from 语句且不产生其他副作用
```

> Here `dual` is a dummy relation, one row and one column, that always exists.

## Modification of the Database

### deletion

```sql
DELETE FROM 表名
[WHERE 条件];
-- 如果忽略掉 WHERE 子句就会把整张表的内容全删了，只留下框架
```

Below are some more specific delete examples:

```sql
delete from instructor
where dept_name = 'finance'
```

```sql
-- 下面是一个典型的`where xxx in cte`的应用场景
delete from instructor
where dept_name in 
(select dept_name
from department
where building = 'Watson'
)
```

```sql
delete from instructor
where salary < (select avg (salary)
from instructor);
```

Syntax for multi-table join deletion:

```sql
delete from owns
where driver_id = '12345'
  and license_plate in (
    select license_plate 
    from car 
    where year = 2010
  );
```

### insertion

```sql
INSERT INTO 表名 VALUES (值1, 值2, 值3, ...);

-- 也可以用下面更清晰的写法，显式指定列名：

INSERT INTO 表名 (列1, 列2, 列3, ...)
VALUES (值1, 值2, 值3, ...);
```

**You can use the `insert into select` clause to insert multiple tuples:**

```sql
-- 给 Perryridge 分行的所有存在贷款的客户送$200，并新建账户
insert into account
select loan_number, branch_name, 200
from loan
where branch_name = 'Perryridge'
```

Inserted data must satisfy the following conditions:

- **The number of columns and the specified types must match**
- The primary key uniqueness constraint must be satisfied, **ensuring the primary key is not duplicated**

For **unspecified columns**, the insertion behaves as follows:

- If a default value is defined, the default value is inserted into the current column
- Otherwise, it is assigned a null value `NULL`

### updates

```sql
UPDATE 表名
SET 列名 = 新值
[WHERE 条件];

-- 如果省略 WHERE 语句，则会更新整张表的所有记录
```

For example

```sql
update account
set balance = case
	when balance <= 10000 then balance * 1.05
	else balance * 1.06
end;
```

# Chapter 4 Intermediate SQL

## Join Expressions Revisited

### natural join

Requires all identically named attributes to be equal

```sql
select name, course_id
from student natural join takes;
```

In essence:

1. Find the identically named columns
2. Filter out rows where the values of the identically named columns are not equal
3. Keep only one of the two identically named columns

### Join Conditions

You can use `on`, which is simple and won't be discussed here.

`on` has a syntactic sugar, `join ... using`, for example:

```sql
select *
from student join course_id using(id)
```

Only the attribute inside `using()` is used to judge during the join, unlike `natural join`, which requires all identically named attributes to be equal when there are multiple of them.

### outer join

```sql
select *
from student natural join takes;
```

A natural join discards rows where `takes.id <> student.id`; for `ID`s that exist in only one table, since no matching value can be found in the other table, they are also discarded. But in real-world requirements, we want to display students who haven't enrolled in courses as well, so an outer join is needed here.

It is divided into:

- left outer join
- right outer join
- full outer join

This part was actually covered earlier, so it won't be discussed here.

**When using an outer join, it's best to first fully filter the conditions in two subqueries and perform the outer join as the last step**. This is because if the outer join is not the last step, a where operation will be performed after the outer join, and in the where operation, anything containing `null` will not evaluate to `True` and will be filtered out, making the outer join pointless.

## Views

A view is a virtual table, a table defined by the result of an SQL query statement. **A view itself does not store data; it depends on the data of the underlying tables.**

A view is essentially an alias / encapsulation of a query. When a view is used in a query, the SQL engine does not directly read data from some table; instead, it expands the view's definition into the original query statement and then executes it. This is called **view expansion**. If a view contains other views, the expansion is **recursive**.

```sql
create view 视图名 as
select ...
from ...
......
```

After a view is defined, it can be used anywhere just like an ordinary table.

- **The data in a view is dynamic: every time the view is queried, the system executes the query statement behind it.**
- **For complex queries that are used frequently, views can improve development efficiency, but do not overuse them (especially in high-performance scenarios).**

**Updating views**: not recommended.

## Transactions

A transaction: a user-defined **sequence of operations**. All operations in this sequence either all execute successfully or none execute at all.

The four major properties of transactions:

|      Meaning      |  Property  |                                                              |
| :-------------: | :----: | ------------------------------------------------------------ |
|  **A**tomicity  | Atomicity | All operations in a transaction are a whole, **indivisible**; either all execute successfully or all fail. |
| **C**onsistency | Consistency | Before and after a transaction executes, the database is in a **consistent state**, without violating the data's integrity constraints. |
|  **I**solation  | Isolation | When multiple transactions execute concurrently, their operations **do not interfere with each other**. For example, if A is transferring money, B cannot see the intermediate process. |
| **D**urability  | Durability | Once a transaction is committed, the changes it made **take effect permanently**, and can be recovered even after a power failure or crash. |

Abbreviated as **ACID**.

The syntax of a transaction:

```sql
begin atomic
	-- 一组语句
	update ...;
	insert ...;
end;
```

After the transaction is defined, execute

```sql
commit;
```

If any statement in the transaction fails during execution, execute

```sql
rollback;
```

to roll back, returning to the initial state.

## Integrity Constraints

### Constraints on a Single Relation

- `not null`: no need for much explanation.
- `unique`: means the value of a field (or combination of fields) **must be unique** (`NULL` values are allowed). Usually used to define **candidate keys**.
- `check`: used to specify that a certain **logical condition** must hold; **does not support using a `select` subquery as the condition**

```sql
CREATE TABLE Employees (
    EmployeeID int PRIMARY KEY,
    
    -- 1. NOT NULL 约束：姓名不能为空
    Name varchar(50) NOT NULL,
    
    -- 2. UNIQUE 约束：身份证号不能重复，但可以有一个人为 NULL（取决于数据库实现）
    ID_Card varchar(18) UNIQUE,
    
    -- 3. CHECK 约束：限制年龄范围
    Age int CHECK (Age >= 18 AND Age <= 65),
    
    -- CHECK 约束：限制性别只能是特定的值
    Gender varchar(10) CHECK (Gender IN ('Male', 'Female', 'Other'))
);
```

### Referential Integrity

Used for **cross-table constraints**, ensuring that a field in one table references data that already exists in another table.

#### Implicit Reference

`foreign key (dept_name) references department`

Here `dept_name` is an Attribute of the Schema currently being defined, and `department` is another Relation.

Underlying behavior: when you omit the attribute names in the parentheses, the SQL standard specifies that the foreign key must reference the **Primary Key** of the referenced table.

That is: `now.dept_name` must exist in the primary key of `department`.

#### Explicit Reference

`foreign key (dept_name) references department(dept_name)`

Underlying behavior: the target column (dept_name) does not have to be the primary key, but it must have a uniqueness constraint or be the primary key itself. That is, it must be a **Superkey**.

> **Recall the concept of a super key**:
>
> Any attribute set that can **uniquely** identify a tuple in a relation is a super key.

That is: `now.dept_name` must exist in `department.dept_name`.

**Cascade operations** are used to automatically propagate updates or deletions:

```sql
FOREIGN KEY (branch_name) REFERENCES branch(branch_name)
ON DELETE CASCADE
ON UPDATE CASCADE
```

Meaning:

- `ON DELETE CASCADE`: if the branch is deleted, the contents of that branch are also automatically deleted;
- `ON UPDATE CASCADE`: if the branch name is modified, the names in tables referencing it are automatically updated as well.

### Assigning Names to Constraints

```sql
-- 使用 constraint 关键字命名该限制
salary numeric(8,2), constraint minsalary check (salary > 29000),
-- 删除该限制
alter table instructor drop constraint minsalary;
```

### Assertions

Assertions are not well supported in mainstream databases, so they won't be discussed here.

## Advanced Data Types

### Built-in Data Types

Besides the **basic data types**, SQL also supports some other types, for example:

|    Type     |             Meaning             |          Example           |
| :---------: | :---------------------: | :---------------------: |
|   `DATE`    |     Represents a date (year-month-day)     |     `'2025-04-29'`      |
|   `TIME`    |     Represents a time (hour:minute:second)     |      `'14:30:00'`       |
| `TIMESTAMP` | Represents a full date and time (with milliseconds) | `'2025-04-29 14:30:00'` |

Use `extract(field from d)` to extract the corresponding field, where `field` can be `year`, `month`, `day`, `hour`, `minute`, `second`.

### Big Object Types

|  Type  |               Meaning               |            Used for            |
| :----: | :------------------------------: | :------------------------: |
| `BLOB` |  Binary Large Object (byte stream)   |  Binary data, such as images and audio  |
| `CLOB` | Character Large Object (character stream) | Text data, such as documents and large blocks of text |

### User-Defined Types

**Only supported by some SQL implementations**

```sql
CREATE TYPE Dollars AS NUMERIC(12, 2) FINAL;
```

`FINAL` means the type cannot be inherited or extended.

### Type Conversion (cast)

SQL provides the `CAST()` function to explicitly convert a value to another data type:

```sql
CAST(expression AS target_type)
```

### Null Coalescing (coalesce)

Syntax: `coalesce(arg1, arg2, ...)`
Logic: physically scans the argument list and returns the first non-`null` value. All arguments are required to have physically consistent types.

```sql
-- 如果 salary 是 null，物理替换为 0 以便后续数学运算
select ID, coalesce(salary, 0) as actual_salary
from instructor;
```

### decode

**Oracle-specific**

Syntax: `decode (value, match-1, replacement-1, match-2, replacement-2, …, match-N, replacement-N, default-replacement);`

```sql
select ID, decode (salary, null, 'N/A',salary) as salary
from instructor
```

### default value

```sql
create table student
    (ID varchar (5),
    name varchar (20) not null,
    dept_name varchar (20),
    tot_cred numeric (3,0) default 0,
    primary key (ID));
```

### SQL Type System

SQL's type system is weakly typed, which means:

- SQL **automatically performs implicit conversions**, such as automatically converting the string `'123'` to an integer;
- Type conflicts do not necessarily cause compilation errors (e.g., comparing `VARCHAR` with `INT` may be feasible);
- Some databases (such as MySQL) even allow inserting data of the wrong type (e.g., inserting letters into a numeric field).

Therefore, important fields should have their types made explicit using methods such as `CAST()` or `DOMAIN`.

## Authorization

There are several kinds of privileges: select, insert, update, delete.

### Granting / Revoking Privileges

The `grant` statement is used to grant privileges; the basic syntax form is:

```sql
grant <privilege list>
on <name of realations or views>
to <users or roles>
```

e.g.

```sql
grant select on department to Amit, Satoshi;
```

```sql
grant update(budget) on department to Amit,Satoshi;
```

If the username is `public`, it is equivalent to granting to all users.

To revoke privileges, use `revoke`; the syntax is basically the same as `grant`.

### role

Essentially a syntactic sugar

```sql
create role instructor;
grant select on takes to instructor;
create role dean;
grant instructor to dean; -- 可以给角色也可以给用户
grant dean to Satoshi;
```

### Authorization on Schemas

`grant references(dept_name) on department to Mariano;`

This is mainly to satisfy foreign key constraints and `check` constraints.

Honestly, I don't quite understand this; I think it will make sense once it's actually used.)

### Transfer of Privileges

```sql
grand select on department to Amit with grant option;
```

`with grant option` grants Amit the privilege to authorize others.

### Revocation of Privileges

By default, revocation is cascaded, meaning that if the upstream is cut off, the downstream is cut off too.

If you do not want cascaded revocation, use `restrict`

```sql
revoke select on department from Amit, Satoshi restrict
```

However, this is often inappropriate in real life, so SQL allows authorization through roles rather than through users.

# Chapter 5 Advanced SQL

## Accessing SQL from a Programming Language

It seems to mainly cover Java, but it probably won't be tested much. For the sake of a quick review, this part is skipped for now; just a few words — **TODO**

**JDBC**: an API provided by Java for connecting to database servers.

**ODBC**: the **Open Database Connectivity** standard defines an API that applications can use to open a connection with a database, send queries and updates, and get back results.

## Functions and Procedural Constructs

The modular programming part of SQL includes:

- **Functions**: have a return value, suitable for direct invocation in queries
- **Procedures**: no return value, but can pass information in/out through parameters, suitable for complex data manipulation workflows
- **Triggers**: no return value; a piece of code that executes automatically when certain events (such as insert, update, delete) occur on a table

Each is expanded below.

### Functions

Main characteristics:

- Have a return value
- Generally used in queries; can be called directly in `SELECT` statements
- Cannot perform modifications on the database, such as `insert`, `update`

Example: given a customer's name, return the number of deposit accounts they own:

```sql
create function account_count(customer_name varchar(20))
returns integer -- 返回值后置
begin
	declare account integer; -- 声明变量
	select count(*) into account
	from depositor
	where depositor.account_name = customer_name;
	return account
end;
```

How to call it:

```sql
select customer_name, customer_street
from customer
where account_count(customer_name) > 1
```

### Procedures

Main characteristics:

- No return value
- Can pass information in and out through parameters
- Can **modify database contents**, and can also perform queries
- Suitable for encapsulating complex logic and batch processing operations

Example: given a customer's name, return the number of deposit accounts they own:

```sql
create procedure account_count_proc (
	in customer_name varchar(20)
    out a_count integer
    -- in 和 out 分别为传入和传出的参数
)
begin
	select count(*) into a_count
	from depositor
	where depositor.account_name = customer_name
end;
```

Invocation:

```sql
declare a_count integer;
call account_count_proc('Smith', a_count);
```

### Triggers

Main characteristics:

- No return value
- No manual invocation needed; triggered automatically by the DBMS
- Can be bound to `INSERT`, `UPDATE`, `DELETE`
- Each trigger is associated with a specific table and operation type

Example: when a user is inserted, the `created_at` field is automatically set to the current time:

```sql
create trigger before_insert_user
before insert on users 
referencing new row as nrow
referencing old row as orow	
-- before 指定触发时机。在执行 insert 操作之前运行
for each row -- 行级触发
begin
	set nrow.created_at = NOW()
	-- NEW 代表即将被插入的那一行
end
```

### Procedural Constructs

SQL introduces control flow structures similar to programming languages, i.e., procedural constructs, such as:

- Loops
- Branches
- Compound statements

These structures make SQL not just a query language, but also capable of implementing complex logic control.

Its features include:

- **Support for control structures**: such as `if-then-else`, `while`, `repeat`, etc.
- **Composable statement blocks**: use `begin...end` to contain multiple statements
- **Can be used in stored procedures, triggers, and other** modules
- **Support for variable declaration and assignment**
- Belongs to **persistent storage modules**: code can be saved in the database and used long-term

#### Loop Statements

- `while` loop

```sql
declare n integer default 0;
while n < 10 do
    set n = n + 1;
end while;
-- 当满足条件时重复执行
```

- `repeat` loop

```sql
declare n integer default 10;
repeat
    set n = n - 1;
until n = 0
end repeat;
-- 先执行，后判断，直到满足条件为止
```

- `for` loop

```sql
declare n integer default 0;
for r as select balance from account
where branch name = 'Perryridge'
do
	set n = n + r.balance;
end for
```

#### Branch Statements

```sql
if r.balance < 1000 then
    set l = l + r.balance;
elseif r.balance < 5000 then
    set m = m + r.balance;
else
    set h = h + r.balance;
end if;
```

#### Compound Statements

SQL requires that only a single statement be written in many places, but general logic often requires writing many statements. In such cases, you can use `BEGIN...END` to combine them into a single statement.

It is equivalent to the use of curly braces `{}`.

```sql
begin
    -- 声明变量、赋值、条件判断、循环等都可以写在这里
end;
```

## Recursive Queries

Recursive queries are used to query hierarchical / multi-level dependency data. Any recursive query consists of two parts:

1. The base query
2. The recursive query

Connected using `UNION`.

Example: find all superiors of an employee

```sql
WITH RECURSIVE empl(employee_name, manager_name) AS (
    -- 基查询：直接管理关系
    SELECT employee_name, manager_name FROM manager

    UNION

    -- 递归查询：间接管理关系
    SELECT m.employee_name, e.manager_name
    FROM manager m, empl e
    WHERE m.manager_name = e.employee_name
)

SELECT * FROM empl;
```

LLM explanation:

> This SQL code uses a **Recursive Common Table Expression (Recursive CTE)**. Its core purpose is to handle **hierarchical structures** (such as company organizational charts, family trees, file directories, etc.) and find all direct and indirect management relationships.
>
> We can break this code down into three main parts: the **base query (Anchor)**, the **recursive query (Recursive)**, and the **termination condition**.
>
> ------
>
> ### 1. Structural Analysis
>
> #### **A. Definition part (`WITH RECURSIVE empl(...)`)**
>
> This line defines a virtual temporary table `empl`. It has two fields: `employee_name` (employee) and `manager_name` (manager).
>
> #### **B. Base Query (Anchor Member)**
>
> SQL
>
> ```sql
> SELECT employee_name, manager_name FROM manager
> ```
>
> - **Purpose**: This is the starting point of the recursion. It first extracts all **direct reporting relationships** (the first level) from the original table `manager`.
> - **Result**: For example, if the table has a row `(张三, 李四)`, it means Li Si is Zhang San's direct superior.
>
> #### **C. Recursive Query (Recursive Member)**
>
> SQL
>
> ```sql
> SELECT m.employee_name, e.manager_name
> FROM manager m, empl e
> WHERE m.manager_name = e.employee_name
> ```
>
> - **Logic**: It joins the original table `manager` (m) with the temporary table `empl` (e) that we are building.
> - **Join condition**: `m.manager_name = e.employee_name`.
>     - Meaning: if A's superior is B, and B is in turn a subordinate of C, then A is also a subordinate of C.
> - **Purpose**: Each round of recursion searches one more level up based on the previous level. The first round finds "the superior's superior," the second round finds "the superior's superior's superior," and so on.
>
> #### **D. Final Query**
>
> SQL
>
> ```sql
> SELECT * FROM empl;
> ```
>
> - Outputs the results of all levels (the base query's results + the results of all recursive rounds) merged together.
>
> ------
>
> ### 2. How does it work? (An example)
>
> Suppose the `manager` table contains the following data:
>
> | **employee_name** | **manager_name** |
> | ----------------- | ---------------- |
> | Xiao Wang              | Lao Li             |
> | Lao Li              | Lao Zhang             |
> | Lao Zhang              | The Big Boss           |
>
> **Recursive execution process:**
>
> 1. **Step 1 (base query)**:
>
>     Find the direct relationships: `(小王, 老李)`, `(老李, 老张)`, `(老张, 大老板)`.
>
> 2. **Step 2 (first round of recursion)**:
>
>     The system discovers: Xiao Wang's superior is "Lao Li," and "Lao Li" is in turn a subordinate of "Lao Zhang."
>
>     Result adds: `(小王, 老张)`.
>
>     Similarly adds: `(老李, 大老板)`.
>
> 3. **Step 3 (second round of recursion)**:
>
>     The system discovers: Xiao Wang's indirect superiors now include "Lao Zhang," and "Lao Zhang" is in turn a subordinate of "The Big Boss."
>
>     Result adds: `(小王, 大老板)`.
>
> 4. **Step 4 (end)**:
>
>     No new management relationships can be derived; the recursion stops.
>
> ------
>
> ### 3. The significance of this query
>
> Without recursive queries, you could only find out "who is whose direct supervisor." If you want to find out "**who are all the superiors of this employee** (**including grandparent-level and great-grandparent-level leaders**)", it would be very cumbersome in traditional SQL.
>
> **Summary of this query's functionality:**
>
> - **Flattening hierarchies**: converts a tree structure into a path list.
> - **Full path search**: no matter how deep the company's management hierarchy is (5 levels or 50 levels), this query can automatically trace to the top.
>
> ### Tip
>
> In some databases (such as MySQL 8.0+ or PostgreSQL), recursive queries need to avoid **infinite loops**. If A manages B and B also manages A, the recursion will go on forever. In production environments, a `DEPTH` limit or loop-detection logic is usually added.

## Advanced Aggregation Features

### Window Functions

This part doesn't actually follow the textbook order; it's knowledge I learned from the CMU-15-445 online course, but I think it's very important.

Format:

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

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

Inside `OVER()` you write `PARTITION BY` or `ORDER BY`.

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

Let's take an example: **"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)

```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;
```

Window functions have excellent performance.
