Skip to content

Instantly share code, notes, and snippets.

@designrubenz
Created February 15, 2019 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save designrubenz/e8126377797cac3ad7c36d011cda2384 to your computer and use it in GitHub Desktop.
Save designrubenz/e8126377797cac3ad7c36d011cda2384 to your computer and use it in GitHub Desktop.
Different ways of creating a foreign key (constraint) in postgresql

Different ways of creating a foreign key (constraint) in postgresql

Prerequisite

CREATE TABLE products (
    product_no integer PRIMARY KEY,
    name text,
    price numeric
);

1

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products (product_no),
    quantity integer
);

2: shortened

CREATE TABLE orders (
    order_id integer PRIMARY KEY,
    product_no integer REFERENCES products,
    quantity integer
);

3: group of columns

CREATE TABLE t1 (
  a integer PRIMARY KEY,
  b integer,
  c integer,
  FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
);

source: https://www.postgresql.org/docs/11/ddl-constraints.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment