PostgreSQL: One Match, Three IDs, No Duplicate Fixtures
When sports feeds assign different IDs to one fixture, canonical match records, provider mappings, and guarded updates prevent duplicate data.
By Boštjan KorošakGuest author · Edited by Dinesh Chandra- 1.Give each real match one internal ID; treat provider IDs as aliases, not universal identifiers.
- 2.Resolve teams and competitions before proposing a cross-provider match.
- 3.Use database constraints to protect provider mappings, but review ambiguous fixture candidates before joining them.
- 4.Keep changes attached to the same match ID, and reject stale updates only when the source provides a trustworthy revision.
- 5.Merge confirmed duplicates transactionally, including their dependent records.
Table of contents
- The problem
- The common wrong approach
- The approach that works
- 1. Resolve team and competition identity before matching
- 2. Make match IDs internal, and provider IDs unique within each feed
- 3. Seed the fictional teams, competitions and aliases
- 4. Create the first canonical match and its first provider mapping together
- 5. Find candidates using normalized team and competition IDs
- 6. Link the second and third IDs after review
- 7. Reschedule a postponed match without changing identity
- 8. Accept a result, then a later correction
- Edge cases and changes
- Late data and reruns
- A postponed fixture disappears from the candidate window
- Two records turn out to be one match
- Schema changes and partial failures
- Trade-offs
- Pitfalls
- FAQ
- What if two providers disagree on kickoff time?
- How do you merge two records that turn out to be the same match?
- Should a database unique constraint prevent all duplicates?
- What if the provider does not expose a revision number?
- Can two workers create the same match at once?
- What this means for your pipelines
A football fixture looks simple in an application: two teams, a kickoff time and a result. Pull the same game from several data feeds, however, and you may get three event IDs, slightly different team names and a kickoff that changes after a postponement. Each feed is internally consistent. Your database is where the trouble begins.
The obvious shortcut is to store whichever external ID arrived first. That works until a second feed supplies the same match with a different ID. Then schedules show duplicate fixtures, results are counted twice, and downstream reports disagree about which record is correct.
This article builds a small PostgreSQL model that separates what the match is from what each provider calls it. The SQL uses fictional teams and IDs so the decisions are inspectable. It covers candidate matching, safe updates and a deliberate duplicate that we then merge. The examples target PostgreSQL 12 or later and should be run in the order shown in a disposable database.
The complete script runs top to bottom in a disposable PostgreSQL database: download the SQL script. It ends with a check that raises an error if any step did not produce the expected state.
The problem
Suppose three providers report the same match:
| Feed | External event ID | Home | Away | Kickoff (UTC) |
|---|---|---|---|---|
| Alpha | A-9314 |
Harbor FC | Valley United | Nov 15, 15:00 |
| Beta | B-2208 |
Harbor FC | Valley Utd | Nov 15, 15:05 |
| Gamma | C-770 |
Harbor Football Club | Valley United | Nov 15, 15:00 |
These are synthetic records, not an actual match or measured provider behavior. Five minutes of disagreement might be a correction, a rounding convention or stale source data. It is not evidence of three matches.
Now imagine that the fixture is postponed. Alpha retains A-9314 but changes the kickoff date. A date-based deduplication job may create another match row; the old one remains scheduled, the new one is postponed, and any prediction or notification tied to the old row loses its connection to the game.
A useful production symptom is not just “duplicate rows.” It is two internal match IDs sharing plausible teams and competition, while external references and dependent records are split between them. A unique index on the provider’s ID will not detect that problem. Each provider ID is different, so every insert looks valid.
The desired invariant is narrower and more useful: one real fixture has one canonical internal match ID, with any number of verified provider references pointing to it. The database can enforce the references. Deciding that two ambiguous fixtures represent the same real-world event still needs a matching policy.
The common wrong approach
The first attempt usually makes the provider ID the primary key. That turns a feed-specific label into an identity for your entire system. Adding Beta later either creates a duplicate or forces unrelated code to understand Alpha’s IDs.
A second attempt matches on home_team, away_team and kickoff date. It seems more portable, but names are display data, not stable keys. “Valley Utd” and “Valley United” differ as strings; translated names and abbreviations add more variations. Kickoff times move, and the same two teams can meet twice in a competition.
The dangerous version is an automatic merge whenever the names look close and the kickoff falls within a tolerance. That can collapse a replay, a reserve-team match, or two legs of a tie into one row. A false merge is often harder to repair than a duplicate because it mixes statistics, subscriber alerts and audit history.
I prefer a two-stage decision: identify candidates using normalized identities, then attach an external ID only when the match is sufficiently certain. Leave uncertain candidates in a review queue instead of pretending that a fuzzy score is a database constraint.
The approach that works
1. Resolve team and competition identity before matching
The sample uses fixed team IDs purely to keep it reproducible. In a real system, these IDs would normally be generated internally, and mapping a provider team to a canonical team would require its own validation.
CREATE TABLE teams (
team_id bigint PRIMARY KEY,
display_name text NOT NULL
);
CREATE TABLE provider_teams (
provider text NOT NULL,
external_team_id text NOT NULL,
team_id bigint NOT NULL REFERENCES teams(team_id),
PRIMARY KEY (provider, external_team_id)
);
CREATE TABLE provider_competitions (
provider text NOT NULL,
external_competition_id text NOT NULL,
competition_key text NOT NULL,
PRIMARY KEY (provider, external_competition_id)
);
These tables do not assume that providers share team names or competition codes. Each reviewed external team reference points to an internal team; each external competition reference points to a canonical competition key. The keys are illustrative and must be scoped consistently in a real system.
2. Make match IDs internal, and provider IDs unique within each feed
CREATE TABLE matches (
match_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
competition_key text NOT NULL,
season_key text NOT NULL,
home_team_id bigint NOT NULL REFERENCES teams(team_id),
away_team_id bigint NOT NULL REFERENCES teams(team_id),
kickoff_at timestamptz NOT NULL,
status text NOT NULL CHECK
(status IN ('scheduled', 'live', 'finished', 'postponed', 'cancelled')),
home_goals integer,
away_goals integer,
updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHECK (home_team_id <> away_team_id),
CHECK (
(home_goals IS NULL) = (away_goals IS NULL)
AND (home_goals IS NULL OR (home_goals >= 0 AND away_goals >= 0))
)
);
CREATE TABLE provider_matches (
provider text NOT NULL,
external_match_id text NOT NULL,
match_id bigint NOT NULL REFERENCES matches(match_id),
last_revision bigint NOT NULL DEFAULT 0 CHECK (last_revision >= 0),
PRIMARY KEY (provider, external_match_id)
);
CREATE INDEX matches_candidates_idx
ON matches (competition_key, season_key,
home_team_id, away_team_id, kickoff_at);
CREATE INDEX provider_matches_match_idx
ON provider_matches (match_id);
Two constraints do different jobs. matches.match_id identifies the canonical fixture. The (provider, external_match_id) primary key means one provider reference cannot point to two internal fixtures simultaneously. Multiple providers can still point to the same match_id.
There is deliberately no unique constraint on teams plus kickoff. Those fields help find candidates, but they are not a universal match identity. The sample also assumes that external event IDs are unique within each provider; if a feed reuses IDs by season or competition, include that scope in the mapping key.
The score constraint accepts either two unknown goals or two nonnegative integers; it rejects a half-known result. This matters because PostgreSQL considers a CHECK satisfied when its expression evaluates to TRUE or NULL, not just TRUE. In a larger schema, canonical competition keys can also reference a dedicated competitions table.
last_revision is used later for a feed that supplies a documented, increasing match revision. Not every provider offers one. If yours does not, do not manufacture a revision number from response-arrival order.
3. Seed the fictional teams, competitions and aliases
INSERT INTO teams (team_id, display_name) VALUES
(101, 'Harbor FC'),
(102, 'Valley United');
INSERT INTO provider_teams (provider, external_team_id, team_id) VALUES
('alpha', 'a-harbor', 101),
('alpha', 'a-valley', 102),
('beta', 'b-011', 101),
('beta', 'b-022', 102),
('gamma', 'g-home', 101),
('gamma', 'g-away', 102);
INSERT INTO provider_competitions
(provider, external_competition_id, competition_key)
VALUES
('alpha', 'a-nl', 'northern-league'),
('beta', 'b-nl', 'northern-league'),
('gamma', 'g-nl', 'northern-league');
These team and competition aliases are already reviewed. Unknown references should be staged for reconciliation rather than matched by guesswork; the fixture query below only considers known mappings.
4. Create the first canonical match and its first provider mapping together
WITH created AS (
INSERT INTO matches (
competition_key, season_key, home_team_id, away_team_id,
kickoff_at, status
) VALUES (
'northern-league', '2026-27', 101, 102,
TIMESTAMPTZ '2026-11-15 15:00:00+00', 'scheduled'
)
RETURNING match_id
)
INSERT INTO provider_matches (
provider, external_match_id, match_id, last_revision
)
SELECT 'alpha', 'A-9314', match_id, 1
FROM created
RETURNING match_id;
The two inserts form one SQL statement. If the external-ID uniqueness check fails, the new match row is rolled back with it rather than becoming an orphan. For repeated imports, first look up the existing provider mapping; do not blindly create another canonical row.
5. Find candidates using normalized team and competition IDs
When Beta reports the fixture, resolve its team and competition identifiers and search a bounded window in the resolved competition and incoming season. The 90-minute window below is an illustrative candidate filter, not a reliable universal threshold.
WITH incoming AS (
SELECT
'beta'::text AS provider,
'b-011'::text AS home_external_id,
'b-022'::text AS away_external_id,
'b-nl'::text AS competition_external_id,
'2026-27'::text AS season_key,
TIMESTAMPTZ '2026-11-15 15:05:00+00' AS kickoff_at
),
resolved AS (
SELECT h.team_id AS home_id,
a.team_id AS away_id,
c.competition_key,
i.season_key,
i.kickoff_at
FROM incoming i
JOIN provider_teams h
ON h.provider = i.provider
AND h.external_team_id = i.home_external_id
JOIN provider_teams a
ON a.provider = i.provider
AND a.external_team_id = i.away_external_id
JOIN provider_competitions c
ON c.provider = i.provider
AND c.external_competition_id = i.competition_external_id
)
SELECT m.match_id, m.kickoff_at,
ABS(EXTRACT(EPOCH FROM (m.kickoff_at - r.kickoff_at)))
AS seconds_apart
FROM matches m
CROSS JOIN resolved r
WHERE m.competition_key = r.competition_key
AND m.season_key = r.season_key
AND m.home_team_id = r.home_id
AND m.away_team_id = r.away_id
AND m.kickoff_at BETWEEN r.kickoff_at - INTERVAL '90 minutes'
AND r.kickoff_at + INTERVAL '90 minutes'
ORDER BY seconds_apart, m.match_id;
The query should return the one fixture we seeded, five minutes from Beta’s proposed kickoff. But one candidate is not automatic proof: a provider may list a replay, a postponed match may move by several days, and a feed may switch the home/away designation. A production matcher should check those cases and record why an ID was linked.
6. Link the second and third IDs after review
Suppose the team, competition and fixture evidence confirms that Beta’s B-2208 and Gamma’s C-770 are aliases for Alpha’s match. Attach them to the existing internal ID; do not insert new matches.
INSERT INTO provider_matches (
provider, external_match_id, match_id, last_revision
)
SELECT v.provider, v.external_match_id, a.match_id, 1
FROM provider_matches a
CROSS JOIN (VALUES
('beta', 'B-2208'),
('gamma', 'C-770')
) AS v(provider, external_match_id)
WHERE a.provider = 'alpha'
AND a.external_match_id = 'A-9314';
That statement deliberately fails on a duplicate external mapping rather than silently redirecting an existing mapping. In a running ingestion service, catch the unique-key error, read the current mapping and decide whether this is an idempotent replay or a real identity conflict.
SELECT provider, external_match_id, match_id
FROM provider_matches
ORDER BY provider;
The result has three distinct provider IDs and just one match_id. From this point, reports join on the internal ID. Provider references remain available for API calls and debugging.
7. Reschedule a postponed match without changing identity
The match was postponed but now has a confirmed new kickoff on November 19. Alpha retains its event ID and publishes revision 2. Once the new date is confirmed, set the current status back to scheduled; reserve postponed for a fixture still awaiting rescheduling. Accept the new state only if that provider’s stored revision is older.
WITH accepted AS (
UPDATE provider_matches
SET last_revision = 2
WHERE provider = 'alpha'
AND external_match_id = 'A-9314'
AND last_revision < 2
RETURNING match_id
)
UPDATE matches m
SET kickoff_at = TIMESTAMPTZ '2026-11-19 19:00:00+00',
status = 'scheduled',
updated_at = CURRENT_TIMESTAMP
FROM accepted
WHERE m.match_id = accepted.match_id
RETURNING m.match_id, m.status, m.kickoff_at;
Run that statement again and it updates nothing. The mapping row’s revision guard prevents a repeated revision 2 from rewriting the fixture. The canonical ID, and therefore its foreign-key relationships, remain unchanged.
The map update and match update are part of one statement and one transaction. The revision guard serializes overlapping updates for this provider’s mapping row. This design also assumes Alpha is the authority for the canonical fields being updated; provider revisions from separate feeds are not directly comparable.
8. Accept a result, then a later correction
A final score may itself be corrected. Revision 3 reports a 2–1 finish, and revision 4 later changes it to 1–1. The correction should be accepted even though the home team’s score decreases.
WITH accepted AS (
UPDATE provider_matches
SET last_revision = 3
WHERE provider = 'alpha'
AND external_match_id = 'A-9314'
AND last_revision < 3
RETURNING match_id
)
UPDATE matches m
SET status = 'finished',
home_goals = 2,
away_goals = 1,
updated_at = CURRENT_TIMESTAMP
FROM accepted
WHERE m.match_id = accepted.match_id
RETURNING m.match_id, m.home_goals, m.away_goals;
WITH accepted AS (
UPDATE provider_matches
SET last_revision = 4
WHERE provider = 'alpha'
AND external_match_id = 'A-9314'
AND last_revision < 4
RETURNING match_id
)
UPDATE matches m
SET home_goals = 1,
away_goals = 1,
updated_at = CURRENT_TIMESTAMP
FROM accepted
WHERE m.match_id = accepted.match_id
RETURNING m.match_id, m.home_goals, m.away_goals;
The latest authoritative revision wins, not the highest score or the last HTTP response to finish. Other providers may disagree; the pipeline needs an explicit policy for which source owns each field instead of applying unrelated revisions to the same canonical record.
Edge cases and changes
Late data and reruns
The simplest safe replay is a provider-ID lookup followed by a revision check. If the incoming external ID is already mapped, update its canonical match rather than searching for a new one. That matters after restarts, queue redelivery and batch backfills. For feeds without stable revisions, stage the received observation and reconcile it against a documented source timestamp or a fresh authoritative snapshot; arrival time alone is not enough.
A postponed fixture disappears from the candidate window
The initial candidate query searches only 90 minutes around a kickoff. It will miss a game rescheduled by four days. That’s acceptable for a first-pass search, not as a final matching decision. Search existing provider mappings first, widen the review process when schedules change, and keep match identity independent of kickoff time.
Two records turn out to be one match
Sometimes the duplicate has already been inserted. To make this case concrete, the next statement intentionally creates a second internal match and assigns it a Delta provider ID. Run it only in the disposable demonstration database.
WITH duplicate AS (
INSERT INTO matches (
competition_key, season_key, home_team_id, away_team_id,
kickoff_at, status, home_goals, away_goals
)
SELECT m.competition_key, m.season_key,
m.home_team_id, m.away_team_id,
m.kickoff_at, m.status, m.home_goals, m.away_goals
FROM matches m
JOIN provider_matches p ON p.match_id = m.match_id
WHERE p.provider = 'alpha' AND p.external_match_id = 'A-9314'
RETURNING match_id
)
INSERT INTO provider_matches (
provider, external_match_id, match_id, last_revision
)
SELECT 'delta', 'D-991', match_id, 1
FROM duplicate;
After confirming that this Delta match really is the same fixture, merge its mapping into the keeper and remove its empty canonical row. This simplified demonstration has no additional dependent tables; a real system must move predictions, statistics and other references before the delete.
BEGIN;
CREATE TEMP TABLE merge_choice ON COMMIT DROP AS
SELECT keeper.match_id AS keep_id,
duplicate.match_id AS drop_id
FROM provider_matches keeper
CROSS JOIN provider_matches duplicate
WHERE keeper.provider = 'alpha'
AND keeper.external_match_id = 'A-9314'
AND duplicate.provider = 'delta'
AND duplicate.external_match_id = 'D-991'
AND keeper.match_id <> duplicate.match_id;
SELECT m.match_id
FROM matches m
JOIN merge_choice c ON m.match_id IN (c.keep_id, c.drop_id)
ORDER BY m.match_id
FOR UPDATE OF m;
UPDATE provider_matches p
SET match_id = c.keep_id
FROM merge_choice c
WHERE p.match_id = c.drop_id;
DELETE FROM matches m
USING merge_choice c
WHERE m.match_id = c.drop_id;
COMMIT;
In production, confirm that the merge plan contains exactly one approved pair and acquire row locks in a consistent match_id order; two concurrent merges that lock the same rows in opposite orders can deadlock. Migrate all dependent foreign keys, resolve conflicting values according to field-specific rules and record an audit trail. An arbitrary DELETE is not a deduplication strategy. Consider a canonical-ID alias table when historical URLs and external references must continue resolving after a merge.
Schema changes and partial failures
Providers change field names and event shapes. Keep raw observations with their source, capture time and schema version so a broken mapping can be replayed. Validate status values and nullable scores before the canonical update. PostgreSQL transactions prevent half of a revision update from committing; they cannot recover an event you never received, so ingestion still needs retry and reconciliation jobs.
Trade-offs
An internal identity layer adds tables, lookups, reconciliation work and a human path for ambiguous candidates. You are exchanging a little ingestion complexity for stable references downstream. That’s usually a good trade in multi-provider analytics, but it may be unnecessary for a short-lived application that uses one provider and never joins to another dataset.
Matching conservatively means some duplicates survive temporarily in a review queue. Matching aggressively reduces that queue at the price of false merges. Choose the threshold according to the cost of a bad join, not the neatness of a dashboard. A false split is often repairable by merging two internal IDs; a false merge can contaminate a season’s aggregates.
The example also stores only the latest canonical state. If your product needs to explain when a result changed, maintain an append-only source observation or change log alongside it. That adds storage and query work but makes corrections auditable. Finally, a single-authority field policy simplifies conflicting feeds; field-level consensus offers more coverage but is significantly harder to reason about.
Pitfalls
- Treating provider IDs as universal: Keep them in a mapping table and expose internal IDs to your own services.
- Uniquely indexing teams plus date: Use those fields for candidate search, not as proof that two records are identical.
- Blindly trusting the latest response: Compare documented source revisions, or reconcile when ordering is uncertain.
- Overwriting mappings during an upsert: Reject conflicting mappings for investigation instead of silently reassigning identities.
- Deleting duplicates before moving references: Merge transactionally, audit the decision and update every dependent table.
FAQ
What if two providers disagree on kickoff time?
Use the already-mapped match ID when one exists. For a new fixture, treat both times as evidence, not as an identity key; compare normalized teams, competition, round and source context. Decide which source owns the published kickoff, and retain the conflicting observation for review if the difference is unexplained.
How do you merge two records that turn out to be the same match?
First verify the identity manually or by a high-confidence, documented rule. Then choose the keeper ID, lock both match rows, redirect provider mappings and dependent foreign keys in one transaction, and retain an audit record. The SQL example demonstrates the core operation but cannot know your other tables or their conflict rules.
Should a database unique constraint prevent all duplicates?
Use it to prevent known invalid states, such as the same provider ID mapping to two matches. No reliable universal uniqueness key exists for two teams plus a kickoff, particularly with postponements and replays. Candidate matching and reconciliation are still necessary.
What if the provider does not expose a revision number?
Do not substitute a local receive timestamp and call it a source revision. If the provider documents ordered event timestamps, use that guarantee carefully; otherwise store the observation, re-fetch an authoritative snapshot when uncertain and avoid overwriting known-good state blindly. The revision-guarded update shown here applies only to feeds with a meaningful increasing revision.
Can two workers create the same match at once?
Yes, if both see no existing mapping and independently decide to insert. Make the first match-plus-mapping operation atomic, handle unique-key conflicts, and serialize tentative identity creation when necessary. A manual review queue or a narrowly scoped advisory lock can reduce races for uncertain cross-provider candidates, but neither replaces a sound identity policy.
What this means for your pipelines
Before adding a second provider, decide which IDs belong to your system and which belong to the feeds. Build the mapping table first, put unique constraints around external references, and make fixture matching return candidates rather than irrevocable guesses. Then test the unglamorous scenarios: postponements, correction backfills, replayed updates and an accidental duplicate that must be merged.
The important outcome is not a clever matching score. It is a stable internal match ID that survives the ordinary messiness of live sports data.
All match names, feed IDs and dates in this article are illustrative. The SQL demonstrates design choices rather than a specific production incident or a claim about any provider’s live schema.
