[SQL] 1:1 relationship
1:1 relationship
How did I encounter this?
Some games in Wikidata have multiple release dates. It might vary due to several reasons such as different platform, or regions. For the future, I want to gather the release dates separated by those reasons if needed. I realized that it's more reasonable to have separate tables. An extra table for release dates, platforms, and regions. To do so, FOREIGN KEY should be used. For that, I was considering connecting the 2 tables with a column named id, a unique and auto incremented column. There I encountered the concept of 1:1 relationship.
Syntax
A one-to-one (1:1) relationship in relational databases means each row in Table A corresponds to at most one row in Table B, and each row in Table B corresponds to at most one row in Table A. In simpler terms, one item in one table is tied to zero or one matching item in the other table.
Example
-
Users Table – Stores main user data:
CREATE TABLE users (user_id INT AUTO_INCREMENT PRIMARY KEY,username VARCHAR(50) NOT NULL-- possibly more fields); -
User Profiles Table – Stores optional extra data (like a biography, avatar URL, etc.):
CREATE TABLE user_profiles (profile_id INT PRIMARY KEY, -- same numeric ID as users.user_idbio TEXT,avatar_url VARCHAR(255),CONSTRAINT fk_profile_userFOREIGN KEY (profile_id) REFERENCES users(user_id)ON DELETE CASCADE);
Here, each row in user_profiles matches exactly one row in users by using the same primary key value. If user #5 has a profile, then profile_id = 5 is the row in user_profiles. If user #5 has no profile, there’s simply no row for #5 in user_profiles.
Characteristics of 1:1 Relationships
- Each entity in
userscan have 0 or 1 matching row inuser_profiles. - Matching is done by the same ID (or by a unique foreign key referencing the user’s primary key).
- Often used to split off rarely used or sensitive columns into a separate table (e.g., storing private data, optional extended info).
Benefits of 1:1 relationship
-
Optional Data
- If not every user needs a profile, it's possible to keep the main
userstable lean, and only have rows inuser_profilesfor those who want a profile.
- If not every user needs a profile, it's possible to keep the main
-
Security or Performance
- it might be possible to store sensitive data in a separate table, different permissions can be applied or it might be loaded less frequently.
-
Normalization
- If there is a large set of columns that don’t apply to every row, they can be moved into a separate table to keep the main table slimmer.
Comments
Post a Comment