Created
October 9, 2015 15:24
-
-
Save dmitry-vsl/0a68b1fbf697abb87e5b to your computer and use it in GitHub Desktop.
Circular FK constraints in postgresql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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