Database Relationships and Diagrams · Lesson 19 of 112

Database One-to-One

What you will learn

  • What a one-to-one relationship is
  • Why you might split one entity over two tables
  • How to enforce "at most one" with a key
  • How to find rows that have no partner

1. At most one on each side

In a one-to-one relationship, a row in table A is linked to at most one row in table B, and the reverse. Examples: a user and their profile, a person and their passport, an employee and their parking space.

users 1 ---------- 1 profiles

You could put everything in one table, so why split? Common reasons:

  • Optional data. Only some users fill in a profile. Putting those columns on users leaves many empty values (NULL).
  • Rarely used or large data. A big biography column slows nothing if it sits in its own table you read only when needed.
  • Different access. Sensitive details can be kept apart and protected separately (chapter 8).

If every row always has the partner and the data is small, one table is simpler. Do not split without a reason.

2. Enforcing "at most one"

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds a small table of its own to your browser's copy; run the examples from top to bottom, and press Reset data to start again.

A plain foreign key allows many children. To make it one-to-one, make the foreign key unique. The neatest way is to make it the child's primary key too. Each customer (in the School, each student) may get one profile row, keyed by the parent's id:

CREATE TABLE customer_profiles (
    customer_id INTEGER PRIMARY KEY REFERENCES customers (customer_id),
    bio      TEXT,
    birthday TEXT
);
INSERT INTO customer_profiles VALUES (1, 'Loves tea', '2000-05-01'), (3, 'Runs at dawn', '1999-11-12');
SELECT * FROM customer_profiles ORDER BY customer_id;
customer_id  bio           birthday
-----------  ------------  ----------
          1  Loves tea     2000-05-01
          3  Runs at dawn  1999-11-12
(2 rows)
CREATE TABLE customer_profiles (
    customer_id INTEGER PRIMARY KEY REFERENCES customers (customer_id),
    bio      TEXT,
    birthday TEXT
);
INSERT INTO customer_profiles VALUES (1, 'Loves tea', '2000-05-01'), (3, 'Runs at dawn', '1999-11-12');
SELECT * FROM customer_profiles ORDER BY customer_id;
customer_id  bio           birthday
-----------  ------------  ----------
          1  Loves tea     2000-05-01
          3  Runs at dawn  1999-11-12
(2 rows)
CREATE TABLE student_profiles (
    student_id INTEGER PRIMARY KEY REFERENCES students (student_id),
    bio      TEXT,
    birthday TEXT
);
INSERT INTO student_profiles VALUES (1, 'Loves tea', '2000-05-01'), (3, 'Runs at dawn', '1999-11-12');
SELECT * FROM student_profiles ORDER BY student_id;
student_id  bio           birthday
----------  ------------  ----------
         1  Loves tea     2000-05-01
         3  Runs at dawn  1999-11-12
(2 rows)

The id column of the new table is both its primary key and a foreign key. A primary key cannot repeat, so each row of the parent can have only one profile row, and the profile cannot exist without a real parent row.

3. What the database refuses

A second profile for the same row breaks uniqueness; a profile for a row that does not exist breaks the foreign key:

INSERT INTO customer_profiles VALUES (1, 'Second', '2001-01-01');
IntegrityError: UNIQUE constraint failed: customer_profiles.customer_id
INSERT INTO customer_profiles VALUES (999999, 'Nobody', '2001-01-01');
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO customer_profiles VALUES (1, 'Second', '2001-01-01');
IntegrityError: UNIQUE constraint failed: customer_profiles.customer_id
INSERT INTO customer_profiles VALUES (999999, 'Nobody', '2001-01-01');
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO student_profiles VALUES (1, 'Second', '2001-01-01');
IntegrityError: UNIQUE constraint failed: student_profiles.student_id
INSERT INTO student_profiles VALUES (999999, 'Nobody', '2001-01-01');
IntegrityError: FOREIGN KEY constraint failed

4. Rows without a partner

The relationship is "at most one", so some rows have none. A LEFT JOIN shows both kinds:

SELECT p.customer_id, p.last_name, pr.bio
FROM customers p
LEFT JOIN customer_profiles pr ON pr.customer_id = p.customer_id
ORDER BY p.customer_id
LIMIT 4;
customer_id  last_name  bio
-----------  ---------  ------------
          1  Ahmed      Loves tea
          2  Ahmed      NULL
          3  Costa      Runs at dawn
          4  Nair       NULL
(4 rows)
SELECT p.customer_id, p.full_name, pr.bio
FROM customers p
LEFT JOIN customer_profiles pr ON pr.customer_id = p.customer_id
ORDER BY p.customer_id
LIMIT 4;
customer_id  full_name    bio
-----------  -----------  ------------
          1  Chen Park    Loves tea
          2  Rafi Uddin   NULL
          3  Grace Kamau  Runs at dawn
          4  Mei Bianchi  NULL
(4 rows)
SELECT p.student_id, p.last_name, pr.bio
FROM students p
LEFT JOIN student_profiles pr ON pr.student_id = p.student_id
ORDER BY p.student_id
LIMIT 4;
student_id  last_name  bio
----------  ---------  ------------
         1  Khan       Loves tea
         2  Haque      NULL
         3  Garcia     Runs at dawn
         4  Meyer      NULL
(4 rows)

Rows 2 and 4 have no profile, so the profile column is NULL. To list only the rows without a partner, add a WHERE on the profile's id column IS NULL; to count them:

SELECT COUNT(*) AS without_profile
FROM customers p
LEFT JOIN customer_profiles pr ON pr.customer_id = p.customer_id
WHERE pr.customer_id IS NULL;
without_profile
---------------
            418
(1 row)
SELECT COUNT(*) AS without_profile
FROM customers p
LEFT JOIN customer_profiles pr ON pr.customer_id = p.customer_id
WHERE pr.customer_id IS NULL;
without_profile
---------------
            298
(1 row)
SELECT COUNT(*) AS without_profile
FROM students p
LEFT JOIN student_profiles pr ON pr.student_id = p.student_id
WHERE pr.student_id IS NULL;
without_profile
---------------
            358
(1 row)

Worked example: should this be one table or two?

A shop keeps employees(name, phone). Only the 3 managers (out of 40 staff) also have a company car with a plate number, make and insurance date.

Option Result
One table, car columns on employees 37 rows with four empty values each
Two tables, cars(employee_id PRIMARY KEY REFERENCES employees(id), plate, make, insured_until) only the 3 real cars are stored; one car per employee is enforced

Two tables fit better here. The numbers are made up.

Common mistakes

  • Forgetting the uniqueness, which silently turns the link into one-to-many.
  • Splitting for no reason, making every query need a join.
  • Treating "at most one" as "exactly one". The partner row may be absent unless you design it to exist.
  • Using a plain JOIN and losing the rows with no partner.

Key takeaways

  • One-to-one links a row to at most one row in another table.
  • Split tables for optional, bulky or separately protected data.
  • Make the foreign key the child's primary key (or UNIQUE) to enforce it.
  • The database then refuses a second partner or a missing parent.
  • LEFT JOIN shows rows without a partner.

Practice

1. Name two real-life one-to-one examples.

Show answer

For example, a person and their passport, or a user and their profile.

2. How do you stop a user from getting two profiles?

Show answer

Make profiles.user_id the primary key (or give it a UNIQUE constraint).

3. What error appears when inserting a profile for a user that does not exist?

Show answer

FOREIGN KEY constraint failed (with foreign keys switched on).

4. Why did some rows show NULL in the profile column of the join result?

Show answer

Those rows have no profile row, and LEFT JOIN fills the missing side with NULL.

5. Give one good reason to split data into a one-to-one table.

Show answer

Optional data (avoids many empty values), bulky rarely-used data, or data that needs separate protection.

6. What would a plain (non-unique) foreign key in profiles allow that we do not want?

Show answer

Several profile rows for the same user, which is a one-to-many relationship.