How to optimaly delete records from a parent and associated children table

47 Views Asked by At

We have a three table structure similar with the below:

CREATE table publications (
    id UUID PRIMARY KEY ,
    type CHAR(1) NOT NULL CHECK (type IN ('B', 'P')),
    title VARCHAR(60),
    publish_date DATE,
    author VARCHAR(50)
);

CREATE table books (
   id UUID PRIMARY KEY ,
   isbn VARCHAR(20),
   pages_no INT,
  CONSTRAINT books_fk FOREIGN KEY (id) REFERENCES publications(id)
);

CREATE TABLE posts (
   id UUID PRIMARY KEY ,
   comments_no INT,
   likes_no INT,
   unlikes_no INT,
   CONSTRAINT posts_fk FOREIGN KEY (id) REFERENCES publications(id)
);
INSERT INTO publications (id, type, title, publish_date, author)
VALUES('5a428ea2-b5a9-48e0-8865-e2fe5f653473', 'B', 'Some book title', current_date, 'John Doe');

INSERT INTO publications (id, type, title, publish_date, author)
VALUES('15a7a75a-3ac7-4628-8735-174d8709bc4a', 'P', 'Some post title', current_date, 'John Doe');

INSERT INTO books (id, isbn, pages_no)
VALUES ('5a428ea2-b5a9-48e0-8865-e2fe5f653473', 'some isbn', 123);

INSERT INTO posts (id, comments_no, likes_no, unlikes_no)
VALUES ('15a7a75a-3ac7-4628-8735-174d8709bc4a', 10, 20, 3);

The reason behind this structure is that our architects put together an API that returns all publications for an author irrespective they are books or posts. Also they want to delete a publication based on its id.

Solution 2 of the accepted answer to this question shows a way to delete from both parent table and associated child table with only one single SQL, but that, if works, is a MySQL solution and it does not work in PostgreSQL.

So my question is: Is there a way to only have one DELETE statement and delete one publication from both parent table and its associated table based on its id without knowing the type of the publication?

If this cannot be done in an elegant way, what would be a better way to achieve this? One way that came to my mind was to have a book_id and a post_id in publications table (only one of them NOT NULL) and have two FOREGN KEY constraints to books and and respective posts tables with CASCADE DELETE but this looks a bit dirty solution to myself because it can become a bit nasty when the number of child tables increases.

Another thing that came to my mind was to have books and posts tables inherit from publications and keep the publication empty and only populate the data in books and respective posts but this again looked a bit complex and our use case does not seem like the reason inheritance concept was added.

0

There are 0 best solutions below