Sub topic 11
Relational Algebra, Safe Calculus, and SQL
Assume you know basic set operations, first-order logic, tables, and simple SELECT statements. This chapter connects relational algebra, tuple relational calculus, and SQL. It also explains why duplicate rows and NULL values can change an SQL answer.
Relational algebra and safe calculus: equal expressive power
Relational algebra is a procedural query language. It describes the operations used to obtain a result, such as selection, projection, and join.
Tuple relational calculus is declarative. It describes the tuples that should appear in the result by using logical conditions.
For example, suppose:
Student(sid, sname, age)stores students.- We need the names of students older than 20.
Relational algebra applies selection first and projection second:
π_sname (σ_age > 20 (Student))The tuple-calculus version describes a result tuple t whose name matches a qualifying student:
{ t | ∃s ∈ Student
(s.age > 20 ∧ t.sname = s.sname) }The expression uses an existential quantifier. It says that there exists a tuple s in Student such that s.age > 20.
A calculus expression is safe when its result is finite and depends only on values found in the database or in the expression's fixed constants. An unsafe expression could try to return every value outside a relation, producing an unbounded result.
For the usual relational queries, relational algebra and safe tuple calculus have equal expressive power. Each query that can be written in one formalism can be translated into the other, although one form may be easier to read.
SQL basics: SELECT, WHERE, DISTINCT, and duplicates
SQL resembles relational algebra, but ordinary SQL uses bag semantics. A bag is a collection that can contain duplicates. Relational algebra normally uses set semantics, where each tuple appears at most once.
SELECT DISTINCT sname
FROM Student
WHERE age > 20;WHERE filters rows. SELECT chooses columns. DISTINCT removes duplicate result rows. Without DISTINCT, two older students with the same name produce two copies of that name.
| Relational idea | SQL construct | Important behavior |
|---|---|---|
| Selection | `WHERE` | Keeps rows satisfying the condition |
| Projection | `SELECT` columns | May keep duplicates |
| Set-style projection | `SELECT DISTINCT` | Removes duplicate rows |
SQL's duplicate behavior becomes more visible with joins. If one student matches three enrollment rows, a join can produce three result rows for that student. Apply DISTINCT only when the question asks for unique values.
Exercise
A table Student contains (1, 'Mira', 21), (2, 'Mira', 22), and (3, 'Noah', 19). How many rows do these queries return: SELECT sname FROM Student WHERE age > 20; and the same query with DISTINCT?
Show answer
The first query returns two rows, both containing Mira. The query with DISTINCT returns one row containing Mira.