Adding constraints (FOREIGN KEY) to a table : FOREIGN KEY « Constraints « PostgreSQL






Adding constraints (FOREIGN KEY) to a table


postgres=#
postgres=#
postgres=# -- Creating the books table
postgres=#
postgres=# CREATE TABLE books (
postgres(#               id integer UNIQUE,
postgres(#               title text NOT NULL,
postgres(#               author_id  integer,
postgres(#               subject_id integer,
postgres(#               CONSTRAINT books_id_pkey PRIMARY KEY (id));
ERROR:  relation "books" already exists
postgres=#
postgres=# create table editions (
postgres(#              edition_id integer,
postgres(#              book_id    integer
postgres(#              );
CREATE TABLE
postgres=#
postgres=#
postgres=# -- Adding constraints to a table
postgres=#
postgres=# ALTER TABLE editions
postgres-#                  ADD CONSTRAINT foreign_book
postgres-#                  FOREIGN KEY (book_id) REFERENCES books (id);
ALTER TABLE
postgres=#
postgres=# drop table books cascade;
NOTICE:  drop cascades to constraint foreign_book on table editions
DROP TABLE
postgres=#
postgres=# drop table editions cascade;
DROP TABLE
postgres=#
           
       








Related examples in the same category

1.Define foreign key for a table
2.Reference two two columns as foreign key column
3.Adding a constraint to an existing table: add foreign key to table
4.Create FOREIGN KEY
5.Using foreign keys
6.ALTER TABLE employee ADD FOREIGN KEY (group_id) REFERENCES product_groups