Module 10 · 15 min read · Free chapter
Relational algebra, tuple calculus and SQL
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.
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 for picking rows and 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 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 |
|---|---|---|---|
| select | Keeps rows satisfying P | same as R | 0 to |
| project | Keeps columns in L, removes duplicates | number of attributes in L | 1 to (0 if R is empty) |
| , | Set union and difference | same as R | to for union, 0 to for difference |
| product | Every tuple of R with every tuple of S | ||
| rename | Gives R a new name | same as R | same as R |
Select () works on rows. keeps only well-paid employees, and conditions can be joined with (and), (or) and (not). Selections can be applied in any order, and two selections can be merged into one with .
Project () works on columns. lists the departments, and because a relation is a set, each department appears only once. This duplicate removal is the reason can return fewer tuples than its input.
Union, difference and intersection need union-compatible relations, meaning the same number of attributes with matching domains. keeps tuples of R that are not in S, so it is not symmetric. Intersection is not basic, because .
Cartesian product () 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 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 () 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 is simply : form all pairs, then keep those satisfying the condition . When uses only equality, it is an equijoin. The natural join 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 = {(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, is the same as . In general . 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 .
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}. 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 . 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 , read as "the set of all tuples t for which P(t) is true".
For example, is the set of Emp tuples with salary above 50. The formula P is built from atoms such as or , joined by , and , and by the quantifiers ("there exists") and ("for all"). To return only some attributes, we write the wanted attribute before the bar, as in .
Here is a query that needs a quantifier. "Names of employees who work in a department located in Patna" becomes . The variable d is bound by , while t is free and forms the result.
A danger lurks in . The query 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 as "some row exists" and 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 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 , not .
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 AND , 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:
- Write a query for a given schema in relational algebra, in tuple calculus and in SQL.
- Trace a given query on a small table and show its output row by row.
- Explain and contrast operators or clauses, such as natural join and outer join, WHERE and HAVING, or IN and EXISTS.
- Discuss a concept such as safety of calculus expressions or the handling of NULL values.
Practice questions (our own, not previous-year questions).
- 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)
- 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)
- 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 , 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 , , , , and , and every operator returns a relation.
- keeps the degree and filters rows, while keeps chosen columns and removes duplicates.
- has degree and 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 answers "related to all of S" questions.
- Tuple calculus 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.