This repository was archived by the owner on Jul 16, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask7.sql
More file actions
64 lines (46 loc) · 1.17 KB
/
Copy pathtask7.sql
File metadata and controls
64 lines (46 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
CREATE DATABASE task7;
USE task7;
--Create departments Table
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50) NOT NULL
);
--Create employees Table
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50) NOT NULL,
department_id INT,
FOREIGN KEY (department_id)
REFERENCES departments(department_id)
ON DELETE CASCADE
);
--Insert Valid Records
-- Insert departments
INSERT INTO departments VALUES
(1, 'HR'),
(2, 'IT'),
(3, 'Finance');
-- Insert employees
INSERT INTO employees VALUES
(101, 'Ravi', 1),
(102, 'Anu', 2),
(103, 'Karthik', 2),
(104, 'Meena', 3);
-- Display Initial Data
SELECT * FROM departments;
--Attempt Invalid Foreign Key Insert (ERROR CASE)
INSERT INTO employees VALUES
(105, 'Suresh', 5);
--Error:
--Cannot add or update a child row:
--a foreign key constraint fails
--Because department_id = 5 does NOT exist in departments
--Demonstrate ON DELETE CASCADE
DELETE FROM departments WHERE department_id = 2;
--Automatically deletes employees:
--Anu
--Karthik
--No manual deletion needed in employees
--Verify Data
SELECT * FROM departments;
SELECT * FROM employees;