ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume I
  5. Relational Database Concepts
Book 6 · Volume I — Database Fundamentals & Relational Data Modeling · Topic 1.4

Relational Database Concepts

Tables, rows, columns, domains and relationships

10 min readStage 3 · Systems8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Relational Operations
  5. 4A. Deep Dive — Relational Model vs Object Model
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 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.

Anatomy of a relational table
Figure 1 — Anatomy of a relational table
Terminology: relational theory, SQL and everyday use
Figure 2 — Terminology: relational theory, SQL and everyday use

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 ruleSQL reality
A relation is a set — no duplicate tuplesSQL tables can contain duplicates unless a key is declared → always declare a primary key
Tuples are unorderedRows have no guaranteed order → use ORDER BY
Attributes are unorderedColumns 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
Table 1 — Theory vs SQL
SQL
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 principleExample
One row per real-world instanceOne row per product, not per product-colour-size unless that is the thing sold
Identified by a keyproduct_id (and sku as alternate key)
Complete for its table's meaningMandatory attributes NOT NULL
No hidden meaning in positionOrder of rows irrelevant
Table 2 — Row principles

3.3 Columns

A column (attribute) is a named property with a type; every row has a value (or NULL) for every column.

Column guidelineReason
Atomic values (one value per cell)Queryable, constrainable (1NF — Chapter 3)
Specific types (DATE, NUMERIC, BOOLEAN), not strings for everythingValidation, sorting, indexing, storage
Explicit nullabilityNULL 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
Table 3 — Column guidelines

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.

SQL
-- 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 conceptSQL mechanismJava counterpart
Base typeINTEGER, NUMERIC, TEXT, DATE, TIMESTAMPTZ, UUID, JSONBint, BigDecimal, String, LocalDate, Instant, UUID
Restricted valuesCHECK, CREATE DOMAIN, enums, lookup tablesRecords with validation, enums
Precision/scaleNUMERIC(12,2)BigDecimal with scale
Time semanticsTIMESTAMPTZ (instant) vs TIMESTAMP (local)Instant/OffsetDateTime vs LocalDateTime
Table 4 — Domains across layers

Money: never FLOAT/DOUBLE; use NUMERIC in SQL and BigDecimal (or a Money value object) in Java.

3.5 Relationships

Relationships through shared values
Figure 3 — Relationships through shared values

A relationship is represented by a foreign key column whose values match a key in another table. Joins recombine related rows at query time.

SQL
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 aspectMechanism
RepresentationFK column(s) holding parent key values
IntegrityREFERENCES constraint (Topic 2.4)
NavigationJOIN (inner, left, …)
Cardinality1:1, 1:N, M:N (Topic 2.3)
Table 5 — Relationships

4How It Works Internally — Relational Operations

Relational operations
Figure 4 — Relational operations

Every SQL query is an expression in relational algebra that the optimizer can reorder:

AlgebraSQLOptimizer freedom
σ (select rows)WHEREPush filters down before joins
π (project columns)SELECT col listRead fewer columns (index-only scans)
⋈ (join)JOIN … ONChoose join order and algorithm (nested loop, hash, merge)
γ (group/aggregate)GROUP BYHash or sort aggregation
∪, ∩, −UNION, INTERSECT, EXCEPTSet operations
Table 6 — Algebra and SQL

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

ConceptRelationalObject (Java)Mismatch
IdentityKey valuesObject reference (==) and equalsMust map keys to identity
RelationshipsFK values, bidirectional by queryReferences, one direction unless modelled both waysORM associations, lazy loading
InheritanceNo native conceptClass hierarchiesSingle table / joined / table-per-class strategies
GranularityTables of flat rowsNested objects, value objectsEmbeddables, JSON columns
NavigationSet-based joinsPointer chasingN+1 queries
TypesSQL types, NULLJava types, OptionalConverters
Table 7 — Object–relational impedance mismatch
JAVA
// 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

FeaturePurpose
CREATE TABLE, ALTER TABLEDefine relations
Data types, CREATE DOMAIN, CREATE TYPE … AS ENUMDomains
PRIMARY KEY, UNIQUE, REFERENCES, CHECKKeys and integrity
JOIN, WHERE, GROUP BY, set operatorsRelational operations
information_schema, \d table (psql)Inspect schema
JPA @Entity, @Column, @ManyToOne; Spring Data JDBC @TableJava mappings
Table 8 — SQL and Java features

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.

ProblemRelational fix
Repeating groups (Product 1..3)order_line table, one row per product
Customer data repeated per ordercustomer table referenced by FK
Phone as free textindian_mobile domain
No identifiersSurrogate keys + natural alternate keys
Table 9 — Spreadsheet to relations
SQL
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

AttributePoor choiceBetter choiceWhy
Order amountDOUBLENUMERIC(14,2)Exact decimal arithmetic
Order timeTIMESTAMP (no zone)TIMESTAMPTZUnambiguous instant across regions
StatusVARCHAR(50) free textCHECK (status IN (…)) or enum/lookup tableValid values only
GSTINVARCHAR(255)CHAR(15) + pattern CHECKCorrect length and format
FlagsCHAR(1) 'Y'/'N'BOOLEANNative semantics
Attributes varying per product type20 nullable columnsCore columns + JSONB for variable specsFlexible without losing core integrity
Table 10 — Type and domain choices

6.5 Worked example — NULL pitfalls

SQL
-- 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;
RuleRecommendation
Make columns NOT NULL by defaultAllow NULL only with a clear meaning
Avoid "magic values" instead of NULLNo '1900-01-01' for unknown dates
Use Optional in Java for nullable columnsMakes absence explicit
Table 11 — Handling NULL

6.6 Worked example — the same relations queried three ways from Java

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);
ApproachRelational concepts exposedBest for
SQL + recordsTables, joins, aggregates explicitlyReports, projections, performance-critical reads
JPA/JPQLEntities over tables; joins via associationsRich domain models with changing state
Spring Data JDBCAggregates mapped to tables, references by idSimpler DDD-style aggregates
Table 12 — Mapping options over the same relations

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

AspectNote
Narrow, well-typed columnsSmaller rows → more rows per page → fewer I/Os
Large valuesTOAST moves them out of line; avoid selecting them unnecessarily
ProjectionSelect only needed columns (enables index-only scans)
Type mismatches in joinsImplicit casts can prevent index use
Table 13 — Performance implications

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicConcept

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.

Q3L2 · IntermediateInternals

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.

Q4L2 · IntermediateTricky

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.

Q5L3 · Senior EngineerTricky

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.

Q6L3 · Senior EngineerConcept

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.

Q7L4 · Technical ArchitectTrade-off

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.

Q8L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.