Skip to content

Instantly share code, notes, and snippets.

@dmitry-vsl
Created October 9, 2015 15:24
Show Gist options
  • Save dmitry-vsl/0a68b1fbf697abb87e5b to your computer and use it in GitHub Desktop.
Save dmitry-vsl/0a68b1fbf697abb87e5b to your computer and use it in GitHub Desktop.
Circular FK constraints in postgresql
-- Three tables: books, authors, authorship
-- Every book must have an author, enforce this constraint at schema level
drop table if exists book cascade;
drop table if exists author cascade;
drop table if exists authorship cascade;
create table book(id serial not null primary key);
create table author(id serial not null primary key);
create table authorship(
book_id integer not null unique references book(id),
author_id integer not null references author(id),
primary key (book_id, author_id)
);
alter table book
add constraint book_must_have_author
foreign key (id) references authorship(book_id) initially deferred;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment