Relational Algebra I — Set & Unary Operators

Relational Algebra I — সেট ও unary অপারেটর

Read: ~40 min Medium 14 practice problems Live SQL runner

1. The Hidden Math Behind Every SELECT

When you type SELECT name FROM student WHERE cgpa > 3.5; the SQL engine doesn’t just hand the text to a parser and pray. Internally, it translates your query into a tree of mathematical operations defined by relational algebra — the formal calculus invented by E. F. Codd in his 1970 paper “A Relational Model of Data for Large Shared Data Banks”.

Every SELECT you’ll ever write is, secretly, a sequence of just six core operators. This module covers all six: three set operators (∪, ∩, −) and three unary operators (σ, π, ρ).

যখন আপনি SELECT name FROM student WHERE cgpa > 3.5; লেখেন, SQL engine ভেতরে সেটিকে Relational Algebra-এর গাণিতিক operator-এর tree-তে রূপান্তর করে। এই algebra তৈরি করেন E. F. Codd, ১৯৭০ সালে। আজ আপনি যত SELECT লিখবেন — সব আসলে ছয়টি operator-এর সমষ্টি: তিনটি সেট operator (∪, ∩, −) এবং তিনটি unary operator (σ, π, ρ)।
Why bother? (1) Algebra explains why two SQL queries that look different produce identical results — they reduce to the same expression. (2) Optimizers rewrite queries algebraically. (3) Every database interview asks at least one algebra question. Knowing it makes you fluent, not lucky.

2. The Closure Property — Tables In, Tables Out

Every operator in relational algebra takes one or more relations (tables) as input and returns another relation as output. This is called the closure property. It’s why operators can be chained: σ(π(R)), π(σ(R)), R ∪ (R − S), and so on. The output of one operator is the legal input of the next.

Relational Algebra-র প্রতিটি operator-এর input হলো একটি বা একাধিক relation (table), এবং output-ও একটি relation। একে বলে closure property। এই কারণেই operator-গুলো একটার পর একটা চেইন করা যায় — আগেরটার output পরেরটার input হতে পারে।
Tiny proof sketch σ takes a relation R(A1,…,An) and returns a relation with the same schema (A1,…,An). π takes R(A1,…,An) and returns a relation with schema (A_i,A_j,…). Both outputs are relations, so the next operator can consume them. Closure ✓.

3. The Demo Universe — Two Tables We’ll Reuse

Throughout this lecture we’ll work with two tables — student from a Bangladeshi university and course from the same institution. Each runnable example below carries its own data-setup, so you can run any block independently.

student
idnamedeptcgpa
101ArifCSE3.71
102SumaiyaCSE3.88
103TanvirEEE3.42
104NusratBBA3.91
105FariaEEE3.10
course
codetitledept
CSE301Database SystemsCSE
CSE201Data StructuresCSE
EEE211Power ElectronicsEEE
BBA101MarketingBBA

4. σ — Selection (the Filter)

Selection, written σpredicate(R), returns the subset of rows of R that satisfy predicate. The schema (column list) is unchanged; only the row count changes.

In SQL, σ is the WHERE clause.

Symbolic example
σcgpa > 3.5(student)
≡ SELECT * FROM student WHERE cgpa > 3.5;
Selection (σ) মানে সারির ফিল্টার — যে শর্ত মানে সেগুলোই বেছে নেয়। স্কিমা একই থাকে, শুধু row সংখ্যা কমে। SQL-এ এটিই WHERE clause।
selection.sql
-- σ_cgpa>3.5(student)
SELECT * FROM student WHERE cgpa > 3.5;

4.1 Compound predicates

σ predicates can be combined with ∧ (AND), ∨ (OR) and ¬ (NOT). σdept='CSE' ∧ cgpa > 3.7(student) becomes WHERE dept='CSE' AND cgpa > 3.7.

selection_compound.sql
-- σ_(dept='CSE' AND cgpa > 3.7)(student)
SELECT * FROM student
WHERE dept = 'CSE' AND cgpa > 3.7;

5. π — Projection (Pick the Columns)

Projection, written πA,B,C(R), keeps only the listed attributes from R. And critically — projection removes duplicates, because the result is still a set. The SQL counterpart is the column list of SELECT, but to mirror algebra’s set semantics you must use SELECT DISTINCT.

Projection (π) মানে কলাম বেছে নেওয়া। π কেবল কলাম রাখে না — এটি ডুপ্লিকেট সারি-ও বাদ দেয় (কারণ ফলাফল একটি সেট)। SQL-এ এর হুবহু সমকক্ষ SELECT DISTINCT। শুধু SELECT লিখলে SQL bag (multiset) ব্যবহার করে — duplicate রেখে দেয়।
projection.sql
-- π_dept(student): all distinct departments
SELECT DISTINCT dept FROM student;

5.1 σ then π — The Most Common Pattern

Most real queries are “take the rows that match, then keep some columns”: πname,cgpa(σdept='CSE'(student)).

sigma_pi.sql
-- π_{name,cgpa}( σ_{dept='CSE'}(student) )
SELECT DISTINCT name, cgpa
FROM student
WHERE dept = 'CSE';

6. Set Operators — ∪, ∩, −

The set operators take two relations R and S and return one relation. They are only defined when R and S are union-compatible: same number of columns, same data types in matching positions.

OperatorSymbolSQL keywordMeaning
UnionR ∪ SUNIONRows in R or S (duplicates removed).
IntersectionR ∩ SINTERSECTRows in both R and S.
DifferenceR − SEXCEPTRows in R but not in S.
Set operator-গুলো (∪, ∩, −) দুটি table নেয় এবং একটি দেয়। শর্ত: দুটি table-এর কলাম সংখ্যা এবং তাদের data-type মিল থাকতে হবে — একে বলে union-compatible। SQL-এ যথাক্রমে UNION, INTERSECT, EXCEPT।

6.1 Union — students of CSE plus students of EEE

union.sql
-- π_name( σ_dept='CSE'(student) ) ∪ π_name( σ_dept='EEE'(student) )
SELECT name FROM student WHERE dept = 'CSE'
UNION
SELECT name FROM student WHERE dept = 'EEE';

6.2 Intersection — students who have BOTH a phone AND an email

intersect.sql
-- has_phone ∩ has_email
SELECT student_id FROM has_phone
INTERSECT
SELECT student_id FROM has_email;

6.3 Difference — students who have phone but NO email

difference.sql
-- has_phone − has_email
SELECT student_id FROM has_phone
EXCEPT
SELECT student_id FROM has_email;
Set vs Bag Pure algebra is set-based: no duplicates, ever. SQL is bag-based: duplicates appear unless you say otherwise. UNION, INTERSECT, EXCEPT drop duplicates by default; their … ALL variants keep them. To stay faithful to algebra, prefer the duplicate-free form.

7. ρ — Rename (Aliasing)

Rename, written ρS(B1,B2,…)(R), returns the relation R but renamed to S, with attributes B1, B2, … . Why do we need this? Three reasons:

  1. To match column names so that two relations become union-compatible.
  2. To give a self-join two distinct names.
  3. To produce friendlier output column names.
Rename (ρ) মানে relation বা attribute-এর নতুন নাম দেওয়া। প্রয়োজন হয় তিনটি কারণে: (১) দুটি relation-কে union-compatible করতে কলাম-নাম মেলানো, (২) self-join-এ একই table-কে দুই বার ব্যবহার করতে আলাদা নাম দেওয়া, (৩) output-এ পাঠকের জন্য বোধগম্য কলাম নাম দেখানো।
rename.sql
-- Self-join: who manages whom?  ρ_E(employee), ρ_M(employee)
SELECT e.name AS employee, m.name AS manager
FROM employee AS e
LEFT JOIN employee AS m
       ON m.emp_id = e.manager_id;

8. The Six-Operator Cheat-sheet

AlgebraSQLWhat it doesBangladeshi mini-example
σp(R)SELECT * FROM R WHERE pFilter rowsCustomers with bKash balance > 1000
πcols(R)SELECT DISTINCT cols FROM RPick columns, drop dupesList of districts where Daraz delivers
R ∪ SR UNION SCombine, dedupAll registered SIMs across GP and Robi
R ∩ SR INTERSECT SCommon rowsCustomers with both Nagad AND bKash
R − SR EXCEPT SR minus SPathao users who never used Foodpanda
ρS(…)(R)R AS SRename relation/columnsUse employee as both e and m in self-join

✅ What Algebra Buys You

  • Compositional, predictable, total-order operators.
  • Lets the optimizer rewrite queries safely.
  • Same algebra describes both NoSQL and SQL planning.

⚠️ What Algebra Doesn’t Have

  • Aggregations (SUM, AVG) — extension needed.
  • NULL semantics (algebra is true sets).
  • Ordering — sets are unordered by definition.

9. Pitfalls and Quirks

UNION compatibility broken silently. If two queries return different column counts, SQL refuses outright. But if they return the same count with mismatched types (text vs integer), SQLite happily coerces; PostgreSQL refuses. Always check.
π without DISTINCT keeps duplicates. Pure π de-duplicates. SQL’s SELECT doesn’t, by default. If you’re translating algebra literally, use SELECT DISTINCT.
EXCEPT vs NOT IN vs LEFT ANTI JOIN. All three answer “rows in R not in S”, but their NULL handling differs. EXCEPT treats NULLs as equal; NOT IN returns nothing if S contains a NULL. We’ll explore this in detail in Module 09.

10. Practice Problems

প্রতিটি প্রশ্ন আগে নিজে চেষ্টা করুন। তারপর Show Answer-এ ক্লিক করে মিলিয়ে নিন। কয়েকটি উত্তর সরাসরি এই পেজেই চালানোর জন্য SQL সহ দেওয়া আছে।
  1. Write σcgpa ≥ 3.7(student) in SQL using the demo table from §3.
    σcgpa ≥ 3.7(student) কে SQL-এ লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    p1.sql
    SELECT * FROM student WHERE cgpa >= 3.7;
  2. Express “list of distinct departments that have at least one student” in algebra and SQL.
    যেসব department-এ অন্তত একজন student আছে তাদের তালিকা — algebra ও SQL-এ লিখুন।
    ✨ Show Answer (উত্তর দেখুন)

    Algebra: πdept(student). SQL: SELECT DISTINCT dept FROM student;

  3. π and σ — does it matter which order you apply them? Give an example.
    π এবং σ-এর প্রয়োগের ক্রম কি ফলাফল বদলায়?
    ✨ Show Answer (উত্তর দেখুন)

    If σ’s predicate uses only the columns that π will keep, then π(σ(R)) = σ(π(R)) — order doesn’t matter. If σ uses a column that π drops, you must apply σ first; otherwise the column is gone. Optimizers prefer pushing σ down (selection-pushdown) because filtering early reduces the rows π must process.

  4. Are these two relations union-compatible? R(name TEXT, age INT) and S(age INT, name TEXT).
    R(name, age) এবং S(age, name) কি union-compatible?
    ✨ Show Answer (উত্তর দেখুন)

    No. Union compatibility is by position, not by name. Position 1 of R is TEXT but position 1 of S is INT. To union them, rename: SELECT name, age FROM S first.

  5. Show how to compute R ∩ S using only ∪ and −.
    শুধু ∪ এবং − ব্যবহার করে R ∩ S বের করুন।
    ✨ Show Answer (উত্তর দেখুন)

    R ∩ S = R − (R − S). Or symmetrically, S − (S − R).

  6. Write “customers who use bKash but not Nagad” using EXCEPT.
    যেসব গ্রাহক bKash ব্যবহার করেন কিন্তু Nagad ব্যবহার করেন না — EXCEPT দিয়ে লিখুন।
    ✨ Show Answer (উত্তর দেখুন)
    p6.sql
    SELECT msisdn FROM bkash_user
    EXCEPT
    SELECT msisdn FROM nagad_user;
  7. What is the cardinality of σtrue(R) and σfalse(R)?
    σtrue(R) এবং σfalse(R)-এর row সংখ্যা কত?
    ✨ Show Answer (উত্তর দেখুন)

    σtrue(R) = R (every row passes), so |σtrue(R)| = |R|. σfalse(R) = ∅, so |σfalse(R)| = 0.

  8. Does π always reduce the number of rows? Always preserve it? Always increase it? Choose one and justify.
    π কি সর্বদা row কমায়, একই রাখে, না বাড়ায়?
    ✨ Show Answer (উত্তর দেখুন)

    π never increases row count. It can decrease (if removing columns causes duplicate rows that get deduped) or keep the count the same (if the projected columns include a key). It can never grow.

  9. Use ρ to write a query that finds pairs of students from the same department (each pair listed once).
    একই department-এর ছাত্র জোড়া দেখান (প্রতিটি জোড়া একবার)।
    ✨ Show Answer (উত্তর দেখুন)
    p9.sql
    SELECT a.name AS student_a, b.name AS student_b, a.dept
    FROM student AS a, student AS b
    WHERE a.dept = b.dept AND a.id < b.id;
  10. Why does pure relational algebra not have an ORDER BY?
    বিশুদ্ধ relational algebra-তে ORDER BY নেই কেন?
    ✨ Show Answer (উত্তর দেখুন)

    Because relations are sets, and sets have no inherent order. Ordering is a presentation concern, not a data concern. SQL adds ORDER BY as a final-stage non-relational layer for human readers.

  11. Translate this English to algebra: “Names of CSE students with CGPA above 3.5”.
    “CSE-এর CGPA 3.5-এর বেশি ছাত্রদের নাম” — algebra-তে লিখুন।
    ✨ Show Answer (উত্তর দেখুন)

    πname(σdept='CSE' ∧ cgpa > 3.5(student))

  12. Are UNION and UNION ALL the same in algebra?
    SQL-এ UNION এবং UNION ALL কি algebra-তে এক?
    ✨ Show Answer (উত্তর দেখুন)

    No. UNION matches algebra’s ∪ (deduplication). UNION ALL is a bag operation that keeps duplicates — it doesn’t exist in pure relational algebra; it’s an extension for performance and bag-semantics SQL.

  13. Write the algebra and SQL: “Students whose name appears in either the library table or the hostel table”.
    যাদের নাম library-তে অথবা hostel-এ আছে — algebra ও SQL।
    ✨ Show Answer (উত্তর দেখুন)

    Algebra: πname(library) ∪ πname(hostel).

    p13.sql
    SELECT name FROM library
    UNION
    SELECT name FROM hostel;
  14. Translate this SQL to algebra: SELECT DISTINCT name FROM student WHERE dept = 'CSE' OR dept = 'EEE';
    উপরের SQL-কে algebra-তে রূপান্তর করুন।
    ✨ Show Answer (উত্তর দেখুন)

    πname(σdept='CSE' ∨ dept='EEE'(student)). Equivalently: πname(σdept='CSE'(student)) ∪ πname(σdept='EEE'(student)).

Summary — Module 08

Six operators — σ, π, ∪, ∩, −, ρ — form the algebraic skeleton of every SQL query you’ll ever write. Selection filters rows; projection drops columns and dedups; the three set operators combine relations under union compatibility; rename gives you the freedom to alias for self-joins and union work. Algebra is the language the optimizer thinks in; once you can speak it, SQL stops feeling like incantation and starts feeling like math.

ছয়টি operator — σ, π, ∪, ∩, −, ρ — হলো প্রতিটি SQL query-এর গাণিতিক কঙ্কাল। σ row ফিল্টার করে, π কলাম বেছে নেয় ও duplicate বাদ দেয়, set operator-গুলো relation মেলে, ρ rename করতে দেয় (self-join আর union-এ লাগে)। এই algebra শিখলে SQL আর জাদু নয়, বরং পরিষ্কার গণিত মনে হয়।

Next Module → Relational Algebra II — Joins & Division.