An audit query told me my fixture table had 1,006 duplicate matches. The obvious fix — GROUP BY ... HAVING count(*) > 1 plus a delete — would have removed 1,613 rows from a 96,384-row table.
Then I checked one group by hand. Six rows, same kickoff minute, six different scorelines: 3-0, 3-1, 4-1, 0-6, 3-1, 1-2. Not duplicates. Six different matches sharing a key that collapsed to nothing.
This is the audit of the audit. Every number comes from a production PostgreSQL database holding 96,384 fixtures and 49,616 stored predictions.
The setup
nami_matches is the fixture master (96,384 rows, 62 columns, unique nami_id). ai_predictions holds one row per model per attempt (49,616 rows, 130 columns) with a boolean hit for graded outcomes. The question is simple: is one fixture exactly one row?
-- The dedupe detector. Do not run the DELETE it implies.
SELECT home_team_id, away_team_id, match_time, count(*) AS n
FROM nami_matches
GROUP BY home_team_id, away_team_id, match_time
HAVING count(*) > 1
ORDER BY n DESC;
1,006 groups, 2,619 rows. Summing n - 1 gives 1,613 redundant rows.
Pattern 1: GROUP BY is not a unique key when the key can be NULL
GROUP BY treats all NULLs as one group. Correct SQL, catastrophic semantics: a NULL team id is not the claim "these rows share a team", it is the absence of a claim. PostgreSQL turned 4,392 keyless rows into a handful of gigantic buckets.
Measured: of the 1,006 groups, 725 involve a NULL team id and 281 have both ids present. Of the 2,619 rows in those groups, 2,593 carry a final score — 99.0%. A duplicate import does not produce 99% final scorelines on both copies. A real schedule does.
SELECT
count(*) AS groups,
count(*) FILTER (WHERE bool_or(home_team_id IS NULL OR away_team_id IS NULL)) AS keyless,
count(*) FILTER (WHERE distinct_scores > 1) AS contradictory,
sum(n) AS rows_in_groups
FROM (
SELECT count(*) AS n,
count(DISTINCT (home_score_regular, away_score_regular)) AS distinct_scores
FROM nami_matches
GROUP BY home_team_id, away_team_id, match_time
HAVING count(*) > 1
) g;
894 of 1,006 groups contain at least two different scorelines — 1,493 rows inside groups that provably are not duplicates. 104 predictions hang off rows in these groups, 43 of them graded hits. A delete on the strength of HAVING count(*) > 1 destroys the fixtures and the evidence that they were distinct.
The fix is not a better dedupe. It is refusing to dedupe on a nullable key:
CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ux_fixture_identity
ON nami_matches (home_team_id, away_team_id, match_time)
WHERE home_team_id IS NOT NULL AND away_team_id IS NOT NULL;
Here it fails to build, on exactly those 281 groups. That failure is the useful outcome: the constraint names 281 rows for review instead of a script deleting 1,613 on a guess. Of those 281, 217 disagree on the scoreline and 64 agree — splitting "broken key" from "candidate duplicate" without deleting anything.
Pattern 2: a sentinel zero is a worse NULL
The system also says "unknown" with 0. Not NULL, not a real id, just a placeholder — and because 0 = 0, it joins and groups like a legitimate value.
SELECT
count(*) FILTER (WHERE home_team_id = 0 OR away_team_id = 0) AS zero_team_rows,
count(*) FILTER (WHERE home_team_id = 0 AND away_team_id = 0) AS zero_pairs,
count(*) FILTER (WHERE home_team_id = away_team_id) AS self_matches,
count(*) FILTER (WHERE season_id = 0) AS zero_season_rows
FROM nami_matches;
2,632 rows carry a zero team id, 472 on both sides, and 22,417 rows (23.3%) carry season_id = 0. That last number is the quiet killer: any fixture-to-season join either drops a quarter of the table, or aggregates a quarter of it into one phantom season. Among the 281 duplicate groups with both ids present, 217 disagree on the scoreline — 0-0 vs 0-0 groups are not one match seen twice, they are a batch of unmapped fixtures ingested on the same clock. A sentinel is a NULL that lies about being a value.
Pattern 3: string concatenation as a composite key
count(DISTINCT a, b) does not exist in PostgreSQL — you get function count(integer, integer) does not exist — so the reflex is to concatenate.
SELECT
count(DISTINCT (home_team_id, away_team_id)) AS tuple_key,
count(DISTINCT home_team_id || '-' || away_team_id) AS concat_key
FROM nami_matches;
89,096 versus 88,943. The concatenated form loses 153 identities, silently. Two mechanisms: NULL || '-' || NULL is NULL, so all 4,392 keyless rows become one value that count(DISTINCT ...) then drops from the denominator entirely; and delimiters collide — (1, 12) and (11, 2) both become '1-12'. Real ids here reach five digits, so the collision is latent, not impossible. The tuple form is a row constructor: no delimiter, no NULL merging. Use it, or hash a canonical jsonb array. Never a string join.
Pattern 4: LEFT JOIN plus WHERE is an INNER JOIN
SELECT count(*) FROM matches m
LEFT JOIN nami_matches n ON n.nami_id = m.nami_id; -- 87,059
SELECT count(*) FROM matches m
LEFT JOIN nami_matches n ON n.nami_id = m.nami_id
WHERE n.status_id = 8; -- 83,619
3,440 rows — 3.95% — vanish. WHERE on the right table rejects every row the outer join preserved with NULLs, because NULL = 8 is unknown, and unknown never passes a filter. Moving the predicate into ON restores all 87,059. Its twin is the anti-join: NOT IN against a subquery containing one NULL returns nothing, forever.
SELECT count(*) FROM nami_matches
WHERE competition_id NOT IN (
SELECT competition_id FROM nami_matches WHERE status_id = 8
); -- 30
SELECT count(*) FROM nami_matches nm
WHERE NOT EXISTS (
SELECT 1 FROM nami_matches x
WHERE x.status_id = 8 AND x.competition_id = nm.competition_id
); -- 47
The 17-row gap is exactly the count of fixtures with a NULL competition_id. NOT IN excluded them; NOT EXISTS kept them. Two defensible answers to a question nobody wrote down precisely — which is the real problem. Pick one, comment it in the query, make it a test.
Pattern 5: the denominator you did not choose
SELECT
count(*) AS rows_total,
count(hit) AS rows_graded,
sum(hit::int) AS hits,
round(100.0 * sum(hit::int) / count(hit), 4) AS pct_over_graded,
round(100.0 * sum(hit::int) / count(*), 4) AS pct_over_all,
sum(hit::int) * 100 / count(hit) AS integer_division
FROM ai_predictions;
49,616 rows total, 49,077 graded, 27,894 hits. Same numerator, two defensible denominators: 56.8372% and 56.2198%. A 0.62-point spread from choosing count(*). Of 49,151 rows flagged settled, 75 have hit IS NULL and 249 have a NULL secondary grade — "flagged settled but ungraded" and "model was wrong" are different states, and averaging over both mixes them.
Integer division truncates the same number to 56, losing 0.84 points. I tested it across all 4,000 model ids with at least one graded call: maximum deviation 0.98 points, and zero threshold flips at all eight gates I checked (50, 55, 56, 57, 58, 60, 65, 70). Real, bounded, and here — not guilty. Reporting that honestly matters more than the finding, because the next reader will assume it was the culprit.
The third drift is fan-out. Joining a one-to-many table multiplies rows invisibly:
SELECT count(*) AS join_rows, count(DISTINCT p.match_id) AS distinct_fixtures
FROM ai_predictions p
JOIN nami_matches nm ON nm.id = p.match_id;
49,553 rows, 17,400 fixtures — 2.85 predictions per fixture. Write count(*) as "matches audited" and you claim a dataset 2.85× the one you have, with every rate weighted by how many models happened to look at each fixture.
The guard: six assertions instead of six comments
CHECKS = [
("fixture rows", "SELECT count(*) FROM nami_matches", lambda v: v == 96384),
("identity tuples",
"SELECT count(DISTINCT (home_team_id, away_team_id, match_time)) FROM nami_matches",
lambda v: v == 94771),
("graded rows never exceed rows",
"SELECT count(hit) - count(*) FROM ai_predictions", lambda v: v <= 0),
("key either complete or absent",
"SELECT count(*) FROM nami_matches "
"WHERE (home_team_id IS NULL) <> (away_team_id IS NULL)", lambda v: v == 0),
("no graded row without a fixture",
"SELECT count(*) FROM ai_predictions p LEFT JOIN nami_matches nm ON nm.id = p.match_id "
"WHERE p.hit IS NOT NULL AND nm.id IS NULL", lambda v: v == 0),
("join fan-out in range",
"SELECT count(*) FROM ai_predictions p JOIN nami_matches nm ON nm.id = p.match_id",
lambda v: 40000 < v < 60000),
]
for label, sql, ok in CHECKS:
value = scalar(sql)
if not ok(value):
raise SystemExit(f"DENOMINATOR DRIFT: {label} = {value}")
Run it before the audit, not after. Two checks would have blocked the delete outright: the identity-tuple count (94,771, not 96,384) says the table is not keyed uniquely, and the asymmetric-null check says the key is partially absent rather than duplicated.
What the audit concluded
| Claim | Naive query | After checking |
|---|---|---|
| Duplicate groups | 1,006 | 1,006, of which 725 keyless |
| Rows a dedupe deletes | 1,613 | 0 justified |
| Groups with ≥2 scorelines | — | 894 (1,493 rows) |
| Predictions at risk | — | 104 (43 graded hits) |
| Real duplicates | unknown | 0 proven; 281 colliding keys, 217 self-contradictory |
| Hit rate | 56% | 56.84% / 56.22% |
The fixture table was never broken. The query was. It treated absence of a key as a shared value, and inferred duplication from a group count instead of a contradiction in the payload. A group containing 3-0 and 0-6 at the same kickoff is not a duplicate group. It is a group whose key failed.
Two rules survived. Dedupe on contradiction, never on count: group by the candidate key, then ask whether the non-key columns disagree — if they do, the key is wrong. And pin every denominator in an assertion before the first GROUP BY. The number a rate is divided by is a design decision, and design decisions belong in code that fails loudly, not in a query that succeeds quietly.
The 1,613 rows are still there. They were never duplicates. They were unkeyed, and I had written a query that could not tell the difference.
Analytics and research content. Not betting advice. 18+
本内容仅供数据分析与操作参考,不构成任何决策建议。