Re: Rows violating Foreign key constraint exists

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Nandakumar M <m(dot)nanda92(at)gmail(dot)com>, pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Rows violating Foreign key constraint exists
Date: 2019-11-28 16:48:05
Message-ID: a39cdf69-3336-0699-f54a-7feb1fe68a9d@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 11/28/19 5:25 AM, Nandakumar M wrote:
> Hi,
>
> I am using PG version 10.5.
>
> Saw a table where we have foreign key defined but few thousand rows
> violate the foreign key constraint.

Have you verified that the FK is not in the parent table and is just not
some index error/corruption?

> It might be useful to have an option to check integrity of any FK (not
> just ones created with NOT VALID clause). Please let me know if there
> is already any way to do this.

Assuming no corruption, how about?:

select distinct on(fk_field) fk_field from child_table where
child_table.fk_field not in (select parent_field from parent_table);

>
> Also, is there any way to make sure the FK checking trigger can never
> be disabled (so that such a case will never arise)?

Not sure that can happen as it is baked into existing code. For instance:

https://www.postgresql.org/docs/11/app-pgdump.html

"
--disable-triggers

This option is relevant only when creating a data-only dump. It
instructs pg_dump to include commands to temporarily disable triggers on
the target tables while the data is reloaded. Use this if you have
referential integrity checks or other triggers on the tables that you do
not want to invoke during data reload.

...

"
>
> How do I proceed from here - Do I just delete the inconsistent rows or
> is there something more I have to do?
>
> Thanks for your help.
>
> Regards,
> Nanda
>
>
>

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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message George Neuner 2019-11-28 21:07:06 Re: status of CURSORs after DISCONNECT
Previous Message George Neuner 2019-11-28 15:04:53 Re: status of CURSORs after DISCONNECT