Courses / Databases for Backend Interviews / Chapter 6
Module 4 · The relational model and normalisation · Chapter 6 of 27
The Relational Model: Relations, Keys, Integrity and Relational Algebra
Builds on Data Modelling: From Requirements to Conceptual, Logical and Physical Models and The Entity-Relationship Model: Entities, Relationships, Cardinality and Mapping. Next up: Functional Dependencies: Closures, Candidate Keys and Minimal Covers.
Part 1 · Relations, tuples, attributes and domains
What a relation is
Every table in a database is a practical version of an idea from 1970: a relation.
The data modelling chapter introduced Edgar Codd's relational model of 1970, in which programs ask for the data they want without knowing how it is stored. This chapter takes the model apart, one idea at a time.
Start with the vocabulary. A domain is a set of allowed values, such as whole numbers from 0 to 100 or all valid dates. An attribute is a named column that draws its values from one domain: marks from whole numbers, test from test names. A tuple is one row, a collection of one value per attribute. A relation is a set of tuples that all have the same attributes.
The attributes together form the relation schema, written Result(student, test, marks). The tuples present at a given moment are the relation instance. The schema changes rarely, the instance changes all the time. The number of attributes is the degree of the relation and the number of tuples is its cardinality. A coaching institute that records the three attributes above for 400 students taking 6 tests has a relation of degree 3 and cardinality 2,400.
| Model term | Everyday word | SQL word |
|---|---|---|
| relation | a list of facts of one kind | table |
| tuple | one fact | row |
| attribute | a property of the fact | column |
| domain | the values a property may take | data type plus CHECK rules |
A relation is a set
The word "set" in that definition has three consequences, and they are where the model and SQL part ways. First, a set has no duplicates, so a relation can never hold the same tuple twice. Second, a set has no order, so there is no first or last tuple. Third, in the form used by SQL-era textbooks the attributes are identified by name, so their left-to-right order carries no meaning (the 1970 paper itself kept column order significant and added role names to tell columns apart). A value in each cell is a single, indivisible value, which is the idea behind first normal form, covered in a later chapter.
SQL relaxes the first two. A SQL table is closer to a bag (also called a multiset): the same row may appear more than once. Rows have no order unless a query says ORDER BY. Columns do have a position, which is why SELECT * returns them left to right. When the model says "relation" and SQL says "table", keep these differences in mind. They explain why DISTINCT exists and why a table without a key can hold the same fact twice.
Every snippet in this chapter can be run in a PostgreSQL 18 session. The outputs were produced with PGlite 0.5.15, a PostgreSQL 18.6 engine that runs inside Node. Results print as aligned text tables, a missing value prints as NULL, and long error messages are wrapped to fit. The runner is the same show helper as in the earlier chapters.
Duplicates in a table, and a key that removes them
The next script builds a table with no key and stores one result twice. A query with DISTINCT behaves like the set version of the same data. Then a table with a primary key refuses the repeated row.
CREATE TABLE scores_raw (student text, test text, marks int); INSERT INTO scores_raw (student, test, marks) VALUES ('Meera', 'Mock 1', 72), ('Karthik', 'Mock 1', 65), ('Meera', 'Mock 1', 72); -- a table with no key keeps the repeated fact SELECT student, test, marks FROM scores_raw; -- a set would keep it once SELECT DISTINCT student, test, marks FROM scores_raw; SELECT count(*) AS rows_stored, count(DISTINCT (student, test, marks)) AS distinct_rows FROM scores_raw;
-- a table with no key keeps the repeated fact student | test | marks --------+--------+------ Meera | Mock 1 | 72 Karthik | Mock 1 | 65 Meera | Mock 1 | 72 (3 rows) -- a set would keep it once student | test | marks --------+--------+------ Karthik | Mock 1 | 65 Meera | Mock 1 | 72 (2 rows) rows_stored | distinct_rows ------------+-------------- 3 | 2 (1 row)
The first query returns three rows, which a relation could not hold. DISTINCT returns two. The counting query shows the gap: three rows stored, two distinct. The second half of the script, shown next, defines the key.
CREATE TABLE scores ( student text, test text, marks int, PRIMARY KEY (student, test) ); -- the same three rows under a primary key INSERT INTO scores (student, test, marks) VALUES ('Meera', 'Mock 1', 72), ('Karthik', 'Mock 1', 65), ('Meera', 'Mock 1', 72); SELECT student, test, marks FROM scores;
-- the same three rows under a primary key ERROR 23505: duplicate key value violates unique constraint "scores_pkey" (0 rows)
The last statement failed, and it failed as a whole: scores is empty, so the SELECT after it printed (0 rows). The primary key (student, test) says that one student has at most one mark per test. The database now enforces the set rule for those columns, which is why you give every table a key.
A table has no key and holds two identical rows. Is it a relation in the sense of the model?
- No. A relation is a set of tuples, so it cannot hold a tuple twice.
- SQL still allows the table. SELECT DISTINCT returns the set version.
Part 2 · Keys
Superkey, candidate key, primary key
Rows need to be told apart. A superkey is a set of attributes whose values are different in every tuple of the relation, so it identifies each tuple. The set of all attributes is always a superkey, since tuples in a set are distinct. A superkey can carry spare attributes: if roll_no is unique, then (roll_no, name) is a superkey too.
A candidate key is a superkey that is minimal, meaning that you cannot remove any attribute and still have a superkey. roll_no is a candidate key. (roll_no, name) is not, because name can be dropped. A relation can have several candidate keys: a student has a roll number and also an email address, and each identifies one student. The primary key is the candidate key you choose as the main identifier. The others are alternate keys. A key with more than one attribute is a composite key.
Keys are statements about every possible instance, not about the rows you see now. Data can show that a set of attributes is not a key, but it can never prove that it is one. The script below counts distinct values in a small students table. Looking at four rows, (batch, name) seems to be unique, but that tells you nothing about next year's intake.
CREATE TABLE students ( student_id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, roll_no text NOT NULL UNIQUE, email text UNIQUE, name text NOT NULL, batch text NOT NULL ); INSERT INTO students (roll_no, email, name, batch) VALUES ('CH24-017', 'meera@example.com', 'Meera', 'Morning'), ('CH24-018', 'karthik@example.com', 'Karthik', 'Evening'), ('CH24-019', NULL, 'Ila', 'Morning'), ('CH24-020', NULL, 'Naveen', 'Evening'); -- two missing emails are allowed by UNIQUE SELECT student_id, roll_no, email FROM students ORDER BY student_id; -- which column sets are unique in this data? SELECT count(*) AS n, count(DISTINCT batch) AS by_batch, count(DISTINCT roll_no) AS by_roll_no, count(DISTINCT (batch, name)) AS by_batch_name FROM students;
-- two missing emails are allowed by UNIQUE student_id | roll_no | email -----------+----------+-------------------- 1 | CH24-017 | meera@example.com 2 | CH24-018 | karthik@example.com 3 | CH24-019 | NULL 4 | CH24-020 | NULL (4 rows) -- which column sets are unique in this data? n | by_batch | by_roll_no | by_batch_name --+----------+------------+-------------- 4 | 2 | 4 | 4 (1 row)
Keys in a real schema
Keys do more work than naming rows. A foreign key is a set of attributes in one relation that must match a candidate key of another, which is how relations point at each other. In PostgreSQL the referenced columns must be a primary key or a non-deferrable UNIQUE constraint (or a plain unique index), so a foreign key can point at an alternate key as well. When you declare a primary key or a UNIQUE constraint the database builds a unique index behind it, which is how it checks uniqueness quickly on every write. That index also makes lookups by the key fast, a topic a later chapter covers.
A table whose only job is to link two others, like a student enrolling in a course, usually takes a composite primary key made of the two foreign keys. The pair is unique and each part is also a reference. Composite keys are fine, but every table that refers to the composite key must carry all its columns. That is one reason people add a surrogate key to a table that others refer to.
| Natural key | Surrogate key | |
|---|---|---|
| Source | the real-world data | generated by the database |
| Stable? | only while the real world agrees | never changes |
| Size in foreign keys | as large as the data | small, often a 4-byte integer |
| Carries meaning | yes | no |
| Typical use | alternate key with UNIQUE | primary key |
Natural keys, surrogate keys and NULL
The data modelling chapter defined natural and surrogate keys. Here the roll number CH24-017 is the natural key and the generated student_id is the surrogate. A roll number format can change, and an email address can be reassigned, while a surrogate key never changes and is short, which makes foreign keys cheap, so many schemas use a surrogate primary key and keep the natural key as an alternate key with a UNIQUE constraint. The table above does exactly that.
The run shows three details worth remembering. The two missing emails were accepted, because UNIQUE treats NULL as "no value", and two unknowns are not considered equal. If you want at most one missing value, declare the column UNIQUE NULLS NOT DISTINCT. The second insert of CH24-017 was rejected with SQLSTATE 23505. And although that insert failed, the next identity value skipped from 4 to 6: the failed statement consumed number 5. Surrogate keys are unique, not gapless, so do not use them as a count.
-- a second student with the same roll number INSERT INTO students (roll_no, name, batch) VALUES ('CH24-017', 'Ravi', 'Evening'); -- the failed insert still used up an identity value INSERT INTO students (roll_no, name, batch) VALUES ('CH24-021', 'Farah', 'Morning') RETURNING student_id; CREATE TABLE seats (seat text UNIQUE NULLS NOT DISTINCT, holder text); -- NULLS NOT DISTINCT treats two NULLs as equal INSERT INTO seats (seat, holder) VALUES (NULL, 'Asha'), (NULL, 'Ravi');
Continuing the same script
-- a second student with the same roll number ERROR 23505: duplicate key value violates unique constraint "students_roll_no_key" -- the failed insert still used up an identity value student_id ---------- 6 (1 row) -- NULLS NOT DISTINCT treats two NULLs as equal ERROR 23505: duplicate key value violates unique constraint "seats_seat_key"
A primary key adds one more rule on top of UNIQUE: none of its columns may be NULL. That rule has a name, entity integrity, and the next lesson covers it together with the other integrity rules.
Can a table have two candidate keys? What happens to the one you do not pick as primary key?
- Yes, for example roll number and email.
- It becomes an alternate key, usually declared UNIQUE (and NOT NULL if it must always exist).
Part 3 · Integrity rules
Domain, entity and referential integrity
An integrity constraint is a rule that every instance of the database must satisfy. The relational model names three kinds that the database itself should enforce. Domain integrity says that every value belongs to its attribute's domain, which SQL expresses with a data type, NOT NULL and CHECK. Entity integrity says that no part of a primary key is NULL, so every row can be identified. Referential integrity says that a foreign key either is NULL or matches the key of an existing row in the referenced table. Anything else is a dangling reference.
The script below builds a small results schema with all three and then breaks each rule once. Every failing statement prints its SQLSTATE, the five-character code that the error code appendix of the PostgreSQL manual lists.
CREATE TABLE students ( student_id int PRIMARY KEY, name text NOT NULL ); CREATE TABLE tests ( test_id int PRIMARY KEY, title text NOT NULL ); CREATE TABLE results ( student_id int NOT NULL REFERENCES students (student_id), test_id int NOT NULL REFERENCES tests (test_id), marks int NOT NULL CHECK (marks BETWEEN 0 AND 100), PRIMARY KEY (student_id, test_id) ); INSERT INTO students (student_id, name) VALUES (1, 'Meera'), (2, 'Karthik'); INSERT INTO tests (test_id, title) VALUES (1, 'Algebra'), (2, 'Mechanics'); INSERT INTO results (student_id, test_id, marks) VALUES (1, 1, 72);
-- domain: the type INSERT INTO results (student_id, test_id, marks) VALUES (1, 2, 'high'); -- domain: the CHECK INSERT INTO results (student_id, test_id, marks) VALUES (1, 2, 140); -- entity integrity: no NULL in the key INSERT INTO results (student_id, test_id, marks) VALUES (NULL, 2, 60); -- key uniqueness: no repeated key INSERT INTO results (student_id, test_id, marks) VALUES (1, 1, 80); -- referential integrity: the student must exist INSERT INTO results (student_id, test_id, marks) VALUES (9, 2, 60); -- referential integrity: a referenced row cannot vanish DELETE FROM students WHERE student_id = 1;
-- domain: the type ERROR 22P02: invalid input syntax for type integer: "high" -- domain: the CHECK ERROR 23514: new row for relation "results" violates check constraint "results_marks_check" -- entity integrity: no NULL in the key ERROR 23502: null value in column "student_id" of relation "results" violates not-null constraint -- key uniqueness: no repeated key ERROR 23505: duplicate key value violates unique constraint "results_pkey" -- referential integrity: the student must exist ERROR 23503: insert or update on table "results" violates foreign key constraint "results_student_id_fkey" -- referential integrity: a referenced row cannot vanish ERROR 23503: update or delete on table "students" violates foreign key constraint "results_student_id_fkey" on table "results"
Where the rules live
You could check every one of these rules in application code, and many teams do as well. The reason to also state them in the schema is that an application is not the only writer. A script that fixes data by hand, a second service, an import job and a future colleague all bypass your code, and a constraint applies to every one of them. A rule in the database holds for every writer at once, and it is checked inside the same transaction as the change, so there is no gap between checking and writing. Rules that need more than one table or more than one row, such as "a doctor has no two overlapping appointments", can still be expressed with unique indexes, exclusion constraints or triggers, and the data modelling chapter showed an exclusion constraint doing exactly that.
Constraint names matter too. PostgreSQL generates one when you give none, such as results_marks_check in the run above, and that name appears in the error your application receives. Naming constraints yourself, for example results_marks_in_range, turns an error message into something a developer or an API can map to a clear reply.
What each code means
| Rule broken | SQLSTATE | Name |
|---|---|---|
| Wrong type for a column | 22P02 | invalid text representation |
| CHECK fails | 23514 | check violation |
| NULL in a NOT NULL or key column | 23502 | not null violation |
| Repeated primary key or UNIQUE value | 23505 | unique violation |
| Foreign key has no matching row, or the row is still referenced | 23503 | foreign key violation |
A few points from the output. The two domain failures have different causes: high is not an integer at all, so it fails on the type, while 140 is an integer outside the range that the CHECK allows. The foreign key fires in both directions. You cannot insert a result for student 9 who does not exist, and you cannot delete student 1 while a result still points to them. A CHECK only sees the row being written: a rule that compares two tables, such as "marks may not exceed the test's maximum", needs a different mechanism like a trigger or a redesigned schema.
There is also a limit worth knowing. A CHECK passes when its condition is unknown, not only when it is true. A NULL mark passes marks >= 0. The sixth lesson comes back to this.
What happens to children when a parent goes
The last failing statement above refused to delete a student who still has results. That is the default behaviour, NO ACTION (checked at the end of the statement), and RESTRICT is the same idea checked immediately. You can choose a different referential action when you declare the key. ON DELETE CASCADE deletes the child rows with their parent. ON DELETE SET NULL keeps the children and clears the reference. ON DELETE SET DEFAULT replaces it with the column's default.
Cascade fits rows that have no meaning without the parent, like a student's results. Set null fits rows worth keeping on their own, like a doubt a student posted. Pick the one that matches the real life of the data, because a cascade can delete far more than you expect.
CREATE TABLE students (student_id int PRIMARY KEY, name text NOT NULL); CREATE TABLE tests (test_id int PRIMARY KEY, title text NOT NULL); CREATE TABLE results ( student_id int NOT NULL REFERENCES students (student_id) ON DELETE CASCADE, test_id int NOT NULL REFERENCES tests (test_id), marks int NOT NULL, PRIMARY KEY (student_id, test_id) ); CREATE TABLE doubts ( doubt_id int PRIMARY KEY, student_id int REFERENCES students (student_id) ON DELETE SET NULL, question text NOT NULL ); INSERT INTO students (student_id, name) VALUES (1, 'Meera'), (2, 'Karthik'); INSERT INTO tests (test_id, title) VALUES (1, 'Algebra'); INSERT INTO results (student_id, test_id, marks) VALUES (1, 1, 72), (2, 1, 65); INSERT INTO doubts (doubt_id, student_id, question) VALUES (1, 1, 'Why is 0! = 1?'); DELETE FROM students WHERE student_id = 1; -- CASCADE removed Meera's result SELECT student_id, test_id, marks FROM results; -- SET NULL kept the doubt and cleared its owner SELECT doubt_id, student_id, question FROM doubts;
-- CASCADE removed Meera's result student_id | test_id | marks -----------+---------+------ 2 | 1 | 65 (1 row) -- SET NULL kept the doubt and cleared its owner doubt_id | student_id | question ---------+------------+--------------- 1 | NULL | Why is 0! = 1? (1 row)
CREATE TABLE late_results ( student_id int NOT NULL REFERENCES students (student_id) DEFERRABLE INITIALLY DEFERRED, marks int NOT NULL ); BEGIN; -- the student does not exist yet, but the check waits for COMMIT INSERT INTO late_results (student_id, marks) VALUES (7, 55); INSERT INTO students (student_id, name) VALUES (7, 'Ila'); COMMIT; SELECT student_id, marks FROM late_results; BEGIN; INSERT INTO late_results (student_id, marks) VALUES (8, 61); -- nobody ever adds student 8 COMMIT; SELECT count(*) AS late_rows FROM late_results;
Part 4 · Relational algebra I
A language of operators on relations
Relational algebra is a small set of operators. Each takes one or two relations and returns a relation, so the output of one operator can be the input of the next. This closure property is why a long query can be written as a pipeline of simple steps. SQL was designed around these operators, and a database turns your SQL into a tree of them before it runs it.
There are six basic operators. Selection σ keeps the tuples that satisfy a condition. Projection π keeps some attributes and, as a set operation, removes repeated tuples. Rename ρ gives a relation or an attribute a new name. Union ∪, difference − and Cartesian product × combine two relations. Intersection ∩ is not basic, because A ∩ B is the same as A − (A − B), but it is convenient.
| Operator | Meaning | SQL |
|---|---|---|
| σ condition (R) | rows of R where the condition is true | SELECT * FROM R WHERE condition |
| π a, b (R) | only columns a and b, no repeats | SELECT DISTINCT a, b FROM R |
| ρ S (R) | rename R to S | FROM R AS S, or column AS name |
| R ∪ S | rows in R or S | UNION |
| R − S | rows in R but not in S | EXCEPT |
| R ∩ S | rows in both | INTERSECT |
| R × S | every row of R with every row of S | CROSS JOIN |
Selection, projection, rename and product
All the examples in this lesson and the next use one small institute: five students, three tests and nine results. Farah has taken none, Naveen only the organic chemistry test. This is the setup script.
CREATE TABLE students ( student_id int PRIMARY KEY, name text NOT NULL, batch text NOT NULL ); CREATE TABLE tests (test_id int PRIMARY KEY, title text NOT NULL); CREATE TABLE results ( student_id int REFERENCES students (student_id), test_id int REFERENCES tests (test_id), marks int NOT NULL, PRIMARY KEY (student_id, test_id) ); INSERT INTO students (student_id, name, batch) VALUES (1, 'Meera', 'Morning'), (2, 'Karthik', 'Evening'), (3, 'Ila', 'Morning'), (4, 'Naveen', 'Evening'), (5, 'Farah', 'Morning'); INSERT INTO tests (test_id, title) VALUES (1, 'Algebra'), (2, 'Mechanics'), (3, 'Organic'); INSERT INTO results (student_id, test_id, marks) VALUES (1, 1, 72), (1, 2, 81), (1, 3, 66), (2, 1, 65), (2, 2, 58), (3, 1, 90), (3, 2, 77), (3, 3, 84), (4, 3, 49);
Selection and projection operate on one relation. The DISTINCT in the projection matters: without it SQL would return one row per student, and the database would be returning a bag.
-- selection: rows that satisfy a condition SELECT student_id, test_id, marks FROM results WHERE marks >= 80 ORDER BY student_id, test_id; -- projection: some columns, duplicates removed SELECT DISTINCT batch FROM students ORDER BY batch; -- rename: new names for the relation and its columns SELECT s.name AS learner, s.batch AS slot FROM students AS s WHERE s.student_id = 5; -- Cartesian product: every student with every test SELECT count(*) AS pairs FROM students CROSS JOIN tests;
-- selection: rows that satisfy a condition student_id | test_id | marks -----------+---------+------ 1 | 2 | 81 3 | 1 | 90 3 | 3 | 84 (3 rows) -- projection: some columns, duplicates removed batch ------- Evening Morning (2 rows) -- rename: new names for the relation and its columns learner | slot --------+-------- Farah | Morning (1 row) -- Cartesian product: every student with every test pairs ----- 15 (1 row)
The product of 5 students and 3 tests has 15 rows. A product rarely appears alone in a real query. It is the raw material of a join, which is a product followed by a selection.
Operators compose
Because each operator returns a relation, you can feed one into the next. The expression π name ( σ marks ≥ 80 ( Student ⋈ Result ) ) reads inside out: join students to results, keep the rows with a mark of at least 80, keep only the name. SQL lets you write it flat, as one SELECT, or as nested steps where every level is one operator. Both forms below return the same relation, and a database treats them as the same query.
-- π name ( σ marks >= 80 ( students ⋈ results ) ) SELECT DISTINCT s.name FROM students AS s JOIN results AS r ON r.student_id = s.student_id WHERE r.marks >= 80 ORDER BY s.name; -- the same expression written as nested steps, one operator each SELECT DISTINCT name FROM ( SELECT name, marks FROM ( SELECT s.name, r.marks FROM students AS s CROSS JOIN results AS r WHERE s.student_id = r.student_id ) AS joined WHERE marks >= 80 ) AS high ORDER BY name;
-- π name ( σ marks >= 80 ( students ⋈ results ) ) name ----- Ila Meera (2 rows) -- the same expression written as nested steps, one operator each name ----- Ila Meera (2 rows)
This is what makes the algebra useful beyond teaching. A database planner rewrites your query into an equivalent expression that is cheaper to run. For instance, it can apply a selection before a join instead of after it, since filtering early leaves fewer rows to join. The result is the same relation, and only the cost changes. Query plans are the subject of a later chapter.
Union, intersection and difference
These three need union-compatible inputs: the same number of attributes, with matching types. In the examples each input is a list of student ids, those who took the Algebra test (1) and those who took the Organic test (3). The set operators remove repeats, and UNION ALL is the bag version that keeps them.
-- union: who took Algebra or Organic SELECT student_id FROM results WHERE test_id = 1 UNION SELECT student_id FROM results WHERE test_id = 3 ORDER BY student_id; -- intersection: who took both SELECT student_id FROM results WHERE test_id = 1 INTERSECT SELECT student_id FROM results WHERE test_id = 3 ORDER BY student_id; -- difference: Algebra but not Organic SELECT student_id FROM results WHERE test_id = 1 EXCEPT SELECT student_id FROM results WHERE test_id = 3 ORDER BY student_id; -- UNION ALL is the bag version: duplicates stay SELECT student_id FROM results WHERE test_id = 1 UNION ALL SELECT student_id FROM results WHERE test_id = 3 ORDER BY student_id;
-- union: who took Algebra or Organic student_id ---------- 1 2 3 4 (4 rows) -- intersection: who took both student_id ---------- 1 3 (2 rows) -- difference: Algebra but not Organic student_id ---------- 2 (1 row) -- UNION ALL is the bag version: duplicates stay student_id ---------- 1 1 2 3 3 4 (6 rows)
Algebra was taken by students 1, 2 and 3 and Organic by 1, 3 and 4. The union is all four, the intersection is 1 and 3, and the difference "Algebra but not Organic" is only student 2. UNION ALL returns six rows: students 1 and 3 appear twice, once from each side.
One more operator is worth naming here: the aggregate (or grouping) operator, written with a script G in some books. It partitions a relation by some attributes and computes a count, sum or average for each part. It is an extension of the six basic operators, and SQL exposes it as GROUP BY. Much of what a basic SELECT says is a combination of these operators.
Which relational operator does SELECT DISTINCT batch FROM students express, and why is DISTINCT needed?
- Projection on batch.
- Projection returns a set, so repeated tuples are removed. SQL needs DISTINCT to do the same.
Rewrite A ∩ B using only difference.
Part 5 · Relational algebra II
Joins
A join combines two relations on a condition. In algebra a theta join R ⋈θ S is a product followed by a selection with condition θ, where θ can be any comparison. An equi-join is a theta join where θ only tests equality, which is the case you meet most. A natural join is an equi-join on all attributes that have the same name in both relations, with the repeated column shown once. This lesson uses the same three tables as the previous one. Conceptually a join is a product followed by a selection: 5 students times 9 results make 45 pairs, and only the 9 where the student ids agree survive.
In SQL the three look like this. The theta join below pairs a student with a higher scorer on the same test: someone who scored more than 20 marks higher. The condition holds an inequality, so this is a theta join and not an equi-join.
-- theta join: the condition is not an equality SELECT a.name AS lower_scorer, b.name AS higher_scorer, ra.test_id FROM results AS ra JOIN results AS rb ON rb.test_id = ra.test_id AND rb.marks > ra.marks + 20 JOIN students AS a ON a.student_id = ra.student_id JOIN students AS b ON b.student_id = rb.student_id ORDER BY lower_scorer, higher_scorer; -- equi-join: students with their results SELECT s.name, t.title, r.marks FROM students AS s JOIN results AS r ON r.student_id = s.student_id JOIN tests AS t ON t.test_id = r.test_id WHERE s.batch = 'Evening' ORDER BY s.name, t.title; -- natural join: equal column names are matched for you SELECT student_id, test_id, marks, title FROM results NATURAL JOIN tests WHERE student_id = 4;
-- theta join: the condition is not an equality lower_scorer | higher_scorer | test_id -------------+---------------+-------- Karthik | Ila | 1 Karthik | Meera | 2 Naveen | Ila | 3 (3 rows) -- equi-join: students with their results name | title | marks --------+-----------+------ Karthik | Algebra | 65 Karthik | Mechanics | 58 Naveen | Organic | 49 (3 rows) -- natural join: equal column names are matched for you student_id | test_id | marks | title -----------+---------+-------+-------- 4 | 3 | 49 | Organic (1 row)
The natural join matched test_id because both tables have a column of that name, and it printed the column once. That is also its weakness: if someone later adds a column called title to results, the join silently changes meaning. Most production code uses explicit ON conditions.
Outer joins
An inner join drops tuples that have no partner. An outer join keeps them and fills the missing side with NULL. A left outer join keeps every tuple of the left relation, a right outer join keeps the right one, and a full outer join keeps both. Right and left are mirror images, so many people write only left joins and swap the tables.
-- left outer join: students with no results are kept SELECT s.name, count(r.test_id) AS tests_taken FROM students AS s LEFT JOIN results AS r ON r.student_id = s.student_id GROUP BY s.name ORDER BY s.name; CREATE TABLE rooms (batch text PRIMARY KEY, room text NOT NULL); INSERT INTO rooms (batch, room) VALUES ('Morning', 'R1'), ('Evening', 'R2'), ('Weekend', 'R3'); -- full outer join: unmatched rows are kept from both sides SELECT DISTINCT s.batch AS student_batch, r.batch AS room_batch, r.room FROM students AS s FULL JOIN rooms AS r ON r.batch = s.batch ORDER BY room;
-- left outer join: students with no results are kept name | tests_taken --------+------------ Farah | 0 Ila | 3 Karthik | 2 Meera | 3 Naveen | 1 (5 rows) -- full outer join: unmatched rows are kept from both sides student_batch | room_batch | room --------------+------------+----- Morning | Morning | R1 Evening | Evening | R2 NULL | Weekend | R3 (3 rows)
Farah took no tests, and the left join kept her with a count of 0. The rooms table has a room for a weekend batch that has no students, so the full join returned a row with a NULL student batch. Notice also that count(r.test_id) counts only non-NULL values, which is why it returns 0 for Farah, while count(*) would have returned 1.
Division
Division answers questions of the form "which X are related to all Y". Which students have taken every test? Which suppliers deliver every product on a list? Algebra has an operator for it, and SQL does not, so you write it with a pattern. The usual form is a double NOT EXISTS: a student qualifies if there is no test for which no result of theirs exists. The second form counts: a student qualifies if the number of distinct tests they took equals the number of tests.
-- division: students who took every test SELECT s.name FROM students AS s WHERE NOT EXISTS ( SELECT 1 FROM tests AS t WHERE NOT EXISTS ( SELECT 1 FROM results AS r WHERE r.student_id = s.student_id AND r.test_id = t.test_id ) ) ORDER BY s.name; -- the same division by counting SELECT s.name FROM students AS s JOIN results AS r ON r.student_id = s.student_id GROUP BY s.student_id, s.name HAVING count(DISTINCT r.test_id) = (SELECT count(*) FROM tests) ORDER BY s.name;
-- division: students who took every test name ----- Ila Meera (2 rows) -- the same division by counting name ----- Ila Meera (2 rows)
Which of the two forms to prefer depends on the question. The double NOT EXISTS follows the definition directly, including the edge case of an empty list of tests, where every student qualifies. The counting form is easier to read and to modify, for example to ask for students who took at least two tests. Check both on a small dataset where you know the answer before you trust either.
Both forms return Ila and Meera. The next scene walks through the idea. Students sit on the left and tests on the right, with one edge for every result, and the walk checks each student against every test. One missing edge is enough to drop a student.
Watch for the students with an edge to all three tests
Read it as steps
Part 6 · NULL and three-valued logic
Unknown is a third truth value
A relational database lets a value be missing, and writes it NULL. Missing can mean not known yet (a mark not recorded), not applicable (no middle name), or not provided. The model treats NULL as a marker, not a value, and gives comparisons a third outcome: unknown. This is three-valued logic. A comparison with NULL is neither true nor false, it is unknown.
-- AND and OR over true, false and unknown (NULL) SELECT a, b, a AND b AS a_and_b, a OR b AS a_or_b FROM (VALUES (true), (false), (NULL::boolean)) AS x (a) CROSS JOIN (VALUES (true), (false), (NULL::boolean)) AS y (b); -- NOT of each value SELECT a, NOT a AS not_a FROM (VALUES (true), (false), (NULL::boolean)) AS x (a); -- comparisons with NULL are unknown, not false SELECT NULL = NULL AS eq, NULL <> 5 AS ne, NULL IS NULL AS is_null, NULL IS NOT DISTINCT FROM NULL AS not_distinct;
-- AND and OR over true, false and unknown (NULL) a | b | a_and_b | a_or_b ------+-------+---------+------- true | true | true | true true | false | false | true true | NULL | NULL | true false | true | false | true false | false | false | false false | NULL | false | NULL NULL | true | NULL | true NULL | false | false | NULL NULL | NULL | NULL | NULL (9 rows) -- NOT of each value a | not_a ------+------ true | false false | true NULL | NULL (3 rows) -- comparisons with NULL are unknown, not false eq | ne | is_null | not_distinct -----+------+---------+------------- NULL | NULL | true | true (1 row)
That is why NULL = NULL is not true: two unknowns are not known to be equal. To test for a missing value you use IS NULL, and to compare two values with a rule that counts two NULLs as equal you use IS NOT DISTINCT FROM. The top of the output also shows the whole truth table for AND, OR and NOT.
Reading the truth tables
Think of unknown as "could be either". true AND unknown depends on the unknown, so it is unknown. false AND unknown is false whichever way the unknown turns out. OR is the mirror image: true OR unknown is true, false OR unknown is unknown. NOT unknown is unknown. The scene fills the AND table cell by cell, using the same values as the query output above.
With a true on the left, the answer is whatever the right side is
Read it as steps
The AND table from the lesson query: false wins, otherwise an unknown makes the answer unknown.
In short: a false decides AND, a true decides OR, and otherwise an unknown stays unknown. Every WHERE clause keeps a row only if its condition is true. Rows where it is false or unknown are both removed.
Where NULL bites
Three places surprise people. A CHECK constraint accepts a row when its condition is true or unknown, so CHECK (marks >= 0) lets a NULL mark through. Add NOT NULL to close that door. A WHERE clause cannot find the rows its negation also misses: for a row with a NULL mark, both marks >= 70 and NOT (marks >= 70) are unknown, so neither picks it. And aggregates skip NULL: avg ignores missing marks and count(column) does not count them.
CREATE TABLE marks ( student text, test text, marks int CHECK (marks >= 0) ); INSERT INTO marks (student, test, marks) VALUES ('Meera', 'Algebra', 72), ('Karthik', 'Algebra', 65), ('Ila', 'Algebra', NULL); -- the CHECK accepted the NULL: a check fails only on false SELECT student, marks FROM marks ORDER BY student; -- WHERE keeps only rows where the condition is true SELECT student FROM marks WHERE marks >= 70 OR marks < 70 ORDER BY student; SELECT student FROM marks WHERE NOT (marks >= 70) ORDER BY student; SELECT student FROM marks WHERE marks IS NULL; -- aggregates skip NULL SELECT count(*) AS rows_counted, count(marks) AS marks_counted, avg(marks) AS average FROM marks;
-- the CHECK accepted the NULL: a check fails only on false student | marks --------+------ Ila | NULL Karthik | 65 Meera | 72 (3 rows) -- WHERE keeps only rows where the condition is true student ------- Karthik Meera (2 rows) student ------- Karthik (1 row) student ------- Ila (1 row) -- aggregates skip NULL rows_counted | marks_counted | average -------------+---------------+-------------------- 3 | 2 | 68.5000000000000000 (1 row)
Ila's missing mark passed the CHECK. A query for marks at least 70 or below 70, which looks like it covers every number, did not return Ila, and neither did its negation. Only IS NULL found her. The average of the two recorded marks is 68.5, not the 45.67 you would get by treating the missing mark as zero.
Because unknown spreads through every comparison, many designers keep NULL out of columns that always have a value, using NOT NULL by default. For attributes that are truly optional, there are two common choices: allow NULL and write every query with it in mind, or move the optional attribute into its own table that has a row only when the value exists. The second choice removes the NULL, at the price of a join. Whichever you pick, be deliberate: NULL can mean not yet known or not applicable, and a column that mixes both meanings will mislead its readers.
All chapters · Previous: The Entity-Relationship Model: Entities, Relationships, Cardinality and Mapping