Skip to content
GATEiit

GATE CSE · Databases

Relational model: relational algebra, tuple calculus and SQL

Relations, keys and the relational algebra operators (selection, projection, joins, set operations, division), tuple relational calculus, and SQL queries with grouping, nested subqueries and NULLs; GATE asks for query outputs, result sizes and equivalences.

Before you start

This topic comes before: ER model, Integrity constraints and normal forms

Concept notes

1. The relational model

A relation is a set of tuples over a schema R(A1,…,An); each attribute Ai takes values from a domain. In a table: columns are attributes, rows are tuples.

  • Degree (arity): number of attributes. Cardinality: number of tuples.
  • A relation is a set: no duplicate tuples, and the order of rows does not matter. (SQL tables are multisets, so duplicates may appear.)
  • Values are atomic (first normal form).

Keys. A superkey is any set of attributes whose values are unique across tuples. A candidate key is a minimal superkey. One candidate key is chosen as the primary key (no NULLs allowed). A foreign key in R refers to the primary key of S: every non-null foreign-key value must appear in S (referential integrity).

Useful counts: with n attributes and one candidate key of k attributes, the number of superkeys containing it is 2n−k.

The relational query languages are relational algebra (procedural: says how), tuple relational calculus (declarative: says what) and SQL, which is based on both. Basic relational algebra and safe relational calculus have the same expressive power (Codd's theorem); neither can express transitive closure or aggregates.

2. Relational algebra operators

Basic operators: σ (select rows), π (project columns, removing duplicates), × (Cartesian product), ∪, − (set union and difference, on union-compatible relations: same degree and matching domains), and ρ (rename). Derived: ∩, joins and ÷.

Let R have r tuples and degree m, S have s tuples and degree n.

Operation Degree of result Number of tuples
σp(R) m 0 to r
πL(R) size of L 1 to r (exactly r if L has a key); 0 if R is empty
R×S m+n exactly r⋅s
R∪S m max⁡(r,s) to r+s
R∩S m 0 to min⁡(r,s)
R−S m 0 to r
R⋈S (natural) m+n− common 0 to r⋅s

Equivalences worth knowing: σp∧q(R)=σp(σq(R)); selections commute; π distributes over ∪ but not over − or ∩; σ distributes over ∪, ∩ and −; σp(R×S)=R⋈pS; push selections below joins when p uses only one side's attributes.

3. Joins and division

  • Theta join R⋈θS=σθ(R×S); an equijoin uses only =.
  • Natural join R⋈S: equijoin on all common attribute names, keeping one copy of each. With no common attribute it is R×S.
  • If the common attribute is a key of S and a non-null foreign key in R referring to S, then ∣R⋈S∣=∣R∣.
  • Outer joins keep unmatched tuples padded with NULL: left keeps all of R, right keeps all of S, full keeps both.
  • Semijoin R⋉S: tuples of R that have a match in S (only R's attributes).

Division answers "for all" questions. For R(X,Y) and S(Y), R÷S is the set of x such that (x,y)∈R for every y∈S: R÷S=πX(R)−πX((πX(R)×S)−R) Read it as: take all candidate x, build every pair they should have, keep the missing pairs, and remove the x values that miss something. If S is empty, R÷S=πX(R).

Enrolledsidcids1c1s1c2s2c1s3c1s3c2s3c3÷Coursecidc1c2=Resultsids1s3s1 has c1 and c2s2 lacks c2s3 has c1, c2 (and c3)"students who take every course"
Division: the students who are enrolled in every course listed in Course

4. Tuple relational calculus

A TRC query has the form {t∣P(t)}: the set of tuples t for which the formula P is true. Atoms are t∈R, t.A  op  s.B and t.A  op  c; formulas are combined with ∧,∨,¬,⇒ and the quantifiers ∃s∈R and ∀s∈R.

Examples on Emp(eid, name, dept, salary, mgr):

  • Employees earning over 50: {t∣t∈Emp∧t.salary>50}.
  • Names of those who manage someone: {t.name∣t∈Emp∧∃s∈Emp (s.mgr=t.eid)}.
  • Highest paid in their department: {t∣t∈Emp∧∀s∈Emp (s.dept=t.dept⇒s.salary≤t.salary)}.

Use the identities ∀s P≡¬∃s ¬P and P⇒Q≡¬P∨Q to move between forms. "For all" in TRC corresponds to division in algebra and to NOT EXISTS ... NOT EXISTS in SQL.

A query is safe if its answer contains only values from the database (or constants in the query), so it is finite. {t∣¬(t∈R)} is unsafe: infinitely many tuples are not in R. Safe TRC, domain relational calculus and basic relational algebra are equally expressive.

5. SQL query semantics

Read a query in this logical order:

  1. FROM: Cartesian product of the listed tables (joins as written).
  2. WHERE: keep rows where the condition is true.
  3. GROUP BY: form groups with equal grouping values.
  4. HAVING: keep groups where the condition is true (may use aggregates).
  5. SELECT: compute output columns; DISTINCT removes duplicates.
  6. ORDER BY: sort.

Hence WHERE cannot use aggregates, and HAVING filters groups, not rows. In a grouped query, every SELECT column must be a grouping column or an aggregate.

Duplicates. SELECT keeps duplicates (bag semantics); SELECT DISTINCT corresponds to π. UNION, INTERSECT, EXCEPT remove duplicates; UNION ALL keeps them.

Aggregates: COUNT, SUM, AVG, MIN, MAX. All except COUNT(*) ignore NULLs. COUNT(DISTINCT x) counts distinct non-null values. On an empty input, COUNT gives 0 and the others give NULL.

Joins in SQL: R JOIN S ON cond, NATURAL JOIN, LEFT/RIGHT/FULL OUTER JOIN. A self-join needs aliases: FROM Emp e, Emp m WHERE e.mgr = m.eid pairs each employee with their manager.

6. NULLs and nested subqueries

Three-valued logic. Any comparison with NULL (even NULL = NULL) is unknown. WHERE and HAVING keep only rows that are true; unknown is dropped. Use IS NULL / IS NOT NULL to test for NULL. Truth rules: false AND unknown = false; true OR unknown = true; NOT unknown = unknown.

Subquery forms:

  • x IN (S): true if x equals some value of S.
  • x NOT IN (S): if S contains a NULL, this is never true (each row gives false or unknown), so the query returns nothing.
  • x > ALL (S): greater than every value (true if S is empty). x > ANY (S) (or SOME): greater than at least one value (false if S is empty).
  • EXISTS (S): true if S has at least one row; NULLs inside do not matter.

A correlated subquery refers to the outer row, so it is re-evaluated for each outer row:

SELECT name FROM Emp e
WHERE salary > (SELECT AVG(salary) FROM Emp f WHERE f.dept = e.dept);

returns employees paid more than their own department's average.

"For all" in SQL uses double negation: students for whom no course exists that they do not take, i.e. NOT EXISTS (... NOT EXISTS (...)). Prefer NOT EXISTS over NOT IN whenever the inner column may contain NULLs.

Formulas to remember

DivisionR(X,Y), S(Y)
R÷S=πX(R)−πX((πX(R)×S)−R)
Cartesian product size
∣R×S∣=∣R∣⋅∣S∣,deg⁡=deg⁡R+deg⁡S
Natural join via productA = common attributes, L = all attributes with one copy of A
R⋈S=πL(σR.A=S.A(R×S))
Intersection from difference
R∩S=R−(R−S)
Selection cascade
σp∧q(R)=σp(σq(R))
Universal quantifier
∀s P(s)≡¬∃s ¬P(s)

Common mistakes

  • Forgetting that π removes duplicates in relational algebra while SQL SELECT keeps them unless DISTINCT is used.
  • Applying HAVING before WHERE; WHERE filters rows first, then groups are formed and HAVING filters groups.
  • Dividing by the total row count when averaging a column with NULLs; AVG ignores NULLs.
  • Using NOT IN on a column that may contain NULL; the query silently returns nothing.
  • Assuming π distributes over set difference; it distributes over union only.
  • Treating natural join with no common attributes as empty; it is the Cartesian product.

Worked examples

Try each step yourself, then reveal the working.

Example 1: Join sizes on small relations

numerical

R(A, B) = {(1, x), (2, y), (3, x), (4, z)}, S(B, C) = {(x, 10), (x, 20), (y, 30), (w, 40)}. Find the number of tuples in R⋈S, πA(R⋈S), the left outer join and the full outer join of R and S.

  1. Step 1: Match tuples on the common attribute B.

    Try it on paper first.

Example 2: Division: students who take every course

numerical

Enrolled(sid, cid) = {(s1, c1), (s1, c2), (s1, c3), (s2, c1), (s2, c3), (s3, c1), (s3, c2), (s3, c3), (s4, c2)} and Course(cid) = {c1, c2, c3}. Find Enrolled ÷ Course using the formula.

  1. Step 1: Find the candidates and all the pairs they should have.

    Try it on paper first.

Example 3: GROUP BY and HAVING

numerical

On the table Emp below, find the output of

SELECT dept, COUNT(*), AVG(salary)
FROM Emp GROUP BY dept HAVING COUNT(*) >= 2;
eid name dept salary mgr
1 Asha CS 90 NULL
2 Ravi CS 60 1
3 Meena EE 70 1
4 Kiran EE 50 3
5 Divya CS 60 2
6 Arjun ME 40 NULL
  1. Step 1: Form the groups.

    Try it on paper first.

Example 4: NOT IN versus NOT EXISTS with NULLs

conceptual

On the same Emp table, compare

(Q1) SELECT name FROM Emp WHERE eid NOT IN (SELECT mgr FROM Emp);

(Q2) SELECT name FROM Emp e WHERE NOT EXISTS (SELECT * FROM Emp m WHERE m.mgr = e.eid);

eid name dept salary mgr
1 Asha CS 90 NULL
2 Ravi CS 60 1
3 Meena EE 70 1
4 Kiran EE 50 3
5 Divya CS 60 2
6 Arjun ME 40 NULL
  1. Step 1: List the subquery result of Q1.

    Try it on paper first.

Previous year questions

23 official GATE CSE questions on this topic, newest first.

Practise these 23 PYQs →

Topic test

10 questions: up to 4 official PYQs and original practice questions, with GATE marking (MCQ wrong answers lose marks). Score 60% or more to pass. A new set is drawn each time.

Mark as mastered

Loading your progress…

My revision notes

Notes written by the GATEiit team against the official GATE CSE syllabus; being checked by a reviewer. Updated 2026-11-21. Spotted a mistake? Use Report an issue on any question, or contact us.