One-to-one Relationship in PostgreSQL

By Hemanta Sundaray on 2022-12-03

Let’s say we have a driver table with the following columns:

  • name
  • address
  • date_of_birth
  • license_id

We also have a license table with the following columns:

  • id
  • state_issued
  • date_issued
  • date_expired

In the driver table, the primary key that uniquely identifies a driver would be the license_id. Similarly, the primary key that uniquely identifies a driver’s license in the license table would be the id itself.

To establish a one-to-one relationship in PostgreSQL between these two tables, we need to designate a foreign key in one of the tables. We can pick the license_id from driver to be the foreign key in the license table. However, doing this is not enough to ensure that duplicate rows will not exist in the license table.

To enforce a strictly one-to-one relationship in PostgreSQL, we need another keyword, UNIQUE. By appending this keyword to the declaration of the foreign key, we should be all set.

license_id char(20) REFERENCES driver(license_id) UNIQUE

The full PostgreSQL script for creating these two tables is as follows:

CREATE TABLE driver (
    license_id char(20) PRIMARY KEY,
    name varchar(20),
    address varchar(100),
    date_of_birth date
);

CREATE TABLE license (
    id integer PRIMARY KEY,
    state_issued varchar(20),
    date_issued date,
    date_expired  date,
    license_id char(20) REFERENCES driver(license_id) UNIQUE
);

Join the Newsletter