A production table with 136 columns has exactly two CHECK constraints. One of them is marked NOT VALID, which in PostgreSQL means the planner enforces it for new rows but the system has never verified it against the rows already there.

That single flag is the whole story in miniature. Every other guarantee this table appears to make — that a settled prediction has an outcome, that a direction is one of three values, that a probability is between 0 and 1 — is made by application code, or by convention, or by nobody.

This is an audit of constraint coverage in a live football-prediction database: 1,803 tables, 31,173 columns, roughly 170 million rows, read from the catalogs and the tables on 2026-12-05. Every query is included so you can rerun it.

Counting what the engine actually enforces

Constraint coverage is not something you feel; it is something you count. pg_constraint holds one row per rule, tagged by contype (p, u, f, c), and pg_attribute.attnotnull marks declared non-null columns.

Quantity Count Coverage
Tables in public 1,803 —
Columns 31,173 —
Columns declared NOT NULL 4,714 15.12%
Primary keys 1,333 471 tables have none (26.13%)
UNIQUE constraints 314 17.41% per table
Foreign keys 107 1,723 tables have none (95.56%)
CHECK constraints 29 25 tables have one (1.39%)
Domains 0 —

Twenty-nine rules, for 31,173 columns. That is one CHECK for every 1,075 columns, and the ones that exist are concentrated on small administrative tables: agent status, message type, pricing tiers. The tables that carry the analytical weight have none.

The pattern is worse than the aggregate suggests. Restrict to tables estimated above one million rows and the constraint count is not lower per table — it is zero: 32 tables, 131,116,593 estimated rows, no CHECK at all. Those 32 tables hold 77.1% of the 169,987,643 rows in the schema. The busiest data in the system is the least constrained data in the system, which is not a coincidence: those are the tables where a failed INSERT costs money, so every rule that could reject a write was moved out of the database and into a try/except.

The one flag that tells you nobody checked

ai_predictions is the table everything downstream reads. It has 136 columns, 6 NOT NULL declarations (id, match_id, settled, created_at, updated_at, is_tainted), zero foreign keys, and two CHECK constraints.

One is chk_analysis_type, eight allowed strings, convalidated = true. The other is ck_ah_none_no_hit, and convalidated = false. It was added with NOT VALID — a legitimate technique for rolling out a rule on a hot table — and then never validated.

The flag matters because it changes what the schema means. A validated constraint is a statement about the past: every row satisfies this. A NOT VALID constraint is a statement about the future only. So we checked by hand:

SELECT count(*) AS rows, count(*) FILTER ( WHERE asian_handicap_direction = 'none' AND asian_handicap_hit IS NOT NULL ) AS would_fail FROM ai_predictions; 

52,569 rows, 0 failures. The rule holds — but the database does not promise it, and nobody had established that it did. Correct and unverified at once is the normal end state of a constraint nobody revisits.

Building a debt ledger instead of an opinion

"Add more constraints" is advice, not a plan. A plan needs a price per rule: for any candidate constraint, the price is the number of existing rows that would block VALIDATE. One query answers it for the whole table:

WITH checks AS ( SELECT 'unique (model_id, match_id)' AS rule, count(*) AS violators FROM (SELECT 1 FROM ai_predictions GROUP BY model_id, match_id HAVING count(*) > 1) d UNION ALL SELECT 'confidence between 1 and 10', count(*) FROM ai_predictions WHERE confidence NOT BETWEEN 1 AND 10 UNION ALL SELECT 'confidence_calibrated between 0 and 1', count(*) FROM ai_predictions WHERE confidence_calibrated NOT BETWEEN 0 AND 1 UNION ALL SELECT 'not settled => hit is null', count(*) FROM ai_predictions WHERE NOT settled AND hit IS NOT NULL UNION ALL SELECT '1/fair_* sums to 1 (+/- 5%)', count(*) FROM ai_predictions WHERE fair_home > 0 AND fair_away > 0 AND fair_draw > 0 AND abs(1/fair_home + 1/fair_away + 1/fair_draw - 1) > 0.05 UNION ALL SELECT 'match_id -> nami_matches(id)', count(*) FROM ai_predictions p WHERE NOT EXISTS (SELECT 1 FROM nami_matches m WHERE m.id = p.match_id) UNION ALL SELECT 'settled => hit is not null', count(*) FROM ai_predictions WHERE settled AND hit IS NULL UNION ALL SELECT 'model_id -> ai_models(id)', count(*) FROM ai_predictions p WHERE NOT EXISTS (SELECT 1 FROM ai_models m WHERE m.id = p.model_id) UNION ALL SELECT 'direction in (home, away, draw)', count(*) FROM ai_predictions WHERE prediction_direction NOT IN ('home', 'away', 'draw') UNION ALL SELECT 'fair_* between 0 and 1', count(*) FROM ai_predictions WHERE fair_home > 1 OR fair_away > 1 OR fair_draw > 1 ) SELECT rule, violators FROM checks ORDER BY violators, rule; 
Candidate rule Rows that block VALIDATE Share of 52,569
UNIQUE (model_id, match_id) 0 0.00%
confidence BETWEEN 1 AND 10 0 0.00%
confidence_calibrated BETWEEN 0 AND 1 0 0.00%
NOT settled => hit IS NULL 1 0.002%
1/fair_* sums to 1 (5% tolerance) 35 0.07%
match_id -> nami_matches 63 0.12%
settled => hit IS NOT NULL 74 0.14%
model_id -> ai_models 4,854 9.23%
direction IN (home, away, draw) 17,777 33.82%
fair_* BETWEEN 0 AND 1 51,699 98.34%

The two rules that describe a different table

The direction IN ('home', 'away', 'draw') check is the first thing any reasonable person writes, and it rejects a third of the table. The actual distribution is:

Value Rows
home 22,290
away 12,143
away/draw 11,603
home/draw 6,093
draw 359
none 81

Six values in a column whose name says direction. The two double-chance labels were added silently by a writer that needed them, and because nothing declared the label space, nothing objected. 17,777 rows now live in a vocabulary every downstream report assumes does not exist. That is what a missing constraint buys you: not chaos, just an undocumented second meaning indistinguishable from the first.

The second rule is a naming problem rather than a vocabulary problem. fair_home, fair_away, fair_draw are numeric(6,3), and a probability check rejects 100% of the 51,699 rows where all three are populated — because they hold decimal prices. fair_home runs from 1.010 to 600.000 with a median of 2.340; the reciprocal triple (1/h + 1/a + 1/d) has a median of exactly 1.0000 and stays within 5% of 1 in 51,664 of 51,699 rows. That sum is an enforceable invariant, and it is written nowhere. The column has no unit and no comment, so the only way to learn what it means is to invert it and watch the answer come out clean.

A constraint would have forced the name and the unit to agree six months ago; without one, the ambiguity survived long enough to become normal.

"Free" is a much smaller set than it sounds

The tempting conclusion is that four rules cost nothing, so add all four plus NOT NULL everywhere. The NOT NULL half does not survive measurement: of the 130 nullable columns, only 15 contain no NULL at all — 11.5%. The other 115 have at least one gap, and each is a product decision dressed as a migration: is fair_home IS NULL a missing price, an unparseable price, or a price that does not exist for this match? Nobody knows, because the column never had to answer. The executable inventory is therefore 15 NOT NULL promotions plus 4 zero-violator rules — 19 changes with no data work — against 8 rules that need a decision first.

Rolling out a rule without stopping the writers

The reason teams avoid ALTER TABLE ... ADD CONSTRAINT on a hot table is the validation scan: it reads every row while holding an exclusive DDL window. The two-step form avoids it:

-- 1. register the rule; new rows are checked, existing rows are untouched ALTER TABLE ai_predictions ADD CONSTRAINT ck_settled_requires_hit CHECK (NOT settled OR hit IS NOT NULL) NOT VALID; -- 2. what still blocks validation: 74 rows SELECT count(*) FROM ai_predictions WHERE settled AND hit IS NULL; -- 3. after the 74 rows are quarantined or repaired ALTER TABLE ai_predictions VALIDATE CONSTRAINT ck_settled_requires_hit; 

Step 1 is where most pipelines stop, which is exactly why ck_ah_none_no_hit still sits at convalidated = false. The flag is not a bug in PostgreSQL; it is an accurate record that the work was left half done.

Step 3 needs a gate, or the same thing happens again silently. This guard fails the build instead of logging a warning:

import psycopg2, sys RULES = { "ck_settled_requires_hit": "settled AND hit IS NULL", "ck_unsettled_has_no_hit": "NOT settled AND hit IS NOT NULL", "ck_confidence_range": "confidence NOT BETWEEN 1 AND 10", } cn = psycopg2.connect("postgresql://.../soccerdream") cn.set_session(readonly=True, autocommit=True) cu = cn.cursor() bad = 0 for name, predicate in RULES.items(): cu.execute(f"SELECT count(*) FROM ai_predictions WHERE {predicate}") n = cu.fetchone()[0] print(f"{name:28s} {n:>7d}") bad += n sys.exit(1 if bad else 0) 

Run before VALIDATE, and again nightly afterwards. The nightly run is the part that matters: it converts "the constraint exists" into "the constraint still holds", which are different claims and only one of them decays.

What this schema actually promises

Precisely this: primary keys are unique, 4,714 of 31,173 columns are not null, 107 relationships resolve, and 29 predicates hold — one of them explicitly unverified. Everything else is a convention maintained by whoever last edited the writer.

That is how almost every analytical system is built: constraints are treated as deploy risk, deferred until there is time, and there is never time. The bill arrives in a measurable form — a label column with six values where three were expected, a probability column holding prices, 4,854 rows pointing at models that no longer exist, 74 settled predictions with no outcome. None of these are crashes. All of them are ambiguity a single CHECK would have refused at write time.

The audit is cheap and the ledger above is one query. Twenty-nine is the number to move, and nineteen of the moves are free.

Analytics and research content. Not betting advice. 18+

本内容仅供数据分析与研究参考,不构成任何决策建议。