PostgreSQL: Advanced SQL: Foreign keys

  • Referential integrity
  • Ensures applications/users interact with data in the intended way
  • Example: all entries in privileges must have a corresponding entry in 'users '
01 CREATE TABLE users (
02      usrid int,
03      name text,
04      primary key(usrid));
05
06 CREATE TABLE privileges (
07      usrid int REFERENCES users(usrid),
08      privl int,
09      primary key(usrid));
10

template1=# insert into privileges values(1);
ERROR:  insert or update on table "privileges" violates foreign key constraint "$1"
DETAIL:  Key (usrid)=(1) is not present in table "users".

Prev

Next

Page 31