- Chapter
- Chapter 1 — Database Fundamentals
- Prerequisites
- Topics 1.1–1.3
- You will be able to
- Define relations, tuples, attributes and domains precisely, relate them to SQL tables, rows and columns, choose appropriate data types and domains, understand how relationships are represented by values and recombined by joins, and map these concepts to Java/JPA
- Covers
- Tables; Rows; Columns; Domains; Relationships
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Relational Operations
- 4A. Deep Dive — Relational Model vs Object Model
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
The relational model (E. F. Codd, 1970) represents data as relations: sets of tuples sharing the same attributes, each attribute drawing values from a domain. SQL implements relations as tables of rows and columns, and relationships as matching key values.


2Why It Exists
Earlier hierarchical and network databases linked records with physical pointers; programs navigated those pointers, so any change to storage structure broke applications. Codd's insight was to base data management on mathematics (set theory and predicate logic): a simple, uniform structure and a declarative language let the DBMS choose access paths itself. Fifty years later, this model underpins most business systems.
3Core Concepts
3.1 Tables
A table (relation) represents one kind of thing or fact: customers, orders, enrolments.
| Relational rule | SQL reality |
|---|---|
| A relation is a set — no duplicate tuples | SQL tables can contain duplicates unless a key is declared → always declare a primary key |
| Tuples are unordered | Rows have no guaranteed order → use ORDER BY |
| Attributes are unordered | Columns have a defined order in SQL, but queries should name columns (no SELECT * in code) |
| Every relation has a heading (schema) and body (rows) | CREATE TABLE defines the heading |
CREATE TABLE product (
product_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku VARCHAR(20) NOT NULL UNIQUE,
name VARCHAR(200) NOT NULL,
hsn_code CHAR(8) NOT NULL,
list_price NUMERIC(12,2) NOT NULL CHECK (list_price >= 0),
active BOOLEAN NOT NULL DEFAULT true
);3.2 Rows
A row (tuple) is one instance: one product, one order. Each row should represent one fact about the thing the table describes, identified by its key.
| Row design principle | Example |
|---|---|
| One row per real-world instance | One row per product, not per product-colour-size unless that is the thing sold |
| Identified by a key | product_id (and sku as alternate key) |
| Complete for its table's meaning | Mandatory attributes NOT NULL |
| No hidden meaning in position | Order of rows irrelevant |
3.3 Columns
A column (attribute) is a named property with a type; every row has a value (or NULL) for every column.
| Column guideline | Reason |
|---|---|
| Atomic values (one value per cell) | Queryable, constrainable (1NF — Chapter 3) |
Specific types (DATE, NUMERIC, BOOLEAN), not strings for everything | Validation, sorting, indexing, storage |
| Explicit nullability | NULL means unknown/not applicable — decide deliberately |
Clear, consistent naming (snake_case, singular) | Readability across teams and tools |
Units in names or types (amount_inr, weight_g) | Avoid ambiguity |
NULL semantics (three-valued logic): NULL = NULL is unknown, not true; use IS NULL, IS DISTINCT FROM. Aggregates ignore NULLs; UNIQUE allows multiple NULLs (PostgreSQL 15+: UNIQUE NULLS NOT DISTINCT to change that).
3.4 Domains
A domain is the set of allowed values for an attribute: a data type plus constraints.
-- Reusable domains in PostgreSQL
CREATE DOMAIN money_inr AS NUMERIC(14,2) CHECK (VALUE >= 0);
CREATE DOMAIN indian_mobile AS VARCHAR(10) CHECK (VALUE ~ '^[6-9][0-9]{9}$');
CREATE DOMAIN email_address AS VARCHAR(254) CHECK (VALUE ~* '^[^@\s]+@[^@\s]+\.[^@\s]+$');
CREATE TABLE customer (
customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email email_address NOT NULL UNIQUE,
mobile indian_mobile,
credit money_inr NOT NULL DEFAULT 0
);| Domain concept | SQL mechanism | Java counterpart |
|---|---|---|
| Base type | INTEGER, NUMERIC, TEXT, DATE, TIMESTAMPTZ, UUID, JSONB | int, BigDecimal, String, LocalDate, Instant, UUID |
| Restricted values | CHECK, CREATE DOMAIN, enums, lookup tables | Records with validation, enums |
| Precision/scale | NUMERIC(12,2) | BigDecimal with scale |
| Time semantics | TIMESTAMPTZ (instant) vs TIMESTAMP (local) | Instant/OffsetDateTime vs LocalDateTime |
Money: never FLOAT/DOUBLE; use NUMERIC in SQL and BigDecimal (or a Money value object) in Java.
3.5 Relationships

A relationship is represented by a foreign key column whose values match a key in another table. Joins recombine related rows at query time.
SELECT o.order_id, c.full_name, o.total
FROM purchase_order o
JOIN customer c ON c.customer_id = o.customer_id
WHERE o.placed_at >= DATE '2026-09-01';| Relationship aspect | Mechanism |
|---|---|
| Representation | FK column(s) holding parent key values |
| Integrity | REFERENCES constraint (Topic 2.4) |
| Navigation | JOIN (inner, left, …) |
| Cardinality | 1:1, 1:N, M:N (Topic 2.3) |
4How It Works Internally — Relational Operations

Every SQL query is an expression in relational algebra that the optimizer can reorder:
| Algebra | SQL | Optimizer freedom |
|---|---|---|
| σ (select rows) | WHERE | Push filters down before joins |
| π (project columns) | SELECT col list | Read fewer columns (index-only scans) |
| ⋈ (join) | JOIN … ON | Choose join order and algorithm (nested loop, hash, merge) |
| γ (group/aggregate) | GROUP BY | Hash or sort aggregation |
| ∪, ∩, − | UNION, INTERSECT, EXCEPT | Set operations |
Because queries describe what, the DBMS can change how (indexes, join algorithms) without changing application code — the payoff of the relational model.
4ADeep Dive — Relational Model vs Object Model
| Concept | Relational | Object (Java) | Mismatch |
|---|---|---|---|
| Identity | Key values | Object reference (==) and equals | Must map keys to identity |
| Relationships | FK values, bidirectional by query | References, one direction unless modelled both ways | ORM associations, lazy loading |
| Inheritance | No native concept | Class hierarchies | Single table / joined / table-per-class strategies |
| Granularity | Tables of flat rows | Nested objects, value objects | Embeddables, JSON columns |
| Navigation | Set-based joins | Pointer chasing | N+1 queries |
| Types | SQL types, NULL | Java types, Optional | Converters |
// Spring Data JDBC: an aggregate maps naturally to tables without lazy-loading surprises
@Table("purchase_order")
public record PurchaseOrder(
@Id Long orderId,
AggregateReference<Customer, Long> customerId,
Instant placedAt,
@MappedCollection(idColumn = "order_id") List<OrderLine> lines) {}
public record OrderLine(Long productId, int quantity, BigDecimal unitPrice) {}Design relationally first; then choose the mapping (JPA entities, Spring Data JDBC aggregates, or SQL with records) that respects the relational structure.
5APIs / Features / Syntax
| Feature | Purpose |
|---|---|
CREATE TABLE, ALTER TABLE | Define relations |
Data types, CREATE DOMAIN, CREATE TYPE … AS ENUM | Domains |
PRIMARY KEY, UNIQUE, REFERENCES, CHECK | Keys and integrity |
JOIN, WHERE, GROUP BY, set operators | Relational operations |
information_schema, \d table (psql) | Inspect schema |
JPA @Entity, @Column, @ManyToOne; Spring Data JDBC @Table | Java mappings |
6Practical Examples
6.1 Strings for everything
A legacy table stored dates as VARCHAR in three formats and amounts as strings with commas; reports mis-sorted and summed incorrectly. Migrating to DATE and NUMERIC with validation fixed reporting and enabled indexes.
6.2 Missing primary key
A log table without a key accumulated duplicate rows from retries; deduplication required a full-table rewrite. Adding a key (and an idempotency column) prevented recurrence.
6.3 Worked example — from a spreadsheet to relational tables
Spreadsheet columns: Customer Name, Customer Phone, Order Date, Product 1, Qty 1, Product 2, Qty 2, Product 3, Qty 3.
| Problem | Relational fix |
|---|---|
| Repeating groups (Product 1..3) | order_line table, one row per product |
| Customer data repeated per order | customer table referenced by FK |
| Phone as free text | indian_mobile domain |
| No identifiers | Surrogate keys + natural alternate keys |
CREATE TABLE customer (customer_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
full_name VARCHAR(200) NOT NULL, mobile indian_mobile UNIQUE);
CREATE TABLE purchase_order (order_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id BIGINT NOT NULL REFERENCES customer,
order_date DATE NOT NULL);
CREATE TABLE order_line (order_id BIGINT REFERENCES purchase_order ON DELETE CASCADE,
line_no SMALLINT, product_id BIGINT NOT NULL REFERENCES product,
quantity INT NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, line_no));6.4 Worked example — choosing types and domains
| Attribute | Poor choice | Better choice | Why |
|---|---|---|---|
| Order amount | DOUBLE | NUMERIC(14,2) | Exact decimal arithmetic |
| Order time | TIMESTAMP (no zone) | TIMESTAMPTZ | Unambiguous instant across regions |
| Status | VARCHAR(50) free text | CHECK (status IN (…)) or enum/lookup table | Valid values only |
| GSTIN | VARCHAR(255) | CHAR(15) + pattern CHECK | Correct length and format |
| Flags | CHAR(1) 'Y'/'N' | BOOLEAN | Native semantics |
| Attributes varying per product type | 20 nullable columns | Core columns + JSONB for variable specs | Flexible without losing core integrity |
6.5 Worked example — NULL pitfalls
-- Returns no rows even for customers with NULL city: NULL <> 'Pune' is UNKNOWN
SELECT * FROM customer WHERE city <> 'Pune';
-- Correct intent
SELECT * FROM customer WHERE city IS DISTINCT FROM 'Pune';
-- COUNT(*) counts rows; COUNT(city) counts non-NULL cities
SELECT count(*), count(city) FROM customer;| Rule | Recommendation |
|---|---|
| Make columns NOT NULL by default | Allow NULL only with a clear meaning |
| Avoid "magic values" instead of NULL | No '1900-01-01' for unknown dates |
Use Optional in Java for nullable columns | Makes absence explicit |
6.6 Worked example — the same relations queried three ways from Java
// 1) Plain SQL with JdbcClient → records (full control, no ORM)
record OrderSummary(long orderId, String customer, BigDecimal total) {}
List<OrderSummary> recent = jdbc.sql("""
SELECT o.order_id, c.full_name AS customer,
sum(l.quantity * l.unit_price) AS total
FROM purchase_order o
JOIN customer c ON c.customer_id = o.customer_id
JOIN order_line l ON l.order_id = o.order_id
WHERE o.order_date >= :from
GROUP BY o.order_id, c.full_name
ORDER BY o.order_id""")
.param("from", LocalDate.now(clock).minusDays(7))
.query(OrderSummary.class)
.list();
// 2) JPA entity navigation (convenient, watch for N+1)
@Query("""
select new com.shop.OrderSummary(o.id, c.fullName, sum(l.quantity * l.unitPrice))
from Order o join o.customer c join o.lines l
where o.orderDate >= :from
group by o.id, c.fullName order by o.id""")
List<OrderSummary> recentSummaries(LocalDate from);
// 3) Spring Data JDBC aggregate load (whole aggregate, no lazy loading)
Optional<PurchaseOrder> order = orders.findById(5001L);| Approach | Relational concepts exposed | Best for |
|---|---|---|
| SQL + records | Tables, joins, aggregates explicitly | Reports, projections, performance-critical reads |
| JPA/JPQL | Entities over tables; joins via associations | Rich domain models with changing state |
| Spring Data JDBC | Aggregates mapped to tables, references by id | Simpler DDD-style aggregates |
All three work because the underlying relational design — keys, foreign keys, domains — is sound; none of them can rescue a poorly designed schema.
7Common Problems & Mistakes
- Tables without primary keys.
- Everything as VARCHAR; money as floating point.
- SELECT * in application code — fragile to schema changes.
- Relying on row order without
ORDER BY. - Nullable by default and misunderstood three-valued logic.
- Designing tables from Java classes instead of from the domain's relations.
8Performance & Production Considerations
| Aspect | Note |
|---|---|
| Narrow, well-typed columns | Smaller rows → more rows per page → fewer I/Os |
| Large values | TOAST moves them out of line; avoid selecting them unnecessarily |
| Projection | Select only needed columns (enables index-only scans) |
| Type mismatches in joins | Implicit casts can prevent index use |
9Architecture & Design Considerations
- Model relations from the domain, with keys and domains, before writing entities.
- Use precise types and domains as the first line of data quality.
- Make relationships explicit with foreign keys.
- Choose a mapping approach (JPA, Spring Data JDBC, SQL + records) that respects the relational design.
10Interview Questions & Answers
What is a relation in the relational model?
A relation is a set of tuples that all share the same heading, meaning the same named attributes, each drawing its values from a domain. Codd defined it mathematically in 1970, and SQL implements it as a table: the heading is the CREATE TABLE definition, the tuples are rows and the attributes are columns. Because a relation is a set, its tuples are unordered and unique, and attribute order carries no meaning. SQL relaxes both rules: tables can hold duplicate rows unless a key is declared, and rows come back in no guaranteed order without ORDER BY. Declaring a primary key and naming columns explicitly keeps a table behaving like a true relation.
What is a domain?
A domain is the set of values an attribute is allowed to take: a base data type plus the constraints that narrow it. NUMERIC(14,2) with CHECK (VALUE >= 0) is a domain for money; a ten-digit string starting with 6 to 9 is a domain for an Indian mobile number. PostgreSQL lets you name one with CREATE DOMAIN and reuse it across tables, so the rule lives in one place and every column using it is validated identically. Enums and lookup tables are other ways to express a restricted domain. In Java the counterpart is a precise type, such as BigDecimal or a validating record, so the same rule holds in both layers.
How are relationships represented in a relational database?
Relationships are represented purely by values. A child table holds a foreign key column whose values match the primary key of a parent row, for example purchase_order.customer_id pointing at customer.customer_id. There are no stored pointers between records, so the database does not navigate links; it recombines related rows at query time with a join on matching values, and the optimizer is free to choose a nested loop, hash or merge join. A REFERENCES constraint makes the database reject orphan values. One-to-many uses a foreign key on the many side, and many-to-many needs a junction table holding two foreign keys, typically with a composite primary key.
Why should every table have a primary key?
A primary key gives every row a stable, unique identity, which the relational model assumes but SQL does not enforce on its own: a table without a key happily stores identical duplicate rows. Without a key you cannot reliably update or delete one specific row, foreign keys have nothing to reference, and ORMs such as JPA cannot map identity at all. Retries are the classic way duplicates appear, as in a log table that collects the same event twice. In PostgreSQL, logical replication also needs a key or replica identity to apply updates and deletes. Use a surrogate identity key plus a UNIQUE constraint on the natural key where one exists.
Why use NUMERIC and BigDecimal for money?
FLOAT and DOUBLE are binary floating point, so most decimal fractions, such as 0.1, cannot be represented exactly; sums drift by tiny amounts, and a comparison like 0.1 + 0.2 = 0.3 is false. For money that means invoices and ledgers that disagree by paise, which auditors will find. NUMERIC stores exact decimal digits with a declared precision and scale, and BigDecimal does the same in Java, so arithmetic and rounding follow rules you choose, such as HALF_EVEN. Create BigDecimal from strings or valueOf, never new BigDecimal(0.1), and compare with compareTo, because equals also compares scale. Keep the currency explicit with a column or a Money value object.
What is the object–relational impedance mismatch?
It is the set of structural differences between Java's object model and the relational model that every mapping layer has to bridge. Objects have identity by reference, relations by key values. Objects link with one-directional references and navigate by pointer chasing, while relations link by foreign key values and recombine with set-based joins. Java has inheritance and nested value objects; tables have flat rows and no inheritance, so JPA offers single-table, joined and table-per-class strategies plus embeddables. NULL versus Optional and type conversions add more friction. The practical consequences are N+1 queries, lazy-loading surprises and awkward schemas generated from classes, which is why the schema should be designed first.
When would you use JSONB in a relational table?
Use JSONB for attributes that genuinely vary and that you rarely constrain or join on, such as product specifications that differ by category, partner payloads stored for audit, or user preferences. Keep everything the business depends on, like identifiers, prices, status and foreign keys, in typed columns with constraints, because JSONB gives up NOT NULL, CHECK, foreign keys and accurate planner statistics for its contents. A GIN index supports containment queries, and an expression index helps a hot path. If you find yourself filtering, joining or reporting on the same JSON key everywhere, promote it to a real column. JSONB complements a relational design; it should not replace one.
Why design the relational model before the Java entities?
The data model usually outlives the application that first writes it. A schema serves many consumers over decades: several services, reporting, analytics, data pipelines and future rewrites in other languages, while the Java entity layer may be replaced within a few years. Designing from the domain's relations, with keys, domains and foreign keys, gives integrity that holds regardless of which code writes the data. Generating tables from entities tends to leak ORM concerns into the schema, such as inheritance tables, missing constraints and vague types. So I design and review the relational model, ship it through Flyway or Liquibase migrations, and then choose JPA, Spring Data JDBC or SQL with records to map it.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.