1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
<Chapter Id="inherit">
<Title>Inheritance</Title>
<Para>
Let's create two classes. The capitals class contains
state capitals which are also cities. Naturally, the
capitals class should inherit from cities.
<ProgramListing>
CREATE TABLE cities (
name text,
population float,
altitude int -- (in ft)
);
CREATE TABLE capitals (
state char2
) INHERITS (cities);
</ProgramListing>
In this case, an instance of capitals <FirstTerm>inherits</FirstTerm> all
attributes (name, population, and altitude) from its
parent, cities. The type of the attribute name is
<Type>text</Type>, a native <ProductName>Postgres</ProductName> type for variable length
ASCII strings. The type of the attribute population is
<Type>float</Type>, a native <ProductName>Postgres</ProductName> type for double precision
floating point numbers. State capitals have an extra
attribute, state, that shows their state. In <ProductName>Postgres</ProductName>,
a class can inherit from zero or more other classes,
and a query can reference either all instances of a
class or all instances of a class plus all of its
descendants.
<Note>
<Para>
The inheritance hierarchy is a actually a directed acyclic graph.
</Para>
</Note>
For example, the following query finds
all the cities that are situated at an attitude of 500ft or higher:
<ProgramListing>
SELECT name, altitude
FROM cities
WHERE altitude > 500;
+----------+----------+
|name | altitude |
+----------+----------+
|Las Vegas | 2174 |
+----------+----------+
|Mariposa | 1953 |
+----------+----------+
</ProgramListing>
</para>
<Para>
On the other hand, to find the names of all cities,
including state capitals, that are located at an altitude
over 500ft, the query is:
<ProgramListing>
SELECT c.name, c.altitude
FROM cities* c
WHERE c.altitude > 500;
</ProgramListing>
which returns:
<ProgramListing>
+----------+----------+
|name | altitude |
+----------+----------+
|Las Vegas | 2174 |
+----------+----------+
|Mariposa | 1953 |
+----------+----------+
|Madison | 845 |
+----------+----------+
</ProgramListing>
Here the <Quote>*</Quote> after cities indicates that the query should
be run over cities and all classes below cities in the
inheritance hierarchy. Many of the commands that we
have already discussed -- <Command>select</Command>, <Command>update</Command> and <Command>delete</Command> --
support this <Quote>*</Quote> notation, as do others, like <Command>alter</Command>.
</Para>
</Chapter>
|