Relational algebra and SQL
Introducido
6:35
Bases de datos
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…
Narración en inglés · subtítulos en inglés y 中文 que puedes cambiar
En esta lección
| English | Significado |
|---|---|
| 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/ | proyección |
| join/dʒɔɪn/ | unió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 |
Cinco operadores, una tubería
- El álgebra: selección σ mantiene filas, proyección π mantiene columnas, unión ⋈ combina bajo una condición, unión y diferencia combinan tablas. Cada SELECT son estos cinco en una tubería.


The operator that keeps columns is —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Projection pi keeps the chosen columns; selection sigma keeps rows.
El orden de las cláusulas es semántico
- FROM construye el conjunto de filas, WHERE filtra filas, GROUP BY particiona, HAVING filtra grupos, SELECT proyecta, ORDER BY ordena. Filtrar una agregación en WHERE es un error categorial que el motor rechaza — use HAVING.
- La consulta de curso: una Course con Enrollment, seleccione credits = 15, agrupe por title, mantenga grupos de tamaño $\ge 2$. Ejecutada en el esquema de muestra, el resultado es
Databases | 3.
Filtering on COUNT(*) happens in —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
WHERE filters rows before grouping; HAVING filters the groups.
El tipo de unión decide quién sobrevive
- Una unión simple descarta los 2 cursos sin matrícula;
LEFT JOINlos mantiene conn = 0— 6 filas.COUNT(*)cuenta filas;COUNT(col)omite NULLs. - Proyectar una columna del lado muchos repite valores: 14 filas de inscripción proyectan 14 IDs de estudiantes — agregue DISTINCT cuando se refiera al conjunto.
Lea cada consulta como una tubería y la salida deja de ser sorprendente.
The course query on the sample schema returns —
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
One 15-credit course has 3 enrollments; Algorithms is 12 credits.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
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?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
The inner join keeps only the 4 courses with enrollments, one group each.
UNION keeps duplicate rows from its two inputs.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
UNION removes duplicates; UNION ALL keeps them, and is cheaper because it skips the check.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
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?
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Window functions compute over a partition without collapsing it.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
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'?
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
$14 - 4 - 3 = 7$: NULL rows are unknown, not true.
WHERE grade = NULL finds the ungraded rows.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
Any comparison with NULL is unknown; use IS NULL.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
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.
Esta tarjeta es nueva, por eso aparece en inglés hasta que su traducción esté lista.
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.
¿Qué salió mal? Solo el equipo del sitio ve esta información.