Foreign key constraint violation when foreign key is present - sql

I am new to PostgreSQL and databases in general and am trying to figure out why I am getting a foreign key violation even when the foreign key is present.
The query I ran
insert into analytics_url_redirect
(source, news_item_id, access_date)
select 'n',id,CURRENT_TIMESTAMP from entry_entry_master
where id=43068778;
This fails with
ERROR: insert or update on table "analytics_url_redirect" violates foreign key constraint "news_item_id_refs_id_15ddd78c"
SQL state: 23503
Detail: Key (news_item_id)=(43068778) is not present in table "entry_entry_master".
The following select query also works fine and gives back 43068778:
select id from entry_entry_master where id=43068778;
The entire create table command - which is the output of django sqlall is
BEGIN;
CREATE TABLE "analytics_url_redirect" (
"id" serial NOT NULL PRIMARY KEY,
"newsletter_id" integer REFERENCES "nlc_newsletter" ("newslettercore_ptr_id") DEFERRABLE INITIALLY DEFERRED,
"alert_id" integer REFERENCES "alerts_emailtracker" ("id") DEFERRABLE INITIALLY DEFERRED,
"source" varchar(1) NOT NULL,
"brief_id" integer REFERENCES "brief_brief" ("id") DEFERRABLE INITIALLY DEFERRED,
"news_item_id" integer REFERENCES "entry_entry_master" ("id") DEFERRABLE INITIALLY DEFERRED,
"external_news_item_id" integer REFERENCES "nlc_newsletterblock" ("id") DEFERRABLE INITIALLY DEFERRED,
"recipient_id" integer REFERENCES "subscriber_subscriber" ("id") DEFERRABLE INITIALLY DEFERRED,
"external_recipient_id" integer REFERENCES "subscriber_pseudosubscriber" ("id") DEFERRABLE INITIALLY DEFERRED,
"access_date" timestamp with time zone NOT NULL
)
;
CREATE INDEX "analytics_url_redirect_newsletter_id" ON "analytics_url_redirect" ("newsletter_id");
CREATE INDEX "analytics_url_redirect_alert_id" ON "analytics_url_redirect" ("alert_id");
CREATE INDEX "analytics_url_redirect_brief_id" ON "analytics_url_redirect" ("brief_id");
CREATE INDEX "analytics_url_redirect_news_item_id" ON "analytics_url_redirect" ("news_item_id");
CREATE INDEX "analytics_url_redirect_external_news_item_id" ON "analytics_url_redirect" ("external_news_item_id");
CREATE INDEX "analytics_url_redirect_recipient_id" ON "analytics_url_redirect" ("recipient_id");
CREATE INDEX "analytics_url_redirect_external_recipient_id" ON "analytics_url_redirect" ("external_recipient_id");
CREATE INDEX "analytics_url_redirect_access_date" ON "analytics_url_redirect" ("access_date");
COMMIT;
So how is it possible to get a foreign key constraint violation when the foreign key is present?
Am I missing something obvious?

I figured this out myself. :(
One detail I missed is that entry_entry_master is partitioned using table inheritance. From the postgres documentation: postgres Inheritance
A serious limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
This also explains why the select query works.

Related

When creating a foreign key in firebird, the error violation of the FOREIGN KEY restriction "PK_ROLES1" in the "roles" table comes out?

I am trying to create a foreign key in the user_roles table.It has a user_id and a roles_id. I created a foreign key for user_id. And for roles_id it is not possible to create. I work at ibexpert.
An error comes out: violation of FOREIGN KEY constraint "PK_RULES 1" on table "rules".I will be glad of any help.
alter table "users_roles"
add constraint FK_USERS_ROLES_2
foreign key (ROLE_ID)
references "roles"(ID)
on delete CASCADE
on update CASCADE
using index FK_USERS_ROLES_2

I have a problem with this query in Postgres

I have a problem with this table in Postgres, it give me this error:
ERROR: cannot use subquery in check constraint
LINE 66: check(Artista in(Select ID_Artista
create table DirigeF(
Artista int references Artista(ID_Artista) on delete cascade,
Film int references Film(ID_Contenuto) on delete cascade,
check(Artista in(Select ID_Artista
from Artista
where tipologia='REGISTA'or'AR')),
constraint DirigeF_PK primary key(Artista, Film)
);
I want to check that Artista in table DirigeF has tipologia='REGISTA' from another table.
As the error suggests, you cannot do this with a check constraint. One option is a trigger. Another is a foreign key constraint -- but that needs to be carefully arranged.
First you need a column that indicates whether the type in Artista is "REGISTA" or "AR". That would be:
alter table artista add is_regista_ar bool generated always as
(tipologia in ('REGISTA', 'AR'));
Then create a unique constraint or index:
alter table artista add unq_artista_tipologia_id
unique (is_regista_ar, id_artista)
Note: This requires Postgres 12+. But something similar can be done in earlier versions.
Then, add a boolean column to your table that is always true:
create table DirigeF (
Artista int references Artista(ID_Artista) on delete cascade,
Film int references Film(ID_Contenuto) on delete cascade,
is_regista_ar bool generated always as true,
constraint fk_artista_tipo_artista foreign key (is_regista_ar, Artista) references Artista(is_regista_ar, ID_Artista),
constraint DirigeF_PK primary key (Artista, Film)
);

Defining foreign key for a composite primary key in SQL Server

I have two tables: Ticket and TicketRelation. I am trying to relate 2 Tickets using the TicketRelation table.
I want to add a cascade constraint to both foreign keys.
I am using SQL Server Management Studio to add the constraints but I get this error:
Introducing FOREIGN KEY constraint 'FK_destiny_ticket' on table 'ticketRelation' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
I also tried to do this with a trigger, but I am not sure how to define it.
Here I provide the tables definitions:
This is the base entity TICKET
CREATE TABLE ticket
(
ticket_id BIGINT,
some_data VARCHAR (50),
CONSTRAINT PK_ticket PRIMARY KEY (ticket_id)
);
and the relational table TICKETRELATION
CREATE TABLE ticketRelation
(
origin_ticket BIGINT,
destiny_ticket BIGINT,
relation_data VARCHAR (50),
CONSTRAINT PK_ticket_relation PRIMARY KEY (origin_ticket, destiny_ticket),
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id),
CONSTRAINT FK_destiny_ticket FOREIGN KEY (destiny_ticket)
REFERENCES ticket(ticket_id),
)
I want to add an ON DELETE CASCADE constraint to both foreign keys:
CONSTRAINT FK_origin_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- I want to add this --
CONSTRAINT FK_destiny_ticket FOREIGN KEY (origin_ticket)
REFERENCES ticket(ticket_id)
ON DELETE CASCADE, -- and this --

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

deferrable initially deferred in postgresql

I have a cyclic foreign keys on 2 tables, so i use deferrable initially deferred as below:
uni=# create table vorlesungen (vnr integer primary key, gelesenvon integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "vorlesungen_pkey" for table "vorlesungen"
CREATE TABLE
uni=# create table professoren (pnr integer primary key, lieblingsvo integer);
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "professoren_pkey" for table "professoren"
CREATE TABLE
uni=# alter table professoren add constraint vfk foreign key (lieblingsvo) references vorlesungen (vnr) deferrable initially deferred;
ALTER TABLE
uni=# alter table vorlesungen add constraint pfk foreign key (gelesenvon) references professoren (pnr) deferrable initially deferred;
ALTER TABLE
so far so good.
but now when i want to insert into the tables, i get foreign key violations, although i specified deferrable initially deferred:
uni=# insert into vorlesungen values (1, 1);
ERROR: insert or update on table "vorlesungen" violates foreign key constraint "pfk"
DETAIL: Key (gelesenvon)=(1) is not present in table "professoren".
uni=# insert into professoren values (1, 1);
ERROR: insert or update on table "professoren" violates foreign key constraint "vfk"
DETAIL: Key (lieblingsvo)=(1) is not present in table "vorlesungen".
whats the problem?
Are you explicitly opening a transaction before the
INSERTs? If you do not use BEGIN, each insert is an independent transaction, therefore enforcing the foreign keys at the end of each command.