0

I've got 2 tables say users and articles, I need to delete a user and all instances of that user from articles as well but I need to do it in a single statement. So I can't say:

DELETE FROM users WHERE id = 1
DELETE FROM articles WHERE user_id = 1

Is there a way I can say something like:

SELECT u.name, u.id, a.user_id
FROM users u, articles a
WHERE u.id = a.user_id
DELETE FROM thistable
WHERE id = 1

Any help would be greatly appreciated

1
  • 3
    What's wrong with doing it in two statements? Commented Jul 28, 2021 at 6:50

1 Answer 1

2

The standard way to do that is to declare the foreign key as ON DELETE CASCADE. Doing so, if a user is deleted, all articles related to it will also be deleted.

CREATE TABLE articles (
  user_id int REFERENCES users (id) ON DELETE CASCADE);

Demo: db<>fiddle

If for some reason you're not able to change the table structure, consider using a DELETE ... RETURNING from users inside a CTE and then use the returned values in a outer DELETE on articles:

WITH j (id) AS (
  DELETE FROM users WHERE id = 1
  RETURNING id
)
DELETE FROM articles a USING j 
WHERE a.user_id = j.id;

Demo: db<>fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.