IS-A and HAS-A
easy 40 minIS-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
| Mapping | Tables for Payment, Card, Transfer | Good | Bad |
|---|---|---|---|
| Single table | payment(id, kind, amount, last4, iban) | One read, easy list of all | Columns empty for other kinds, hard to demand last4 for cards |
| Class table | payment(id, amount), card(id, last4), transfer(id, iban) | Every column has a meaning | A join per read, two writes |
| Concrete table | card(id, amount, last4), transfer(id, amount, iban) | No join for one kind | All payments need a union, ids must be unique across tables |
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)));HAS-A
Column, table or document
| Part | Store as | Because |
|---|---|---|
| Address of an order | Columns or JSON in the order | No identity, read with the order |
| Lines of an order | Table with a foreign key, deleted together | Many, owned |
| Customer of an order | Foreign key, never deleted together | Lives on its own |
| Roles of a person | Table with since and until | History is asked for |
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.