4 Recall the weather and cities tables from Chapter 2. Consider the
5 following problem: You want to make sure that no one can insert rows in
6 the weather table that do not have a matching entry in the cities
7 table. This is called maintaining the referential integrity of your
8 data. In simplistic database systems this would be implemented (if at
9 all) by first looking at the cities table to check if a matching record
10 exists, and then inserting or rejecting the new weather records. This
11 approach has a number of problems and is very inconvenient, so
12 PostgreSQL can do this for you.
14 The new declaration of the tables would look like this:
16 name varchar(80) primary key,
20 CREATE TABLE weather (
21 city varchar(80) references cities(name),
28 Now try inserting an invalid record:
29 INSERT INTO weather VALUES ('Berkeley', 45, 53, 0.0, '1994-11-28');
31 ERROR: insert or update on table "weather" violates foreign key constraint "wea
33 DETAIL: Key (city)=(Berkeley) is not present in table "cities".
35 The behavior of foreign keys can be finely tuned to your application.
36 We will not go beyond this simple example in this tutorial, but just
37 refer you to Chapter 5 for more information. Making correct use of
38 foreign keys will definitely improve the quality of your database
39 applications, so you are strongly encouraged to learn about them.