Relational algebra is a set of operations on relations that produce new relations. Six fundamental operations: select (filter rows), project (pick columns), union, difference, Cartesian product, and rename. Join is derived from these. Every SQL query compiles down to a relational algebra expression.
Select (sigma) — filter rows
Selection picks tuples that satisfy a predicate. It does not change the schema, only the cardinality. In SQL this is the WHERE clause.
A natural join pairs tuples from two relations that agree on shared attribute names. An equi-join matches on a specified condition. The join is the workhorse of relational queries: it reconstructs information that normalization split across tables.
# Join in Python
users = [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]
orders = [{"uid": 1, "item": "book"}, {"uid": 2, "item": "pen"}, {"uid": 1, "item": "lamp"}]
result = [
{**u, **o}
for u in users
for o in orders
if u["id"] == o["uid"]
]
for r in result:
print(r['name'] + " -> " + r['item'])
Union and difference — set operations
Union combines tuples from two union-compatible relations (same schema). Difference returns tuples in the first relation but not the second. Both require matching attribute names and domains.
Scheme
; Union and difference on relations
(define r1
(list (list (cons "x"1)) (list (cons "x"2)) (list (cons "x"3))))
(define r2
(list (list (cons "x"2)) (list (cons "x"3)) (list (cons "x"4))))
(define (rel-union a b)
(let loop ((result a) (remaining b))
(if (null? remaining) result
(if (member (car remaining) result)
(loop result (cdr remaining))
(loop (append result (list (car remaining))) (cdr remaining))))))
(define (rel-difference a b)
(filter (lambda (t) (not (member t b))) a))
(define (show label rel)
(display label)
(for-each (lambda (t) (display " ") (display (cdar t))) rel)
(newline))
(show "R1: " r1)
(show "R2: " r2)
(show "Union: " (rel-union r1 r2))
(show "Difference:" (rel-difference r1 r2))
Neighbors
Cross-references
🔑 Logic Ch.6 — predicate logic: queries are predicates over tuples