AlgoViz

IS-A and HAS-A

easy 40 min

IS-A says that an object is a kind of something and can stand in for it.

Watch lesson4:45

Storing relations

IS-A and HAS-A in tables: three mappings for one, two for the other.

The point: tables have no IS-A. You choose which price to pay: empty columns, joins, or repeated columns.

IS-A

Three ways to store a hierarchy

MappingTables for Payment, Card, TransferGoodBad
Single tablepayment(id, kind, amount, last4, iban)One read, easy list of allColumns empty for other kinds, hard to demand last4 for cards
Class tablepayment(id, amount), card(id, last4), transfer(id, iban)Every column has a meaningA join per read, two writes
Concrete tablecard(id, amount, last4), transfer(id, amount, iban)No join for one kindAll payments need a union, ids must be unique across tables
The names follow the catalogue of Patterns of Enterprise Application Architecture.
SQL
CREATE TABLE payment (  id      bigint PRIMARY KEY,  kind    text NOT NULL CHECK (kind IN ('card', 'transfer')),  cents   integer NOT NULL CHECK (cents > 0),  last4   text,  iban    text,  CHECK ((kind = 'card'     AND last4 IS NOT NULL AND iban IS NULL)      OR (kind = 'transfer' AND iban IS NOT NULL AND last4 IS NULL)));
A single table can still protect itself with a check. Each kind names its own required columns.

HAS-A

Column, table or document

PartStore asBecause
Address of an orderColumns or JSON in the orderNo identity, read with the order
Lines of an orderTable with a foreign key, deleted togetherMany, owned
Customer of an orderForeign key, never deleted togetherLives on its own
Roles of a personTable with since and untilHistory is asked for
Which delete rule belongs to which relation is worked out on Aggregation vs composition.

Eight payment kinds, mostly read as one list, each with two or three own fields. Which mapping?

BreaksConcrete tables
How
Eight tables.
Limit
The list is a union of eight, and paging over it is slow.
Choose when
Kinds are never read together.
WorksClass tables
How
One base table and eight small ones.
Limit
The list needs no join, details need one. Inserts write twice.
Choose when
Strict columns matter more than writes.
StrongSingle table with checks, or a JSON column for the own fields
How
One read per page, a check per kind.
Limit
Wide rows. Constraints inside JSON are harder.
Choose when
The list is the main read, as here.