[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 

  1. Users Table – Stores main user data:

    CREATE TABLE users (
        user_id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL
        -- possibly more fields
    );
  2. 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_id
        bio TEXT,
        avatar_url VARCHAR(255),
        CONSTRAINT fk_profile_user
          FOREIGN 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

  1. Each entity in users can have 0 or 1 matching row in user_profiles.
  2. Matching is done by the same ID (or by a unique foreign key referencing the user’s primary key).
  3. 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

  1. Optional Data

    • If not every user needs a profile, it's possible to keep the main users table lean, and only have rows in user_profiles for those who want a profile.
  2. 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.
  3. 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