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/ | 조인 |
| 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.
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.