]> begriffs open source - ai-pg/blob - full-docs/txt/tutorial-fk.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / tutorial-fk.txt
1
2 3.3. Foreign Keys #
3
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.
13
14    The new declaration of the tables would look like this:
15 CREATE TABLE cities (
16         name     varchar(80) primary key,
17         location point
18 );
19
20 CREATE TABLE weather (
21         city      varchar(80) references cities(name),
22         temp_lo   int,
23         temp_hi   int,
24         prcp      real,
25         date      date
26 );
27
28    Now try inserting an invalid record:
29 INSERT INTO weather VALUES ('Berkeley', 45, 53, 0.0, '1994-11-28');
30
31 ERROR:  insert or update on table "weather" violates foreign key constraint "wea
32 ther_city_fkey"
33 DETAIL:  Key (city)=(Berkeley) is not present in table "cities".
34
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.