L
L
lozhkinandrei2015-12-13 14:56:45
MySQL
lozhkinandrei, 2015-12-13 14:56:45

How does ON DELETE CASCADE work in MySQL?

Hello!
I can't find and understand exactly how referential integrity works on the example of ON DELETE CASCADE in MySQL.
There is a parent table:

CREATE TABLE ReportDate
(
   report_id              int unsigned auto_increment   NOT NULL, 
   report_date          smalldatetime    NOT NULL   DEFAULT CURRENT_SMALLDATETIME(),
   PRIMARY KEY (report_id)
);

There is a child table:
CREATE TABLE Report
(
   report_id            int unsigned     NOT NULL, 
   user_id               int unsigned     NOT NULL,
   PRIMARY KEY (report_id),
   FOREING KEY (report_id) REFERENCES ReportDate(report_id)
                          ON DELETE CASCADE,
   FOREING KEY (user_id) REFERENCES UserLogin(user_id)
);

If a data row for a specific report_id is deleted, what will happen in the child tables? Will the data in only one "cell" report_id be deleted (with reference to NULL, then this argument must be valid NULL; then, accordingly, what is the difference with SET NULL)? Or will the entire row of data in the child table associated with the deleted particular report_id (i.e. both the particular report_id and its corresponding user_id) be deleted?
PS: do not judge strictly for the quality of the question and the code - I'm learning in the process...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
grabbee, 2020-12-01
@grabbee

ON DELETE CASCADE - will delete a row in the child table when deleting in the main one.
SET NULL - set the ID value to NULL if you delete a row in the main table. To do this, the subtable must allow a NULL value for that column.
Constraints are set on each sub-table. Whatever you set ON DELETE CASCADE or SET NULL will happen.
Described in detail in Russian https://metanit.com/sql/mysql/2.5.php Helped
me...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question