Re: ADD FOREIGN KEY fails, but the records exist

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Ron <ronljohnsonjr(at)gmail(dot)com>, "pgsql-generallists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: ADD FOREIGN KEY fails, but the records exist
Date: 2021-02-15 16:17:55
Message-ID: 37d7ad6b-3da6-0778-47fe-e6256babb4ad@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 2/15/21 8:12 AM, Ron wrote:
> Postgresql 12.5
>
> It's a self-referential FK on a single (but partitioned) table.  The
> ALTER TABLE command fails, but I queried it, and the record that it
> fails on exists.  I modified the original INITIALLY IMMEDIATE clause to
> INITIALLY DEFERRED but that did not help.
>
> What am I doing wrong?
>
> (We're migrating from Oracle to PostgreSQL, and this is working in Oracle.)
>
> sides=> ALTER TABLE employer_response
>     ADD CONSTRAINT amended_response_fk FOREIGN KEY
> (amended_response_id, part_date)
>         REFERENCES employer_response(employer_response_id, part_date)
>     ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED ;
> ERROR:  insert or update on table "employer_response_p2021_01" violates
> foreign key constraint "amended_response_fk"
> DETAIL:  Key (amended_response_id, part_date)=(103309154, 2021-01-06
> 00:00:00) is not present in table "employer_response".
> sides=>
> sides=> select employer_response_id, part_date
> sides-> from strans.employer_response
> sides-> where amended_response_id = 103309154;
> employer_response_id |      part_date
> ----------------------+---------------------
>             103309156 | 2021-01-06 00:00:00
> (1 row)

The error:

DETAIL: Key (amended_response_id, part_date)=(103309154, 2021-01-06
00:00:00) is not present in table "employer_response"

is pointing at 103309154 for amended_response_id = employer_response_id.
You are showing an employer_response_id of 103309156

>
>
> sides=> select employer_response_id, part_date
> from strans.employer_response_p2021_01
> where amended_response_id = 103309154;
> employer_response_id |      part_date
> ----------------------+---------------------
>             103309156 | 2021-01-06 00:00:00
> (1 row)
>
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Marc Millas 2021-02-15 16:18:48 prepare in a do loop
Previous Message Laurenz Albe 2021-02-15 16:15:41 Re: MultiXactMemberControlLock contention on a replica