How to add delete cascade constraint in sql - sql

I have 2 tables.Table A have columns as (aid, name,depart) where aid is primary key.
Table B has (aid1,aid2,aid3,created_by) where aid1 is the primary_key. aid1, aid2 and aid3 all are primary key of Table A
I want to delete a record in Table B i.e aid1 and simultaneously with delete cascade all three records in TABLE A should be deleted. My doubt here is where should I put the delete cascade constraint. I know that in parent child relationship we need to put delete cascade on the child table so that when parent is deleted, child entities are also deleted but in this scenario I dont understand where I should put delete cascade

Cascading a table will be on the child table. You have to set this on your child table when creating or after creating the child table.
E.g
CREATE TABLE schools (
id int auto_increment primary key not null,
schoolname varchar(191) not null
);
CREATE TABLE students(
id int auto_increment primary key not null,
studentname varchar(191) not null,
school_id int FOREIGN KEY REFERENCES students(id) ONDELETE CASCADE
);
or
You can as well alter the table by running this command.
ALTER TABLE childTable
ADD FOREIGN KEY (childTableParentTableColumn) REFERENCES parentTable(parentTableColumn);

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;

How to use DELETE ON CASCADE in this senario?

so I have 3 tables, Applicant, Vacancy and a Link table. I am trying to have the applicant data removed when the vacancy is removed. Here is the current SQL code I have, would this remove the applicant?
CREATE TABLE Applicant(
ID INT PRIMARY KEY,
name varchar(20),
address varchar(20),
VacancyID INT,
FOREIGN KEY (VacancyID) REFERENCES Vacancy(ID) ON DELETE CASCADE);
CREATE TABLE AppVac(
ApplicantID INT PRIMARY KEY,
VacancyID INT PRIMARY KEY,
FOREIGN KEY (ApplicantID) REFERENCES Applicant(ID),
FOREIGN KEY (VacancyID) REFERENCES Vacancy(ID);
CREATE TABLE Vacancy(
ID INT PRIMARY KEY,
.....
No. The Applicant has not relationship to the Vacancy. What gets removed are all corresponding rows in AppVac.
If you want to require that applicants have at least one row in AppVac, then you'll need a delete trigger on the table. Cascading foreign keys won't do that for you. That is, cascading deletes delete from the referring table, not from the reference table.

Create three tables with the same auto increment primary key and name

Cannot find a good answer for this online. I need to create three tables as an example below, a parent with an auto increment ID that will then link to the two child tables (Subject and Comment) with the same exact ID and cascade back if that parent ID is deleted.
Any ideas on how to solve?
I have googled and am extremely confused as to how to solve this one. I have a decent amount of experience with SQL, but not with creating tables and relationships.
CREATE TABLE Parent
(
ParentID INT NOT NULL IDENTITY PRIMARY KEY,
Email VARCHAR(50) NOT NULL,...
)
CREATE TABLE Subject
(
ParentID INT NOT NULL PRIMARY KEY,
Subject
)
CREATE TABLE Comment
(
ParentID INT NOT NULL PRIMARY KEY,
Comment VARCHAR(100)
)
Use a 1 to 1 relationship with on delete cascade:
CREATE TABLE Parent(
ParentID INT NOT NULL IDENTITY PRIMARY KEY,
Email VARCHAR(50) NOT NULL,...
)
CREATE TABLE Subject(
ParentID INT NOT NULL PRIMARY KEY,
Subject,
CONSTRAINT fk_SubjectParentId FOREIGN KEY (ParentID)
REFERENCES Parent (ParentID) ON DELETE CASCADE
)
CREATE TABLE Comment(
ParentID INT NOT NULL PRIMARY KEY,
Comment VARCHAR(100),
CONSTRAINT fk_CommentParentId FOREIGN KEY (ParentID)
REFERENCES Parent (ParentID) ON DELETE CASCADE
)
This is known as a 1 to 1 relationship, since both ends of the foreign key are unique within their table.
Though I have to agree with Mitch Wheat comment, cascading deletes is something to use with caution. by specifying cascade delete, you are telling the database engine to delete the related records whenever a parent record is deleted. Not having that cascade delete option will simply throw an error if you attempt to delete a record that is referenced by another table. This forces you, as a developer, to think about the side effects of deleting rows from the parent table and basically acts as a "Are you sure you want to delete?" guard against unwanted deletes.

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

Enforcing unique rows in a many-to-many junction table

I have a junction table for a many-to-many relationship that just links two foreign keys together. However I've found that this will not prevent duplicate identical row entries. What's the proper way of handling that? I thought adding PRIMARY KEY to the two foreign keys would do it, but it seems like I'm not understanding that correctly.
CREATE TABLE ab_link (
a_id bigint REFERENCES a(a_id) PRIMARY KEY,
b_id bigint REFERENCES b(b_id) PRIMARY KEY
);
I found on another question this example:
CREATE TABLE bill_product (
bill_id int REFERENCES bill (bill_id) ON UPDATE CASCADE ON DELETE CASCADE
, product_id int REFERENCES product (product_id) ON UPDATE CASCADE
, amount numeric NOT NULL DEFAULT 1
, CONSTRAINT bill_product_pkey PRIMARY KEY (bill_id, product_id) -- explicit pk
);
Is that constraint the best way of enforcing uniqueness? I would think there would be some way of doing it without having a third row.
For a compound primary key, you need a separate declaration:
CREATE TABLE ab_link (
a_id bigint REFERENCES a(a_id),
b_id bigint REFERENCES b(b_id),
PRIMARY KEY (a_id, b_id)
);