Relational algebra and SQL
แนะนำใหม่
6:35
ฐานข้อมูล
A database is a set of true sentences about a domain. This course shows how to model, query, protect and govern data. The first three units model and shape it…
บรรยายภาษาอังกฤษ · สลับคำบรรยายภาษาอังกฤษและภาษาจีนได้
ในบทเรียนนี้
| English | ความหมาย |
|---|---|
| Relational algebra/rɪˈleɪʃənl ˈældʒɪbrə/ | the set of operations on tables (select, project, join, union, difference) that queries are built from |
| Selection/sɪˈlekʃn/ | Choosing instructions by a condition; in relational algebra, choosing rows that satisfy a condition. |
| projection/prəˈdʒekʃn/ | โปรเจกชัน |
| join/dʒɔɪn/ | การเชื่อมต่อ (join) |
| anti-join/ˈænti dʒɔɪn/ | the rows of one table that have no matching row in another |
| window function/ˈwɪndəʊ ˈfʌŋkʃn/ | an SQL function computed over a group of rows that keeps every row in the output, such as RANK() OVER (...) |
| three-valued logic/θriː ˈvæljuːd ˈlɒdʒɪk/ | logic with true, false and unknown, which SQL uses for NULL |
Five operators, one pipeline
- Relational algebra 关系代数 has five basic operators. Selection 选择 σ keeps rows, projection 投影 π keeps columns and join 连接 ⋈ combines tables on a condition. Union and difference combine whole tables.
- Every SELECT query is these operators in a pipeline.

The operator that keeps columns is —
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Projection pi keeps the chosen columns; selection sigma keeps rows.
The order of the clauses has meaning
- FROM builds the set of rows, WHERE filters rows, GROUP BY splits them into groups, HAVING filters groups, SELECT chooses columns and ORDER BY sorts. Filtering on an aggregate in WHERE makes no sense, and the engine rejects it: use HAVING.
- The course query: join 连接 Course and Enrollment, keep credits = 15, group by title, and keep groups of size $\ge 2$. On the sample schema the result is
Databases | 3.
Filtering on COUNT(*) happens in —
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
WHERE filters rows before grouping; HAVING filters the groups.
The kind of join decides which rows stay
- A plain join 连接 drops the 2 courses with no enrolment;
LEFT JOINkeeps them withn = 0, giving 6 rows.COUNT(*)counts rows;COUNT(col)skips NULLs. - Projecting a column from the many side repeats values: 14 enrolment rows give 14 student ids. Add DISTINCT when you want the set.
Read every query as a pipeline, and its output will stop surprising you.
The course query on the sample schema returns —
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
One 15-credit course has 3 enrollments; Algorithms is 12 credits.
Subqueries, anti-joins and sets
- "Which courses have no enrolment?" is an anti-join 反连接:
SELECT title FROM Course c WHERE NOT EXISTS (SELECT 1 FROM Enrollment e WHERE e.course_id = c.course_id)returns the $2$ empty courses.NOT INgives the same answer only when the subquery returns no NULLs. - Set operators need matching columns.
UNIONremoves duplicates,UNION ALLkeeps them, andEXCEPTis the algebra's difference. An inner join of Course with Enrollment, grouped by course, gives $4$ groups: the two empty courses disappear.
On the sample schema (6 courses, 2 with no enrollment), how many rows does an inner join of Course and Enrollment grouped by course return?
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
The inner join keeps only the 4 courses with enrollments, one group each.
UNION keeps duplicate rows from its two inputs.
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
UNION removes duplicates; UNION ALL keeps them, and is cheaper because it skips the check.
Aggregates that keep every row
GROUP BYturns the rows of each group into one row. A window function 窗口函数 computes over a group but keeps every row:RANK() OVER (PARTITION BY dept_id ORDER BY credits DESC)ranks each course inside its department.- "Top course per department" is then a filter on rank 1. Window functions also give running totals and moving averages without joining a table to itself.
Which keeps one output row for every input row?
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Window functions compute over a partition without collapsing it.
Worked example: NULL is not a value
- Of 14 enrolments, 4 have grade
'A'and 3 have no grade yet (NULL).WHERE grade <> 'A'returns 7 rows, not 10: for NULL the comparison is unknown, and WHERE keeps only rows where it is true. - SQL uses three-valued logic 三值逻辑. To include the ungraded rows, write
WHERE grade <> 'A' OR grade IS NULL: $\mathbf{10}$ rows.NULL = NULLis also unknown, so test withIS NULL.
14 rows: 4 graded A, 3 with NULL grade, the rest other grades. Rows returned by WHERE grade <> 'A'?
ความยาก 2/5 · 140 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
$14 - 4 - 3 = 7$: NULL rows are unknown, not true.
WHERE grade = NULL finds the ungraded rows.
ความยาก 1/5 · 100 เหรียญ + บอนัสน้อยๆ เมื่อทำสำเร็จครั้งแรกในวันนี้
Any comparison with NULL is unknown; use IS NULL.
Marks that slip away
- An aggregate in WHERE. WHERE runs before grouping; filter groups with
HAVING COUNT(*) >= 2. COUNT(*)after a LEFT JOIN 连接. It counts the NULL row as $1$;COUNT(e.student_id)gives $0$ for an empty course.NOT INwith a NULL. If the subquery returns a NULL,NOT INmatches nothing.NOT EXISTSis safe.
Recap
- Each operator has its SQL clause:
| Operator | Does | In SQL |
|---|---|---|
| σ select | keeps rows | WHERE |
| π project | keeps columns | SELECT list |
| ⋈ join 连接 | matches rows of two tables | JOIN … ON |
| ∪ and − | combine whole tables | UNION, EXCEPT |
- Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
LEFT JOINkeeps unmatched rows;COUNT(col)skips NULLs.
เกิดปัญหาอะไรขึ้น? เฉพาะทีมเว็บไซต์เท่านั้นที่เห็นข้อมูลนี้