4 Inheritance is a concept from object-oriented databases. It opens up
5 interesting new possibilities of database design.
7 Let's create two tables: A table cities and a table capitals.
8 Naturally, capitals are also cities, so you want some way to show the
9 capitals implicitly when you list all cities. If you're really clever
10 you might invent some scheme like this:
11 CREATE TABLE capitals (
14 elevation int, -- (in ft)
18 CREATE TABLE non_capitals (
21 elevation int -- (in ft)
25 SELECT name, population, elevation FROM capitals
27 SELECT name, population, elevation FROM non_capitals;
29 This works OK as far as querying goes, but it gets ugly when you need
30 to update several rows, for one thing.
32 A better solution is this:
36 elevation int -- (in ft)
39 CREATE TABLE capitals (
40 state char(2) UNIQUE NOT NULL
43 In this case, a row of capitals inherits all columns (name, population,
44 and elevation) from its parent, cities. The type of the column name is
45 text, a native PostgreSQL type for variable length character strings.
46 The capitals table has an additional column, state, which shows its
47 state abbreviation. In PostgreSQL, a table can inherit from zero or
50 For example, the following query finds the names of all cities,
51 including state capitals, that are located at an elevation over 500
53 SELECT name, elevation
55 WHERE elevation > 500;
59 -----------+-----------
65 On the other hand, the following query finds all the cities that are
66 not state capitals and are situated at an elevation over 500 feet:
67 SELECT name, elevation
69 WHERE elevation > 500;
72 -----------+-----------
77 Here the ONLY before cities indicates that the query should be run over
78 only the cities table, and not tables below cities in the inheritance
79 hierarchy. Many of the commands that we have already discussed —
80 SELECT, UPDATE, and DELETE — support this ONLY notation.
84 Although inheritance is frequently useful, it has not been integrated
85 with unique constraints or foreign keys, which limits its usefulness.
86 See Section 5.11 for more detail.