Let’s assume that we have two tables users
and messages
with the following fields:
- users: id, name, email
- messages: id, content, user_id
I want to delete a user but keep all data in messages. Is there a way to do this?
Let’s assume that we have two tables users
and messages
with the following fields:
I want to delete a user but keep all data in messages. Is there a way to do this?
2
Answers
If there is no foreign key constraint on
messages.user_id
, you can simply delete the data fromusers
without affectingmessages
.In case of a foreign key constraint, simply set the desired
messages.user_id
tonull
first then delete the user.e.g in case of delete the user with id 5,
Unlike what I see in the comments, you can keep the foreign key from
messages
tousers
(it is actually recommended you do keep it, precisely because it allows the user id to be automatically set to null when deleting a user). You also do not need to update themessages
table first when you want to delete a user.The possible actions you can apply on your foreign key are described in the
CREATE TABLE
help page. What you want is create it withSET NULL
.For instance and skipping the creation of
users
(and assumingusers(id)
corresponds to a login and is of typevarchar
):As you can see, the foreign key constraint itself carries what should happen to the field when the corresponding record is deleted; if you delete a user, the DB will update the messages so that
User_ID
is set toNULL
everywhere it needs to.delete from users where id = 'SomeLogin'
is all you need.