forked from bbrumm/databasestar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample_data_on_delete_cascade.sql
93 lines (73 loc) · 1.79 KB
/
sample_data_on_delete_cascade.sql
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
Sample data for the On Delete Cascade post
*/
/*
Create and populate tables
*/
CREATE TABLE category (
id INT,
category_name VARCHAR(50),
CONSTRAINT pk_category PRIMARY KEY (id)
);
CREATE TABLE product (
id INT,
category_id INT,
product_name VARCHAR(50),
CONSTRAINT pk_product PRIMARY KEY (id),
CONSTRAINT fk_prod_category
FOREIGN KEY (category_id) REFERENCES category(id)
);
INSERT INTO category (id, category_name) VALUES
(1, 'Electronics'),
(2, 'Furniture');
INSERT INTO product (id, category_id, product_name) VALUES
(1, 2, 'Desk Chair'),
(2, 2, 'Couch'),
(3, 1, 'TV'),
(4, 1, 'Coffee Machine');
/*
Delete parent row
*/
DELETE FROM category WHERE id = 1;
/*
You should see an error like this (MySQL error shown):
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`my_new_db`.`product`, CONSTRAINT `fk_prod_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`))
*/
/*
Drop and recreate tables with ON DELETE CASCADE
*/
DROP TABLE product;
DROP TABLE category;
CREATE TABLE category (
id INT,
category_name VARCHAR(50),
CONSTRAINT pk_category PRIMARY KEY (id)
);
CREATE TABLE product (
id INT,
category_id INT,
product_name VARCHAR(50),
CONSTRAINT pk_product PRIMARY KEY (id),
CONSTRAINT fk_prod_category
FOREIGN KEY (category_id) REFERENCES category(id)
ON DELETE CASCADE
);
INSERT INTO category (id, category_name) VALUES
(1, 'Electronics'),
(2, 'Furniture');
INSERT INTO product (id, category_id, product_name) VALUES
(1, 2, 'Desk Chair'),
(2, 2, 'Couch'),
(3, 1, 'TV'),
(4, 1, 'Coffee Machine');
/*
Delete parent row
*/
DELETE FROM category WHERE id = 1;
/*
Select from the tables
*/
SELECT id, category_name
FROM category;
SELECT id, category_id, product_name
FROM product;