Computer Science and IT‹›⌂ 0:00 studied

Module 10 · 15 min read · Free chapter

Relational algebra, tuple calculus and SQL

In short

Relational algebra builds queries from σ, π, ∪, −, × and ρ, with joins and division derived from them. Tuple calculus states the answer as {t ∣ P(t)}, and only safe expressions are allowed. SQL keeps duplicates unless DISTINCT is used, runs FROM, WHERE, GROUP BY, HAVING, then SELECT, and treats comparisons with NULL as UNKNOWN.

What are you preparing for? We show the practice and previous year questions of your exam.

Start from zero: asking questions of a table

Picture the register at a ration shop. Each line has a card number, the head of family's name, the village, the card type (BPL or other) and the number of members. The inspector arrives and asks, "Give me the names of all BPL families in Rampur."

The shopkeeper does three simple things. He first looks only at the lines where the village is Rampur and the card type is BPL, which means picking rows. Then he copies just the name from each of those lines, which means picking columns, and he writes each name once even if it appears twice.

A database answers questions in exactly this way. Relational algebra gives each simple step a symbol, such as σ\sigma for picking rows and π\pi for picking columns, and every step takes a table and gives back a table. Because the output is again a table, steps can be chained into a pipeline.

SQL is the language people actually type, and tuple calculus is a mathematical way of describing the answer without saying how to get it. All three describe the same kinds of questions, as this chapter shows.

Why it matters. Every report that a bank, a railway or a ration office prints is a query. Knowing the algebra behind SQL lets you predict a query's output exactly, which is what GATE tests with its "how many rows does this return" questions.

The basic operators of relational algebra

We will use one small table throughout: Emp(EmpID, Name, Dept, Salary), with salary in thousands of rupees. The condition or attribute list is written right after the symbol, so σDept=’CS’(Emp)\sigma_{\mathit{Dept} = \text{'CS'}}(\mathit{Emp}) means "the rows of Emp whose Dept is CS". In the table below, r and s stand for the numbers of tuples in R and S.

Operator What it does Degree of result Tuples in result
σP(R)\sigma_P(R) select Keeps rows satisfying P same as R 0 to rr
πL(R)\pi_L(R) project Keeps columns in L, removes duplicates number of attributes in L 1 to rr (0 if R is empty)
R∪SR \cup S, R−SR - S Set union and difference same as R max⁡(r,s)\max(r, s) to r+sr + s for union, 0 to rr for difference
R×SR \times S product Every tuple of R with every tuple of S deg⁡R+deg⁡S\deg R + \deg S r×sr \times s
ρS(R)\rho_S(R) rename Gives R a new name same as R same as R

Select (σ\sigma) works on rows. σSalary>50(Emp)\sigma_{\mathit{Salary} > 50}(\mathit{Emp}) keeps only well-paid employees, and conditions can be joined with ∧\wedge (and), ∨\vee (or) and ¬\neg (not). Selections can be applied in any order, and two selections can be merged into one with ∧\wedge.

Project (π\pi) works on columns. πDept(Emp)\pi_{\mathit{Dept}}(\mathit{Emp}) lists the departments, and because a relation is a set, each department appears only once. This duplicate removal is the reason π\pi can return fewer tuples than its input.

Union, difference and intersection need union-compatible relations, meaning the same number of attributes with matching domains. R−SR - S keeps tuples of R that are not in S, so it is not symmetric. Intersection is not basic, because R∩S=R−(R−S)R \cap S = R - (R - S).

Cartesian product (×\times) joins every tuple of R with every tuple of S. If R has 10 tuples of degree 3 and S has 5 tuples of degree 2, then R×SR \times S has 50 tuples of degree 5. Product alone is rarely useful, but a selection on top of it gives the joins in the next section.

Rename (ρ\rho) gives a relation or its attributes a new name. It is needed when a table must be compared with itself, such as finding pairs of employees in the same department.

Why it matters. Every SQL query is turned into a tree of these operators inside the database. Questions on the size or degree of a result are just the table above applied step by step.

Joins and division

A theta join R⋈θSR \bowtie_\theta S is simply σθ(R×S)\sigma_\theta(R \times S): form all pairs, then keep those satisfying the condition θ\theta. When θ\theta uses only equality, it is an equijoin. The natural join R⋈SR \bowtie S goes one step further: it equates every attribute that has the same name in both relations and keeps only one copy of each.

Worked example. Let R(A, B) = {(1, x), (2, y), (3, x)} and S(B, C) = {(x, 10), (x, 20), (z, 30)}. In the natural join, B = x matches twice on each side, so R⋈SR \bowtie S = {(1, x, 10), (1, x, 20), (3, x, 10), (3, x, 20)}, which is 4 tuples. The tuple (2, y) and the tuple (z, 30) find no partner and are dropped.

Outer joins keep the partners that the natural join drops. The left outer join R ⟕ S adds (2, y, NULL), giving 5 tuples. The right outer join R ⟖ S adds (NULL, z, 30), and the full outer join R ⟗ S adds both, giving 6 tuples.

Three facts about join sizes come up often. If R and S share no attribute, R⋈SR \bowtie S is the same as R×SR \times S. In general 0≤∣R⋈S∣≤∣R∣×∣S∣0 \le \lvert R \bowtie S \rvert \le \lvert R \rvert \times \lvert S \rvert. If the common attribute is a non-NULL foreign key in R that refers to the key of S, every R tuple finds exactly one partner, so ∣R⋈S∣=∣R∣\lvert R \bowtie S \rvert = \lvert R \rvert.

Division answers "for all" questions. Let Enrol(Student, Course) hold (Asha, DB), (Asha, OS), (Ravi, DB), (Meena, DB), (Meena, OS) and (Meena, CN), and let Core(Course) = {DB, OS}. Enrol÷Core\mathit{Enrol} \div \mathit{Core} gives the students enrolled in every core course, which is {Asha, Meena}; Ravi misses OS, and Meena's extra course CN does not matter.

Division is not a basic operator. With A for Student, it can be written as πA(Enrol)−πA((πA(Enrol)×Core)−Enrol)\pi_A(\mathit{Enrol}) - \pi_A((\pi_A(\mathit{Enrol}) \times \mathit{Core}) - \mathit{Enrol}). The inner part builds every pair a student should have, subtracts the pairs that exist, and so finds the students who miss something, and the outer difference removes them.

Why it matters. Joins are how scattered tables are put back together, and division is how exams test "students who took all courses" or "suppliers who supply all parts". Most GATE algebra questions are a join or a division in disguise.

Tuple relational calculus and safety

Relational algebra says how to get the answer, step by step. Tuple relational calculus says only what the answer is, so it is called non-procedural. A query has the form {t∣P(t)}\{t \mid P(t)\}, read as "the set of all tuples t for which P(t) is true".

For example, {t∣t∈Emp∧t.Salary>50}\{t \mid t \in \mathit{Emp} \wedge t.\mathit{Salary} > 50\} is the set of Emp tuples with salary above 50. The formula P is built from atoms such as t∈Empt \in \mathit{Emp} or t.Dept=s.Deptt.\mathit{Dept} = s.\mathit{Dept}, joined by ∧\wedge, ∨\vee and ¬\neg, and by the quantifiers ∃\exists ("there exists") and ∀\forall ("for all"). To return only some attributes, we write the wanted attribute before the bar, as in {t.Name∣t∈Emp∧t.Salary>50}\{t.\mathit{Name} \mid t \in \mathit{Emp} \wedge t.\mathit{Salary} > 50\}.

Here is a query that needs a quantifier. "Names of employees who work in a department located in Patna" becomes {t.Name∣t∈Emp∧∃d (d∈Dept∧d.Dept=t.Dept∧d.City=’Patna’)}\{t.\mathit{Name} \mid t \in \mathit{Emp} \wedge \exists d\,(d \in \mathit{Dept} \wedge d.\mathit{Dept} = t.\mathit{Dept} \wedge d.\mathit{City} = \text{'Patna'})\}. The variable d is bound by ∃\exists, while t is free and forms the result.

A danger lurks in ¬\neg. The query {t∣¬(t∈Emp)}\{t \mid \neg(t \in \mathit{Emp})\} asks for every tuple that is not an employee, which includes every possible combination of values in the universe, an infinite set. Such an expression is called unsafe.

An expression is safe when every value in its result comes from the relations and constants that appear in it. Restricted to safe expressions, tuple calculus can express exactly the same queries as relational algebra. A language with this power is called relationally complete, and SQL is built to be at least that strong.

Why it matters. GATE gives a calculus expression and asks which English query or which algebra expression it matches. Reading ∃\exists as "some row exists" and ∀\forall as "every row satisfies" turns these into quick translations.

SQL: defining tables and simple queries

SQL has two main parts. The data definition language (DDL) creates and changes the structure, and the data manipulation language (DML) reads and changes the rows. Here is a typical definition with its constraints:

CREATE TABLE Dept (
  Dept  CHAR(4) PRIMARY KEY,
  City  VARCHAR(20) NOT NULL
);
CREATE TABLE Emp (
  EmpID  INT PRIMARY KEY,
  Name   VARCHAR(30) NOT NULL,
  Dept   CHAR(4) REFERENCES Dept(Dept),
  Salary INT CHECK (Salary >= 0)
);

The constraints do real work. PRIMARY KEY means unique and not NULL, UNIQUE means no repeats but allows NULL, REFERENCES makes Dept a foreign key, and CHECK rejects any row breaking the condition. INSERT adds rows, UPDATE changes them, and DELETE removes rows but keeps the table, while DROP TABLE removes the table itself.

The core of every query is SELECT-FROM-WHERE. The query SELECT Name FROM Emp, Dept WHERE Emp.Dept = Dept.Dept AND City = 'Patna' means πName(σcond(Emp×Dept))\pi_{\mathit{Name}}(\sigma_{\mathit{cond}}(\mathit{Emp} \times \mathit{Dept})) in algebra. There is one big difference: SQL keeps duplicate rows unless you write SELECT DISTINCT.

Joins can also be written in the FROM clause. Emp JOIN Dept ON Emp.Dept = Dept.Dept is an inner join, Emp NATURAL JOIN Dept matches same-named columns, and Emp LEFT OUTER JOIN Dept ON ... keeps employees with no department, filling the Dept columns with NULL.

A few small features are tested often. ORDER BY Salary DESC sorts from high to low, and ascending is the default. In LIKE patterns, % matches any string and _ matches exactly one character, so Name LIKE 'R_m%' matches "Ram" and "Ramesh". BETWEEN 40 AND 60 includes both 40 and 60.

Why it matters. IT officer and RRB JE papers ask SQL syntax and keyword meanings directly. GATE expects you to run a given query by hand on a small table, which needs exact knowledge of duplicates and joins.

Aggregates, GROUP BY and HAVING

Questions such as "average salary per department" need aggregate functions: COUNT, SUM, AVG, MIN and MAX. GROUP BY splits the rows into groups with equal values, and each group produces one output row. HAVING then filters whole groups, just as WHERE filters single rows.

It helps to know the logical order in which the parts run: FROM, then WHERE, then GROUP BY, then HAVING, then SELECT, and finally ORDER BY. So WHERE cannot use an aggregate, because groups do not exist yet when it runs. Any column in SELECT that is not inside an aggregate must also appear in GROUP BY.

Worked example. Take this Emp table, with salary in thousands:

EmpID Dept Salary
1 CS 50
2 CS 70
3 EE 40
4 EE NULL
5 ME 60
SELECT Dept, COUNT(*), COUNT(Salary), AVG(Salary)
FROM Emp
GROUP BY Dept
HAVING COUNT(*) > 1;

GROUP BY makes three groups: CS with rows 1 and 2, EE with rows 3 and 4, and ME with row 5. HAVING COUNT(*) > 1 drops ME. For CS the output is (CS, 2, 2, 60), and for EE it is (EE, 2, 1, 40).

Look closely at EE. COUNT(*) counts rows, so it gives 2, but COUNT(Salary) skips the NULL and gives 1. AVG also skips the NULL, so it is 401=40\dfrac{40}{1} = 40, not 402=20\dfrac{40}{2} = 20.

Why it matters. GATE loves such tables, because a single NULL changes COUNT and AVG in different ways. Writing out the groups on paper before reading SELECT avoids nearly every slip.

Nested queries, correlated queries and NULL logic

A nested query puts one SELECT inside another. The inner query can feed IN or NOT IN, EXISTS or NOT EXISTS, or a comparison with ANY or ALL. For example, Salary > ALL (SELECT Salary FROM Emp WHERE Dept = 'EE') finds people paid more than everyone in EE.

A subquery is correlated when it uses a column of the outer query, so it must be run again for each outer row. Using the same Emp table as before, this query finds employees paid more than their own department's average:

SELECT E.EmpID FROM Emp E
WHERE E.Salary > (SELECT AVG(F.Salary) FROM Emp F
                  WHERE F.Dept = E.Dept);

Work it row by row. The CS average is 60, so employee 2 with 70 qualifies and employee 1 with 50 does not. The EE average is 40, and 40 > 40 is false for employee 3, while employee 4's NULL salary gives UNKNOWN; the ME average is 60, and 60 > 60 is false, so the answer is just employee 2.

That UNKNOWN is the heart of three-valued logic. Any comparison with NULL, even NULL = NULL, gives UNKNOWN, and WHERE keeps a row only when the condition is TRUE. The rules are FALSE AND UNKNOWN = FALSE, TRUE OR UNKNOWN = TRUE, and NOT UNKNOWN = UNKNOWN, while to test for missing values you must write Salary IS NULL.

The NOT IN trap. The subquery SELECT Salary FROM Emp WHERE Dept = 'EE' returns {40, NULL}. Then x NOT IN {40, NULL} means x≠40x \ne 40 AND x≠NULLx \ne \text{NULL}, and the second part is always UNKNOWN. So WHERE Salary NOT IN (that subquery) returns no rows at all, while the same idea written with NOT EXISTS behaves as expected.

Empty sets have their own rules. A comparison with ALL over an empty subquery is TRUE, because no value breaks it, and a comparison with ANY over an empty subquery is FALSE. EXISTS is TRUE exactly when the subquery returns at least one row, whatever the values are.

Why it matters. Correlated queries express questions like "above their own group's average" that plain joins cannot. NULL handling is the most common source of wrong answers in GATE SQL questions, so it deserves slow, careful practice.

Descriptive lens: how written papers ask this

Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about query languages in four ways:

  1. Write a query for a given schema in relational algebra, in tuple calculus and in SQL.
  2. Trace a given query on a small table and show its output row by row.
  3. Explain and contrast operators or clauses, such as natural join and outer join, WHERE and HAVING, or IN and EXISTS.
  4. Discuss a concept such as safety of calculus expressions or the handling of NULL values.

Practice questions (our own, not previous-year questions).

  1. For Supplier(SID, Name), Part(PID, Colour) and Supplies(SID, PID), write the names of suppliers who supply all red parts in relational algebra and in SQL. (15 marks)
  2. Explain the difference between WHERE and HAVING with a query on an employee table, and state the logical order of clauses in a SELECT statement. (10 marks)
  3. What is a correlated subquery? Write one to list students whose marks are above the average of their own class, and trace it on a table of five rows. (10 marks)

Answer plan for question 1.

  • State that the query is a "for all" query, so division is the natural algebra operator.
  • Build the divisor as πPID(σColour=’red’(Part))\pi_{\mathit{PID}}(\sigma_{\mathit{Colour} = \text{'red'}}(\mathit{Part})), which is the set of red parts.
  • Divide Supplies by this set and join the result with Supplier to get the names.
  • Write the SQL form with NOT EXISTS (red part NOT EXISTS in this supplier's supplies), since SQL has no division operator.
  • Note that if there are no red parts, every supplier qualifies, which matches the meaning of "all" over an empty set.

Quick revision

  • The basic operators are σ\sigma, π\pi, ∪\cup, −-, ×\times and ρ\rho, and every operator returns a relation.
  • σ\sigma keeps the degree and filters rows, while π\pi keeps chosen columns and removes duplicates.
  • R×SR \times S has degree deg⁡R+deg⁡S\deg R + \deg S and ∣R∣×∣S∣\lvert R \rvert \times \lvert S \rvert tuples, and union needs union-compatible relations.
  • Natural join matches all same-named attributes and becomes a product when there are none.
  • Outer joins keep unmatched tuples with NULLs on the missing side.
  • Division R÷SR \div S answers "related to all of S" questions.
  • Tuple calculus {t∣P(t)}\{t \mid P(t)\} says what the answer is, and only safe expressions are allowed.
  • SQL keeps duplicates unless DISTINCT is written, and the logical order is FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.
  • COUNT(*) counts rows, while COUNT, SUM and AVG on a column skip NULLs.
  • Any comparison with NULL is UNKNOWN, WHERE keeps only TRUE, and NOT IN against a NULL returns nothing.

Check yourself

Exam-style questions on this chapter. Pick an answer to see the explanation. 0 of 15 answered

  1. Which of these is NOT a basic relational algebra operator?

  2. Emp has 50 tuples but only 4 distinct departments. How many tuples does πDept(Emp)\pi_{\mathit{Dept}}(\mathit{Emp}) return?

  3. R has 10 tuples of degree 3 and S has 5 tuples of degree 2. R×SR \times S has:

  4. R∩SR \cap S can be written using basic operators as:

  5. R(A, B) and S(C, D) have no common attribute, with 4 and 6 tuples. R⋈SR \bowtie S (natural join) has:

  6. R(A, B) = {(1, x), (2, y), (3, x)} and S(B, C) = {(x, 10), (x, 20), (z, 30)}. The full outer join on B has how many tuples?

  7. Division Enrol(Student,Course)÷Core(Course)\mathit{Enrol}(\mathit{Student}, \mathit{Course}) \div \mathit{Core}(\mathit{Course}) returns:

  8. Which tuple calculus expression is unsafe?

  9. Which SQL statement removes a table along with its definition?

  10. By default, SQL SELECT:

  11. A condition on an aggregate, such as AVG(Salary) > 50, must be written in:

  12. In group EE the salaries are 40 and NULL. What do COUNT(*), COUNT(Salary) and AVG(Salary) give for EE?

  13. A correlated subquery is one that:

  14. The subquery returns {40, NULL}. WHERE Salary NOT IN (subquery) returns:

  15. Emp LEFT OUTER JOIN Dept ON Emp.Dept = Dept.Dept returns:

Previous year questions

Previous year questions for UPSC CSE will appear here once each one is checked word for word against the official question paper.

Learn with AI

A tutor that asks instead of telling, a partner that argues the other side, and this chapter told through your own district.

Tell the tutor what you are stuck on. It will guide you with questions and give the answer after a few tries.

🙋 Raise a doubt or feedback

Stuck somewhere, or spotted a mistake? Write to the ExamHike team. We usually reply within a day, and you will see the reply on My progress.

Log in to ask a doubt or send feedback →

Frequently asked questions

What is the difference between WHERE and HAVING?

WHERE filters single rows before grouping, while HAVING filters whole groups after GROUP BY, so aggregate conditions go in HAVING.

What does relational division return?

R(A, B) ÷ S(B) returns the A values paired in R with every B value in S, which answers 'for all' questions.

Why does NOT IN return no rows when the subquery has a NULL?

Because x ≠ NULL is UNKNOWN, the whole NOT IN condition is never TRUE, and WHERE keeps only TRUE rows.

What is an unsafe tuple calculus expression?

It is one whose result can include values not found in the relations it names, such as {t ∣ ¬(t ∈ R)}, which is infinite.

More in this module: Databases

Official sources

Facts in this chapter were checked against these official sources.

  1. GATE 2026 Computer Science and Information Technology (CS) syllabus, IIT Guwahati
  2. NPTEL Database Systems (IIT Kanpur, 106104135): relational algebra, relational calculus and SQL