Do foreign keys gets inserted when primary key is inserted? - sql

A very basic question I'm confused about, similar to UPDATE and DELETE CASCADE, do foreign keys gets inserted automatically when a referenced table's primary key is inserted?
Or are they simply a constraint that tells to check the primray key that is being reference and if present add, else error.
As a example, I'm asking about something like this:
...
CONSTRAINT idFK
FOREIGN KEY(id)
REFERENCES Users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
...
Here, will id in this table automatically get inserted when an id is inserted in Users table?

when you insert a record in "Users" table , nothing inserted in any other tables.
when you insert a record in a table with foreign key, the value of foreign key field just will check with the primary key value in parent(Here "Users") table.

Related

How to add delete cascade on staging table

Here how I created tables:
CREATE TABLE TABLE_A(
id uuid NOT NULL, UNIQUE
name text
);
CREATE TABLE TABLE_B(
id uuid NOT NULL, UNIQUE
name text
);
-- custom realization of many-to-many association
CREATE TABLE TABLE_A_B(
id uuid NOT NULL, UNIQUE
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE
);
I've already created tables and now can't update it by adding ON DELETE CASCADE.
And I need now to add ON DELETE CASCADE to staging table TABLE_A_B. How to do it ?(
You use ON DELETE CASCADE:
CREATE TABLE TABLE_A_B(
id uuid NOT NULL UNIQUE,
a_id uuid REFERENCES TABLE_A(id) ON UPDATE CASCADE ON DELETE CASCADE,
B_id uuid REFERENCES TABLE_B(id) ON UPDATE CASCADE ON DELETE CASCADE
);
Here is a db<>fiddle that fixed some typos in your code.
In particular, the foreign key reference should be to a primary key. Although allowed to a unique key, the purpose of primary keys is really to identify individual rows -- and one main use is for foreign key references.
EDIT:
If the constraints already exist, then do the following.
First, get their names:
select *
from information_schema.table_constraints
where constraint_type = 'FOREIGN KEY' and table_name = 'table_a_b';
Note: You can assign names to skip this step.
Then drop the existing foreign key constraint:
alter table table_a_b
drop constraint table_a_b_a_id_fkey;
Finally, add a new one:
alter table table_a_b
add constraint fk_table_a_b_a
foreign key (a_id) references table_a(id)
on update cascade
on delete cascade;

Update or Delete Violates foreign key constraint

I have two tables that look like the following.
CREATE TABLE book (
book_id BIGSERIAL PRIMARY KEY,
book_special_id character(10) NOT NULL DEFAULT random_string(10) UNIQUE,
author_id bigint REFERENCES author(author_id) ON DELETE RESTRICT,
category_id bigint REFERENCES category(category_id) ON DELETE RESTRICT,
title text NOT NULL,
subtitle text,
book_text text
);
CREATE TABLE booksubcategory (
booksubcategory_id BIGSERIAL PRIMARY KEY,
book_id BIGSERIAL REFERENCES book(book_id) ON DELETE CASCADE,
subcategory_id BIGSERIAL REFERENCES subcategory(subcategory_id) ON DELETE RESTRICT,
CONSTRAINT booksubcategory_book_id_subcategory_id_key UNIQUE (book_id, subcategory_id)
);
In this example the book_id column is the primary key in the book table, and the referenced foreign key in the booksubcategory table. When I try and run the following sql, I receive the error:
ERROR: update or delete on table "book" violates foreign key constraint "booksubcategory_book_id_fkey" on table "booksubcategory"
Detail: Key (book_id)=(888392) is still referenced from table "booksubcategory"
Here is what the SQL looks like.
INSERT INTO book (book_special_id, author_id, category_id, title, subtitle, book_text)
VALUES ("D4jOko2IP0",34, 4, "Book Example", "Book Subtitle", "Some lengthy text")
ON CONFLICT (book_special_id)
DO UPDATE SET author_id=EXCLUDED.author_id, book_id=EXCLUDED.book_id, category_id=EXCLUDED.category_id, title=EXCLUDED.title, subtitle=EXCLUDED.subtitle, book_text=EXCLUDED.book_text;
In this situation the sql should update the columns because the book_special_key already exists in the book table.
I'm familiar with the reason why updates and deletes on foreign key constraints can fail for integrity reasons, but in my case I'm not updating the book_id directly, just the columns in the book table. Also I have ON DELETE CASCADE set on the foreign key in the child table. Can someone tell my why I'm experiencing this issue?
The inserted row clashes on unique key special_book_id, then the conflict rule tries to update the duplicate row.
But what is the value book_id of a NEW row that was not yet inserted due to conflicts and is autogen? Well, either null or a new serial.
So, whatever the case, you are updating book_id to null or a new serial and it fails as the old book_id value, that is disappearing, has references.
Remove the update to column book_id and it should work.

Create a table in SQL where the Composite Primary Key is also a Foreign Key

I need to create a table called LFM_Enroll in SQL that has a composite primary key of Student_ID and Section_Number. Student_ID is also a foreign key, it references Student_ID in the LFM_Student table and Section_Number is also a foreign key, it references Section_Number in the LFM_Section table. How do I write the constraints and foreign keys? I've attached an image of the tables and below is what I have done so far. After the LFM_Enroll table is created I need to update one row. I tried doing so but kept getting the below error.
: Error starting at line : 173 in command -
UPDATE LFM_Enroll
SET Student_ID = 1234567,
Section_Number = 01234
WHERE Student_ID = 900000 AND Section_Number = 4138
Error report -
ORA-02291: integrity constraint (SYSTEM.FK_LFM_ENROLL_SECTION_NUMBER) violated - parent key not found.
Tables Thanks in advance for all your help.
CREATE TABLE LFM_Enroll (
Student_ID char(7),
Section_Number char(4),
constraint PK_LFM_Enroll Primary Key (Student_ID,Section_Number),
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID,Section_Number) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Student_ID,Section_Number) references LFM_Section (Section_Number)
);
Your foreign key constraints are not right. You are trying to map two columns {Student_ID,Section_Number} to a single column LFM_Student.Student_ID.
The number of columns in the principal key must match the number of columns in the foreign key. In other words, the key LFM_Student is one column (Student_ID), so the foreign key also needs to be a single matching column - in this case LFM_Enroll.Student_ID. Correct DDL would be:
constraint FK_LFM_Enroll_Student_ID
Foreign Key (Student_ID) references LFM_Student (Student_ID),
constraint FK_LFM_Enroll_Section_Number
Foreign Key (Section_Number) references LFM_Section (Section_Number)
I'm not quite sure why your RDBMS is allowing what you have, but it may be using the first column and simply ignoring the second. In which case FK_LFM_Enroll_Section_Number is creating a foreign key LFM_Enroll.Student_ID => LFM_Section.Section_Number.
The error indicates that the values with which you are trying to update the two columns may not exist in Student and / or Sections tables i.e. 1234567 doesn't exists in the student table and / or 01234 doesn't exist in your section table . You should try inserting new rows or updating existing ones with the new values you are trying to update your foreign keys with.
[Edit: For defining constraints refer lc.'s post]

On delete actions when a table has a 2 foreign key from 2 different tables

I have a table let's say table3 and it contains two foreign keys, each one referencing a different table. I want to learn that, could I define two different ON DELETE action for them.
Let me explain it via an example.
create table table3 (
ID varchar(255),
Name varchar(255),
primary key(ID,Name),
foreign key(ID) References user(id),
foreign key(Name) References shops(StoreName)
on update cascade
on delete cascade // I want to cascade table if id is deleted
on delete no actions); // and do not allowed if StoreName is deleted.
Is there anyone to help me ? Thanks in advance.
Not sure if I totally understand what you're trying to do - but if you want to have ON DELETE CASCADE on the fk reference to the User table, and ON DELETE NO ACTIONS on the fk reference to the Shops table, you need to use this T-SQL:
create table table3 (
ID varchar(255),
Name varchar(255),
primary key(ID,Name),
foreign key(ID) References user(id)
on delete cascade, // I want to cascade table if id is deleted
foreign key(Name) References shops(StoreName)
on update cascade
on delete no actions); // and do not allowed if StoreName is deleted.
You need to specify the ON DELETE .... action right with your foreign key definition

Table record update stopped by Foreign key constraint

I have a problem in updating records to a derby db table with foreign key. Consider the two tables QUESTIONCHOICE and QUESTIONANSWER below. The records in table QUESTIONANSWER is a subset of QUESTIONCHOICE and has a foreign key constraint to make sure QUESTIONANSWER table is always subset of QUESTIONCHOICE table.
Now i am trying to update a record in QUESTIONCHOICE table using the query below and the update is stopped by foreign key constraint.
update "USER"."QUESTIONCHOICE" set "CHOICE"='GET1' where "QID"=10001 and "CHOICE"='GET';
UPDATE on table 'QUESTIONCHOICE' caused a violation of foreign key constraint 'QUESTIONANSWER_FK' for key (10001,GET). The statement has been rolled back.
How am i supposed to update the records in the table QUESTIONCHOICE?
i can delete the record in QUESTIONANSWER table update my record in QUESTIONCHOICE table and then insert the record in QUESTIONANSWER. but it doesnt sounds good to me.
Also can i create QUESTIONANSWER as a VIEW instead a TABLE, If so how will i make a subset of QUESTIONCHOICE table?
please suggest.
Thanks,
-Vijay Selvaraj
----------
CREATE TABLE USER.QUESTIONCHOICE(
QID INT NOT NULL,
Choice VARCHAR(100) NOT NULL,
CONSTRAINT QUESTIONCHOICE_PK PRIMARY KEY (QID, Choice),
CONSTRAINT QUESTIONCHOICE_FK FOREIGN KEY (QID)
REFERENCES user.questionbank (QuestionID)
);
----------
create table USER.QUESTIONANSWER(
QID INT NOT NULL,
Answer VARCHAR(100) NOT NULL,
CONSTRAINT QUESTIONANSWER_PK PRIMARY KEY (QID, Answer),
CONSTRAINT QUESTIONANSWER_FK FOREIGN KEY (QID, Answer)
REFERENCES USER.QUESTIONCHOICE (QID, Choice)
);
Why dont you add a additional column to the QUESTIONCHOICE table to mark a row as the answer row, this way, the view also can be created by applying a constraint on the answer column.