Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mjapanwala/93e1d8258f4cc122969093d89ff750bf to your computer and use it in GitHub Desktop.
Save mjapanwala/93e1d8258f4cc122969093d89ff750bf to your computer and use it in GitHub Desktop.
One to One Relationship
If you have two tables suppose Users table and a UsersProfile Table.
In your users table you will have things like user_id PRIMARY_KEY AUTO_INCREMENT/SERIAL, email VARCHAR(244), password varchar(12)
In your user_profile table you will have PRIMARY_KEY users.user_id FOREIGN_KEY users.user_id, first_name VARHCAR(122), last_name VARCHAR(133)
The primary and foreign key needs to be referencing the users table. The reason for this because it forces data integrity, and forcing a one to one relationship
between the two tables.
One-toOne relationships are typically used to split the data that may not always be needed together or to seperate sensitive information into
a seperate table,
Important features to know about foreign_keys, since foreign keys reference another tables primary_key.
What happens if that tables primary key got deleted?
We have something on the child table known as ON UPDATE OR ON DELETE associated with a foreign key as part of the foreign key declaration.
We have several things,
Common options include ON UPDATE:
CASCADE: Update the foreign key values based in the dependent tables to match the new primary key value
SET NULL: set the foreign key value(s) in the dependent table(s) to NULL
SET DEFAULT: set the foreign key value(s) in the dependent table(s) to their default value
RESTRICT: Prevent the update if it would violate referential integrity.
ON DELETE: Specifies the action to take when the referenced primary key is deleted.
CASCADE: Delete the dependent rows in the child table(s) along with the referenced row in the parent table.
SET NULL: Set the foreign key value(s) in the dependent table(s) to their default value.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment