interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 6 · Databases · Lesson 1 of 10

Relational model and query semantics

The relational model gives SQL its meaning: relations with keys and constraints, an algebra over bags of rows, and three-valued logic for NULL. Knowing the semantics rather than only the syntax lets you predict results, catch silently wrong answers and design schemas that keep data consistent.
About 4 hFocus mode

Builds on

Step 1: Learn the ideas

  • Relations, tuples, attributes and domains
  • Relational algebra: selection, projection, join, union, difference, grouping
  • Set versus bag (multiset) semantics in SQL
  • NULL, three-valued logic and aggregates over NULLs
  • Inner, outer, semi- and anti-joins; NOT IN versus NOT EXISTS
  • Logical clause order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY
  • Keys: superkey, candidate, primary and foreign keys; referential actions
  • NOT NULL, UNIQUE and CHECK constraints and what constraints cannot express
  • Functional dependencies and normal forms (1NF, 3NF, BCNF)
  • Deliberate denormalization and its maintenance cost

Why it matters

SQL is declarative: you describe the result and the database chooses how to compute it. That makes the semantics the contract. Syntax errors fail loudly, so the SQL bugs that survive testing tend to be semantic ones that return plausible but wrong results: a join that multiplies rows and inflates a SUM, a LEFT JOIN that silently becomes an inner join, a NOT IN that returns nothing because of a single NULL. The same semantics decide which rewrites an optimizer may apply, so this topic is also the base for query optimization.

Core ideas

Relations and bags. In Codd's model a relation is a set of tuples. SQL tables and query results are bags: duplicates survive unless a key, DISTINCT or a set operator without ALL removes them. Projection does not deduplicate, UNION removes duplicates while UNION ALL keeps them, and a join emits one row per matching pair. If an order has three line items and two payments, joining all three tables yields six rows for that order, and summing payments triple-counts them. Aggregate each child table before joining, or join only along key-preserving paths.

Logical evaluation order. Conceptually a query runs FROM (with joins), then WHERE, GROUP BY, HAVING, SELECT (expressions and window functions), DISTINCT, ORDER BY and LIMIT. This explains why WHERE cannot use an aggregate, why HAVING filters groups and why a SELECT alias is not visible in WHERE. The physical plan may differ, as long as the result is the same.

Three-valued logic. A comparison with NULL yields UNKNOWN, and WHERE and HAVING keep only rows whose condition is TRUE. Consequences:

  • x = NULL is never true; use IS NULL, or IS NOT DISTINCT FROM for null-safe equality.
  • x NOT IN (SELECT y ...) is UNKNOWN for every x once the subquery yields a NULL, so the query returns nothing; NOT EXISTS has no such trap.
  • Aggregates skip NULLs: COUNT(col) counts non-null values, COUNT(*) counts rows, AVG ignores NULLs instead of treating them as zero, and SUM over zero rows is NULL.
  • GROUP BY and DISTINCT put all NULLs into one group, although NULL = NULL is not true. A UNIQUE constraint normally accepts several NULLs; PostgreSQL lets you opt out with NULLS NOT DISTINCT.

Outer joins. A LEFT JOIN keeps unmatched left rows padded with NULLs. A condition on the right table placed in WHERE discards exactly those padded rows; put it in the ON clause if unmatched rows must survive.

Keys and constraints. A candidate key is a minimal set of attributes that identifies a row; one becomes the primary key. A foreign key requires each referencing value to exist in the referenced key (or be NULL), with actions such as RESTRICT, CASCADE or SET NULL. NOT NULL, UNIQUE and CHECK are enforced by the database on every write, which is more reliable than checks scattered across services. A CHECK constraint sees one row at a time, so rules that span rows need something else: UNIQUE or exclusion constraints when the rule is uniqueness or non-overlap, and triggers or serializable transactions for rules such as "at least one doctor on call per shift".

Normalization. A functional dependency X → Y says equal X values imply equal Y values. When a non-key attribute depends on part of a key or on another non-key attribute, the same fact is stored repeatedly and updates can leave copies inconsistent. BCNF requires the left side of every non-trivial dependency to be a superkey; 3NF relaxes this slightly so that a dependency-preserving decomposition always exists. In R(student, course, instructor) where each instructor teaches one course, instructor → course violates BCNF. Practice: store each fact once, then denormalize deliberately (materialized views, cached counters, wide analytical tables) and say how the copies stay correct.

Common misconceptions

  • "SQL tables are sets." They are bags; joins that fan out make counts and sums wrong.
  • "NULL means zero or empty." It means unknown or missing; arithmetic with NULL yields NULL. Use COALESCE to substitute explicitly.
  • "NOT IN and NOT EXISTS are interchangeable." They differ as soon as the subquery can produce a NULL.
  • "A LEFT JOIN always keeps every left row." Only if no later WHERE condition rejects the NULL-padded rows.
  • "Normalization is about performance." It is about avoiding anomalies; denormalization is a separate, explicit tradeoff.
  • "ORDER BY in a subquery or view fixes the output order." Only the outermost ORDER BY defines the order of the final result.

How to approach it

Rebuild the rules with tiny tables you can evaluate by hand: three rows containing a duplicate and a NULL are enough to test everything above. Write the expected result before running each query. In interviews, state assumptions about uniqueness and NULLs aloud, check for fan-out before aggregating, and prefer NOT EXISTS for anti-joins. For schema questions, start from entities and keys, list the dependencies you believe hold, and say which constraints the database will enforce for you. Database-research interviews may go further into algebraic equivalences, for example why outer joins cannot always be reordered freely.

Suggested order

  1. 1Read CMU 15-445 Fall 2025 Lecture #01 notes (Relational Model & Algebra) and restate each operator with a three-row example of your own.
  2. 2Read Berkeley CS186 Note 1 (SQL Part 1 - Basic Queries) and Note 2 (SQL Part 2 - Joins & Subqueries), focusing on clause order, outer joins and correlated subqueries.
  3. 3Read the PostgreSQL pages Comparison Functions and Operators and Subquery Expressions for NULL comparisons, IS DISTINCT FROM and how IN and NOT IN treat NULLs.
  4. 4Work through CMU 15-445 Lecture #02 notes (Modern SQL) for aggregates, nested queries, lateral joins and common table expressions.
  5. 5Read CS186 Note 13 (DB Design) on functional dependencies and BCNF, then normalize one schema you know well on paper.
  6. 6Do CMU 15-445 Homework #1 (SQL) or a block of SQL 50 problems, predicting every result before running the query.
  7. 7Finish with the NULL-sensitive problems: solve Customers Who Never Order with both NOT IN and NOT EXISTS, then Second Highest Salary and Trips and Users.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • CMU 15-445/645 Intro to Database SystemsStart here

    Carnegie Mellon University Database Group

    Section: Fall 2025 Lecture #01: Relational Model & Algebra (notes)

    Relational model, keys and the core algebra operators in compact lecture notes; Lecture #02 covers modern SQL features.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Berkeley CS186 Database Systems course notesStart here

    UC Berkeley CS186

    Section: Note 2: SQL Part 2 - Joins & Subqueries

    Worked examples of inner, outer and natural joins and correlated subqueries; Note 13 covers functional dependencies and BCNF.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PostgreSQL documentation (current release)

    PostgreSQL Global Development Group

    Section: Subquery Expressions

    Exact rules for IN, NOT IN, EXISTS, ANY and ALL when a subquery returns NULLs; read with the Comparison Functions and Operators page.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • PostgreSQL documentation (current release)

    PostgreSQL Global Development Group

    Section: Constraints

    What CHECK, NOT NULL, UNIQUE, primary key, foreign key and exclusion constraints guarantee, including NULL handling in unique constraints.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Designing Data-Intensive Applications

    O'Reilly Media (author's book site)

    Section: Ch. 2: Data Models and Query Languages

    Relational versus document models and declarative querying, for schema-design discussions beyond pure SQL.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

Before running any query, write down the expected result on a tiny dataset that contains a duplicate and a NULL. Solve Customers Who Never Order twice (NOT IN and NOT EXISTS), then insert a NULL into the subquery column and explain the difference. For every aggregation, check whether a join can multiply rows before you SUM or COUNT. A problem counts as done when your query is right on edge cases you designed, not when it passes the sample.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1What do COUNT(*), COUNT(x) and SUM(x) return on a table where every x is NULL, and on an empty table?
  2. Question 2Why can a WHERE condition turn a LEFT JOIN into an inner join, and how do you avoid it?
  3. Question 3When do UNION and UNION ALL differ, and which is cheaper to compute?
  4. Question 4Why is a column alias defined in SELECT not visible in WHERE?
  5. Question 5In R(student, course, instructor) where each instructor teaches one course, which dependency violates BCNF and what decomposition fixes it?
  6. Question 6Which business rules can a CHECK constraint not enforce, and what are the alternatives?

You’re done when you can

  • Predict, without running them, the results of ten queries over a small table with duplicates and NULLs, with at most one mistake.
  • Explain in under two minutes why NOT IN returns no rows when the subquery contains a NULL, and rewrite the query with NOT EXISTS.
  • Normalize a five-attribute schema to BCNF from a given set of functional dependencies and say whether all dependencies are preserved.
  • Complete CMU 15-445 Homework #1 or ten SQL problems that include at least two outer-join and two NULL-sensitive queries.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Unlocks next: Transactions, isolation anomalies and MVCC, Indexes, B+ trees, LSM trees and Bloom filters

Your notes and study time

Log study time