C
C
coderlex2016-03-28 11:30:35
MySQL
coderlex, 2016-03-28 11:30:35

Rows of related tables are deleted inside the overall transaction?

Let's say there are 2 tables linked via a foreign key:

CREATE TABLE `post` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  ...
  PRIMARY KEY (`id`)
);

CREATE TABLE `post_comment` (
  `post_id` int(11) NOT NULL,
  ...
  FOREIGN KEY (`post_id`) REFERENCES `post`(`id`) ON DELETE CASCADE
);

If you execute
DELETE FROM `post` WHERE `id` = 1
Then, are the lines from post and post_comment internally deleted within a GENERAL transaction or a separate one for deletion from post and a separate one for post_comment?
In other words, a simple removal from post (as in the code above) at the internal level is analogous to this (option 1):
START TRANSACTION
SELECT * FROM `post` WHERE `id` = 1 FOR UPDATE
DELETE FROM `post_comment` WHERE `post_id` = 1
DELETE FROM `post` WHERE `id` = 1
COMMIT

Or an analogue of this (option 2):
START TRANSACTION
DELETE FROM `post_comment` WHERE `post_id` = 1
COMMIT
START TRANSACTION
DELETE FROM `post` WHERE `id` = 1
COMMIT

PS Also of interest is the question of the differences between Postgres and InnoDB in this regard. Therefore, I will be grateful if you indicate in the answer the DBMS for which it is valid.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Shelemetiev, 2016-03-31
@coderlex

In PostgreSQL, a transaction is consistent. That is, if you do DELETE FROM `post` WHERE `id` = 1, then all related deletions from `post_comment` will be in the same transaction. Those. option 1.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question