schema anti-patterns
entity-attribute-value, polymorphic foreign keys, comma lists in a column, and the table called data.
- address
- everything.design.anti_patterns
- part
- part 7, schema design
- chapter
- chapter 11 of 13
- reading time
- 8 min
most schema anti-patterns are the same mistake in different clothes: data the database could check is stored where it can't. an EAV table turns columns into rows and every value into text. a polymorphic reference names its target table in a string, so no foreign key can follow it. a comma list hides a relationship inside one value. a missing foreign key lets orphans in quietly.
and the table per tenant multiplies the catalog instead of the rows. each one has a real query that goes wrong, and a fix that's ordinary SQL.
the picture
you know the schema that started "flexible"? an attributes table so nobody needs a migration, a type column so one comments table serves everything, tags in a string because a join table felt heavy. each saved ten minutes on day one, and each turned a database error into a silent wrong answer later.
think of a filing cabinet where, to save buying folders (tables and columns), everything goes into one big drawer, with a sticky note on each sheet saying what it is (a type column, an attribute name). it's flexible. it's also the drawer where a sheet labelled "colour" is never found by someone looking for "color".
- 1SELECT n.value AS name, p.value AS price
- 2FROM product_attrs AS n
- 3JOIN product_attrs AS p ON p.product_id = n.product_id AND p.attr = 'price'
- 4JOIN product_attrs AS c ON c.product_id = n.product_id AND c.attr = 'color'
- 5WHERE n.attr = 'name' AND c.value = 'red' AND p.value < '9.50'
- 6ORDER BY n.product_id;
| nametext | pricetext |
|---|---|
| assam tea | 6.50 |
| teapot | 45.00 |
red products under 9.50: a self-join per attribute, and a text comparison. as strings '45.00' < '9.50', so the teapot sneaks in, and the tea towel is lost to a misspelled attribute name.
entity-attribute-value
EAV stores (entity, attribute, value) triples: one row per cell. every value is text, so comparisons are string comparisons ('45.00' < '9.50' is true), every attribute you filter on is another self-join, a misspelled attribute name is just another row, and nothing can be NOT NULL, CHECKed or a foreign key. the planner can't estimate any of it, because every attribute shares one value column's statistics.
the fix is columns. if the attributes really vary per row (product specs from a hundred suppliers), use real columns for what you query and constrain, and a jsonb column for the long tail: it keeps types (a number stays a number), can be indexed with GIN, and lives in the row instead of in N joins.
CREATE TABLE products (id int PRIMARY KEY, name text NOT NULL, price numeric(8,2) NOT NULL, specs jsonb NOT NULL DEFAULT '{}');
INSERT INTO products VALUES
(1, 'assam tea', 6.50, '{"color": "red", "caffeine_mg": 40}'),
(2, 'teapot', 45.00, '{"color": "red", "litres": 1.2}');
SELECT name, price FROM products WHERE specs ->> 'color' = 'red' AND price < 9.50 ORDER BY id;| nametext | pricenumeric |
|---|---|
| assam tea | 6.50 |
polymorphic associations
(target_type, target_id) is a foreign key that postgres can't see: the table it points into depends on a string. so a comment on post 99, which never existed, is accepted, and deleting a post leaves its comments behind. a CHECK can't help, because it can't look at other tables.
num_nonnulls(post_id, photo_id) = 1 keeps "exactly one target" true. with many target types, the other fixes are a junction table per target (post_comments, photo_comments) or a shared parent table ("commentables") that every target gets a row in, so the comment has one ordinary foreign key.
comma-separated lists
a list in a string is a relationship you can't join on. LIKE '%red%' finds infrared. 'red, garden' with a space is a different tag. counting articles per tag means splitting every row first, and no index helps. the fix is the junction table from from requirements to tables: one row per (article, tag), with a primary key that stops duplicates.
-- tags: 'red,garden' / 'infrared,tech' / 'fruit,red'
SELECT count(*) FROM articles WHERE tags LIKE '%red%';an array column (tags text[]) is the middle ground: 'red' = ANY(tags) is exact, and a GIN index serves tags @> '{red}'. it still can't have a foreign key to a tags table, so it suits free-form labels better than references (arrays).
missing foreign keys
"we enforce it in the app" lasts until a script, a second service or a manual DELETE disagrees. then orphan rows sit there, and every inner join drops them without a word: the revenue report in the figure is short by two orders and nobody gets an error. finding them is an anti join; fixing them is a decision (delete, reassign, or restore the parent); then add the constraint. on a big table, add it NOT VALID first so new orphans stop immediately, and VALIDATE once the old ones are gone (foreign keys).
a table per tenant
giving every customer of a SaaS app its own copy of every table feels like isolation. it's a catalog explosion: each table brings its primary key index, a TOAST table and its index, statistics, and an entry in every planner lookup and every pg_dump. here's 100 tenants with one small orders table each:
thousands of tenants means hundreds of thousands of relations, slow backups, autovacuum spread thin across tiny tables, and migrations that can half-apply. the usual design is one set of tables with a tenant_id column leading every key and index, with row-level security so a missing WHERE tenant_id = ... can't leak data. schema-per-tenant sits between the two and has the same catalog cost; a database per tenant makes sense only for a few large, contractually separated customers.
keylines
- every anti-pattern here hides from the database something it could have checked.
- EAV: text values, a join per attribute, no constraints. use columns, plus jsonb for the long tail.
- polymorphic references can't have foreign keys: one nullable FK per target, CHECK exactly one.
- comma lists and missing FKs give wrong answers silently, not errors.
- table per tenant multiplies the catalog; use tenant_id and row-level security.