Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a sound relational schema, give each row a reliable identifier, enforce other uniqueness rules separately, connect tables with foreign keys, and use constraints to reject invalid data. The SQL examples below use PostgreSQL syntax and document behavior described in PostgreSQL 18 unless noted; check your own database engine and version before relying on engine-specific details.

What is a primary key?

A primary key is the column or group of columns that identifies each row in a table. In PostgreSQL, its values must be unique and non-null, and a table can have at most one primary-key constraint. A key can consist of multiple columns. See the PostgreSQL 18 constraints documentation.

CREATE TABLE customers (
    customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL UNIQUE
);

Here, customer_id is the table’s designated row identifier. The separate UNIQUE constraint protects email addresses from duplication; it does not make email the primary key. This separation is useful when an account also has a business identifier, such as an externally assigned code, that must not repeat.

When should I use a composite key?

Use a composite key when the rule says a combination of values identifies a row or must not repeat. For example, a membership table might allow a person to join a group only once:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
CREATE TABLE group_memberships (
    group_id bigint NOT NULL,
    person_id bigint NOT NULL,
    joined_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (group_id, person_id)
);

The pair is unique even though neither column has to be unique on its own. If other tables or application code benefit from a compact, stable single-column identifier, you can instead define that identifier as the primary key and enforce the pair with a composite unique constraint:

CREATE TABLE group_memberships (
    membership_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    group_id bigint NOT NULL,
    person_id bigint NOT NULL,
    joined_at timestamptz NOT NULL DEFAULT now(),
    UNIQUE (group_id, person_id)
);

Choose based on the data rule and how the row will be referenced; a composite key is neither automatically superior nor inferior to a single-column key. PostgreSQL supports both multi-column primary keys and multi-column unique constraints.

What does a foreign key do?

A foreign key requires values in one table to match an eligible key in another table, protecting referential integrity. In PostgreSQL, the referenced columns must be covered by a primary key, a unique constraint, or a non-partial unique index. For example:

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
CREATE TABLE orders (
    order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id bigint NOT NULL REFERENCES customers(customer_id)
);

Because customer_id is NOT NULL, every order must refer to a customer, and the foreign key rejects an order whose customer does not exist. If the relationship is optional, allow the referencing column to be null and omit NOT NULL. PostgreSQL’s foreign-key tutorial demonstrates that a reference to a nonexistent parent row is rejected.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Composite foreign keys and nulls

A foreign key may reference a group of columns. Under PostgreSQL’s default MATCH SIMPLE behavior, a referencing row does not need a match if any referencing column is null. MATCH FULL permits that exception only when all referencing columns are null; a mix of null and non-null values does not qualify. Make the columns NOT NULL when partial or absent references should not be allowed.

CREATE TABLE shipment_items (
    shipment_id bigint NOT NULL,
    item_number integer NOT NULL,
    product_id bigint NOT NULL REFERENCES products(product_id),
    PRIMARY KEY (shipment_id, item_number)
);

How do I model relationships?

Start by deciding whether a relationship is mandatory or optional for each row, then choose where the foreign key belongs. A foreign key on the many-side is the common relational pattern for a one-to-many relationship: each order refers to one customer, while multiple orders can refer to that customer. The orders.customer_id example above expresses that structure; making it NOT NULL makes the association mandatory for each order.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

For a many-to-many relationship, represent the association as its own table with foreign keys to both related tables. A composite primary key or unique constraint on the two foreign-key columns prevents the same pair from appearing twice, as shown by group_memberships. If the association has its own attributes—such as a join date or role—they belong on that table.

For a one-to-one relationship, a foreign key alone does not ensure that each referenced row is used only once. Add a UNIQUE constraint to the referencing column (or make it the referencing table’s primary key) if the schema must prevent multiple rows from pointing to the same parent. Whether the reference is also mandatory depends on whether that row is required to have a parent.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use ON DELETE CASCADE?

Choose a foreign-key action according to the relationship’s meaning and data-retention needs; do not apply cascading deletion as a default. PostgreSQL supports actions including CASCADE, SET NULL, SET DEFAULT, RESTRICT, and NO ACTION. The constraint documentation describes their behavior and timing.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Action Effect Use when
CASCADE Deletes dependent rows when the referenced row is deleted; an update can likewise propagate a changed referenced key. The dependent row should share the referenced row’s lifecycle.
SET NULL Sets the referencing columns to null when the referenced row is deleted or updated. The relationship is optional and the referencing columns permit nulls.
SET DEFAULT Sets the referencing columns to their defaults when the referenced row is deleted or updated. The default is meaningful and satisfies the foreign-key requirement.
RESTRICT Blocks the referenced delete or update when it would affect the constraint. The operation must not proceed while dependent references exist.
NO ACTION Checks the constraint at its applicable check time; it is PostgreSQL’s default action. You want the default check behavior rather than automatic changes to dependent rows.

PostgreSQL distinguishes RESTRICT from NO ACTION in timing: NO ACTION can permit a statement’s resulting state to pass when the check is deferred, while RESTRICT prevents the operation immediately. The exact choice matters most when constraints are deferred or updates are involved.

CREATE TABLE order_lines (
    order_id bigint NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
    line_number integer NOT NULL,
    product_id bigint NOT NULL REFERENCES products(product_id),
    PRIMARY KEY (order_id, line_number)
);

This example makes order lines follow an order’s lifecycle. It does not cascade product deletion, because preserving the order line’s product reference may be important; the default restrictive behavior prevents deleting a referenced product until the reference is addressed.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Which constraints belong in the schema?

Constraints make the database reject invalid writes no matter which application or process attempts them. Use the constraint that matches the rule:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
  • NOT NULL: a value is required.
  • UNIQUE: a value, or combination of values, must not be duplicated.
  • FOREIGN KEY: a reference must point to an eligible row in another table.
  • CHECK: each inserted or updated row must satisfy a predicate.

For example, to prevent negative line-item quantities:

CREATE TABLE inventory_adjustments (
    adjustment_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    quantity_change integer NOT NULL CHECK (quantity_change <> 0)
);

Keep CHECK rules row-level

In PostgreSQL, a CHECK constraint is appropriate for a condition evaluated on the row being inserted or updated. Do not rely on it to enforce a rule involving other rows or tables: PostgreSQL warns that such a check cannot guarantee consistency when those other rows change. Use a suitable unique, exclusion, or foreign-key constraint for cross-row integrity where one fits. See the PostgreSQL 17 constraints documentation.

Do foreign keys create indexes?

In PostgreSQL, primary keys and unique constraints create unique B-tree indexes. PostgreSQL does not automatically create an index on the referencing foreign-key columns. An index on those columns can help joins and filters, and can make checks associated with deleting or updating a referenced row more efficient, but it also takes storage and adds work to writes.

Add such an index when table size, query patterns, parent-row maintenance, or observed query plans justify it—not automatically on every foreign key. For a frequently queried order list by customer, for example, an index may be useful:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
CREATE INDEX orders_customer_id_idx ON orders (customer_id);

PostgreSQL’s CREATE TABLE documentation covers constraint and index creation details. These index behaviors are PostgreSQL-specific; verify the defaults for the engine and version you use.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.