Delete query in sqlite for child tables - database

I have 3 tables, like Employee, Department and Electronics tables.
Electronics table is child table for Department table and Department table is child table for Employee table.
I want to delete one record in Employee table where E_id=2 ( this is Primary key) this is Foreign key in Department table (E_id is Foreign key and Dept_id is Primary key) and Dept_id is Foreign Key in Electronics table.
First I want to delete related records in Electronics table then Department table and finally Employee table.
Please guide me how to do it.

You can read more about foreign key support in sqlite here: http://www.sqlite.org/foreignkeys.html
but you should be able to turn it on:
sqlite> PRAGMA foreign_keys = ON;
and then setup the database schema with the deletes cascading:
-- Database schema
CREATE TABLE Employee(
E_id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE Department(
Dept_id INTEGER PRIMARY KEY,
name TEXT,
E_id INTEGER REFERENCES Employee(E_id) ON DELETE CASCADE
);
CREATE TABLE Electronics(
Elec_id INTEGER PRIMARY KEY,
name TEXT,
Dept_id INTEGER REFERENCES Department(Dept_id) ON DELETE CASCADE
);
With all this in place and the data in the tables:
DELETE FROM Employee WHERE E_id = 2;

Related

Chicken or Egg problem in table schema [PostgreSQL]

How do I create and insert rows to the following table schema in PostgreSQL:
Table: employee
emp_id, emp_name, emp_dept, emp_manager
Table: department
dept_id, dept_name, dept_manager
emp_manager is a foreign key to employee(emp_id)
emp_dept is a foreign key to department(dept_id)
dept_manager is a foreign key to employee(emp_id)
It can work like this:
CREATE TABLE employee (
emp_id int PRIMARY KEY
, emp_dept int NOT NULL
, emp_manager int
, emp_name text NOT NULL
, CONSTRAINT fk_emp_manager FOREIGN KEY (emp_manager) REFERENCES employee(emp_id)
, UNIQUE (emp_dept, emp_id) -- needed for FK fk_dept_manager
);
CREATE TABLE department (
dept_id int PRIMARY KEY
, dept_manager int
, dept_name text NOT NULL
, CONSTRAINT fk_dept_manager FOREIGN KEY (dept_id, dept_manager) REFERENCES employee(emp_dept, emp_id)
);
ALTER TABLE employee
ADD CONSTRAINT fk_emp_dept
FOREIGN KEY (emp_dept) REFERENCES department(dept_id);
Note how I change fk_dept_manager into a multicolumn FK reference to only allow employees of the same department to be department manager. Assuming you want that.
You might also want a CHECK constraint in table employee to disallow employees from being their own manager:
CHECK (emp_manager <> emp_id)
How to INSERT?
As usual. To overcome mutual dependencies, either make FK constraints DEFERRABLE and run multiple commands in a single transaction (more expensive) or use a single command with one or more CTEs.
Example: to insert a new department and a new employee as its manager at once:
WITH ins_dept AS (
INSERT INTO department
(dept_manager , dept_name)
VALUES (nextval(pg_get_serial_sequence('employee', 'emp_id')), 'Sales')
RETURNING *
)
INSERT INTO employee
(emp_id , emp_dept, emp_manager, emp_name)
SELECT dept_manager, dept_id , NULL, 'Bob'
FROM ins_dept;
db<>fiddle here
Further reading:
Complex foreign key constraint in SQLAlchemy
SET CONSTRAINTS ALL DEFERRED not working as expected
How to deal with mutually dependent inserts

T-SQL inserting data into table with foreign key

I'm using SQL Server 2014 to create and insert data into tables and came along a problem when it comes to populating a table with a foreign key constraint in it. I have a table user and and a table city which were created beforehand.
I used code to alter the user table to include a cityId foreign key from table city with this code:
ALTER TABLE [Schema].[user]
ADD cityId UNIQUEIDENTIFIER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
GO
Basically I modified the user table by adding a field called cityId which i made foreign key. now the problem is that when inserting data, in the first line
INSERT INTO [Schema].[user](name, surname, dob, gender, .. )
cityId cannot be found to be mapped. Dunno why it ain't showing. In the design view it is listed as a foreign key so there should be no problems.
Thanks a lot
try :
ALTER TABLE [Schema].[user]
ADD cityId NUMBER NOT NULL
CONSTRAINT usr_cid_fk
FOREIGN KEY (cityId) REFERENCES [Schema].[city] (cityId);
Note :
For ADD cityId UNIQUEIDENTIFIER NOT NULL
By the SQL standard, a foreign key must reference either the primary key or a unique key of the parent table. If the primary key has multiple columns, the foreign key must have the same number and order of columns. Therefore the foreign key references a unique row in the parent table; there can be no duplicates.

Transfer data with different type Primary key

I'm redesigning very old DB where new tables have PK type UNIQUEIDENTIFIER and old tables have INT. There are also many relationships between tables. Can anyone help with how not to lose any relationships and change PK type when transferring data?
Old Table: Item(PK - itemID(int), FK - Vendor_Id(int), and Manufacture_Id(int) Manufacture ID is not as set FK but it should be in new table.
Let's say you have empty School and Student tables with UNIQUEIDENTIFIER typed primary keys named id.
Let's say the relationship between students and schools is many-to-one, via a school_id foreign key.
The old tables are called oldSchool and oldStudent and have id columns of type int. oldStudent
also has a foreign key named school_id.
Steps to take:
Extend all new tables that are referenced to by foreign keys with an extra column called old_id of type int. In the example table School would get this extra column:
ALTER TABLE School ADD old_id int;
All foreign key columns should get a sybling column of type int, called old_original_name. In our example
Student should get an extra old_school_id column
Temporarily disable foreign key constraints:
SET foreign_key_checks = 0;
Or, if that fails, drop all the foreign keys, to recreate them later, for example:
ALTER TABLE Student DROP FOREIGN KEY fk_school_id;
Also make those foreign key columns nullable:
ALTER TABLE Student MODIFY school_id int NULL;
Insert records from the old tables into the new tables, making sure the values of
primary keys and foreign keys are stored in the target's corresponding old_xxxxxx columns.
In the example, it would look like this:
INSERT INTO School (old_id, name, address)
SELECT id, name, address
FROM oldSchool;
INSERT INTO Student (name, class, old_school_id)
SELECT name, class, school_id
FROM oldStudent;
Update the foreign key columns which are null by looking up the new id via the old_xxxx foreign key values. In our example:
UPDATE Student
SET school_id = (
SELECT id
FROM School
WHERE old_id = Student.old_id);
Now make those foreign key columns not nullable again:
ALTER TABLE Student MODIFY school_id int NOT NULL;
Enable the foreign key constraints again.
SET foreign_key_checks = 1;
Or if you had to drop them, recreate them, for example:
ALTER TABLE Student
ADD CONSTRAINT fk_school_id
FOREIGN KEY (school_id)
REFERENCES School(id);
Optionally drop all the old_xxxxx columns from all your tables. In the example:
ALTER TABLE Student DROP COLUMN old_school_id;
ALTER TABLE School DROP COLUMN old_id;
Optionally drop all old tables. In the example:
DROP TABLE oldStudent;
DROP TABLE oldSchool;
Done.

How to model this many-many relation in Database?

We have two tables ManagementPlan which tells what type of product model has to be used.Based on this model number, a particular product of that type is assigned to a patient during therapy session.How can we model the many-many relation between Product table and ManagementPlan table
MangamentPlan(
PlanID(PK),
DiagnosisID(FK),
PhysicianID(FK),
PMCModelID,
Objective,
Description,
DateTime
)
Product(
PMCProductID(PK),
ManuProductID(FK),
ManufacturerID(FK),
PMCModelID,
Manufacturer model,
Features description,
PurchaseDate,
Storage Location
)
Add a junction table:
ManagementPlanProduct(PlanID(PK, FK(ManagementPlan)), PMCProductID(PK, FK(Product)))
You need a junction table
ManagementPlanProduct (
PlanID (PK, FK)
PMCProductID (PK, FK)
)
CREATE TABLE ManagementPlanProduct (
PlanID int NOT NULL,
PMCProductID int NOT NULL,
CONSTRAINT PK_mpp PRIMARY KEY CLUSTERED (PlanID, PMCProductID)
);
ALTER TABLE ManagementPlanProduct
ADD CONSTRAINT FK_mpp_mp
FOREIGN KEY (PlanID) REFERENCES ManagementPlan (PlanID)
ON DELETE CASCADE;
ALTER TABLE ManagementPlanProduct
ADD CONSTRAINT FK_mpp_p
FOREIGN KEY (PMCProductID) REFERENCES Product (PMCProductID)
ON DELETE CASCADE;
You can also add other columns to the junction table like quantity, date added, sort order and so on.

SQL Server keys and foreign keys

If I have a primary key in table A and in table B of the same database (table B has its own primary key) I create a relationship with the primary key in table A so that a column in table B is the foreign key, does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column or do I have to code that relationship, and if so how do I go about that?
In response to your question:
...do I have to code that
relationship, and if so how do I go
about that?
You will need to define the relationships between the two tables. Example:
ALTER TABLE tableB
ADD CONSTRAINT FK_tableB_TableA FOREIGN KEY (tableAId)
REFERENCES tableA (id) ;
When you insert a record into tableB you will still need to define tableAId is. SQL Server doesn't magically know what this should be.
So hypothetically if tableA looked like this:
1 | Some text | 1/1/2020
2 | blah blah | 6/1/2021
To insert a record in tableB that referenced record 2 you would need to do this:
INSERT INTO TableB (2,'My important information')
This assumes tableB has the following structure:
TableB
---------
Id --identity column/pk
tableAId --fk
SomeTextColumn
Your Q : does it mean that the primary key data created in the primary key column of table A will also be added to table B by virtue of it being a foreign key column
Nope, foriegn keys will not enter data into other tables. You will need a record in Table A before you insert a record referencing that foriegn key in Table B.
Q # 2 : or do I have to code that relationship, and if so how do I go about that?
insert into tableA, then insert into Table B. A trigger could be put on TableA to insert a record into TableB when data was entered into tableA had you wanted...
I'm not entirely sure what you're asking, but if you want to insert one record into table A and a related record into table B, then you have to specify the id from the table A record as the value in the foreign key field in table B.
Here's an example: table author has fields id and name.
INSERT author (id, name) VALUES (5, 'James Joyce')
Now table book has fields id, author_id and title.
INSERT book (id, author_id, title) VALUES(99, 5, 'Ulysses')
If the author's id field is automatically generated, then you would not specify it in the insert statement, and you would retrieve its value using the ##IDENTITY property.

Resources