There are 2 tables 'users' and 'address'.
create table address (
username varchar(255) not null,
address1 varchar(255),
primary key (username)
)
and
create table users (
user_id varchar(255) not null,
username varchar(255) not null,
address varchar(255) not null,
primary key (user_id)
)
'users' has few columns including a column named 'address' and this 'users' table is altered with
1. alter table if exists users add constraint uk_users_username unique (username)
2. alter TABLE users ADD CONSTRAINT fk_user_address FOREIGN KEY(address) REFERENCES address(username) ON DELETE RESTRICT ON UPDATE CASCADE
(just trying to make a 'users' to 'address' OneToOne unidirectional relation)
Now, as expected, When I add a valid record in 'users' it automatically adds one entry to 'address'. And also, when I use one of the below DELETE sqls
1. delete from users where user_id = 'some_user_id';
2. delete from users where username = 'some_user_name';
it deletes the record from the 'users' table, as expected; but the related record from 'address' is not deleted.
Question: Shouldn't it complain 'users' table has a constraint on 'address' and this "user" cannot be deleted until the related record in 'address' is deleted as well(because we have ...ON DELETE RESTRICT ON UPDATE CASCADE)?
Thanks in advance!!
ON DELETE RESTRICT
prevents deleting records from the parent table if any child is pointing to it. In your case however, you are defining the FK on the users
table and referencing address
, making users
the child, and address
the parent. So, you are able to delete from users
despite the constraint. If you'd like the constraint to work as you're describing, you'll have to flip them around and put your FK on the address
table.
When defining a foreign key, the owner table becomes the "child" in the relationship, and the referenced table becomes the parent. ON DELETE RESTRICT
protects the parent, not the child.
Also, generally speaking, it is ill-advised to add FK constraints on columns containing business-relevant data. Your usernames may be unique today, but an undefined time later someone may come along and wish for them to not be unique anymore. By adding the FK constraint, you'd be making that impossible. Instead, a better idea is to add the FK on the id of the record, and you should always have non-business-related unique identifiers ( like a generated id )