Sub topic 3
Selection and Projection
Assume you know basic set operations, Cartesian products, and elementary logic. You should also be comfortable reading a relation as a set of tuples, where a tuple is one row and an attribute is one column.
Selection and projection are the two basic unary operators of relational algebra. A unary operator takes one relation as input.
Selection: filtering tuples
Selection chooses complete tuples that satisfy a condition. It is written with the Greek letter sigma:
\[ \sigma_{\text{condition}}(R) \]
For example, let Student(sid, sname, age) contain these tuples:
| sid | sname | age |
|---|---|---|
| 1 | Ana | 21 |
| 2 | Ben | 19 |
| 3 | Chen | 22 |
The expression
\[ \sigma_{\text{age} > 20}(\text{Student}) \]
returns Ana and Chen, but it keeps every attribute of their tuples. Selection is therefore similar to a SQL WHERE condition.
Projection: choosing attributes
Projection chooses specified attributes from every tuple. It is written with the Greek letter pi:
\[ \pi_{\text{attribute list}}(R) \]
The expression
\[ \pi_{\text{sname}}(\text{Student}) \]
returns only the sname attribute. In relational algebra, relations use set semantics, so duplicate projected tuples are removed.
Selection and projection can be combined. To find the names of students older than 20, first select the qualifying tuples and then project the names:
\[ \pi{\text{sname}}\left(\sigma{\text{age} > 20}(\text{Student})\right) \]
The order matters. Projection may remove an attribute needed by a later selection. For example, this expression is invalid because age is no longer available:
\[ \sigma{\text{age} > 20}\left(\pi{\text{sname}}(\text{Student})\right) \]
SQL translation
SQL uses WHERE for selection and the SELECT list for projection.
CREATE TABLE Student (
sid INTEGER,
sname TEXT,
age INTEGER
);
INSERT INTO Student VALUES
(1, 'Ana', 21),
(2, 'Ben', 19),
(3, 'Chen', 22);
SELECT DISTINCT sname
FROM Student
WHERE age > 20;DISTINCT is important here. Relational algebra removes duplicates automatically, but SQL normally uses bag semantics and preserves duplicate rows.
Exercise
Which relational algebra expression returns the sid values of students whose age is at least 21?
Show answer
πsid(σage ≥ 21(Student)).