This page in other versions: 9.0 / 9.1 / 9.2 / 9.3  |  Development versions: devel / 9.4  |  Unsupported versions: 7.3 / 7.4 / 8.0 / 8.1 / 8.2 / 8.3 / 8.4

5.5. Inheritance

Let's create two tables. The capitals table contains state capitals which are also cities. Naturally, the capitals table should inherit from cities.

CREATE TABLE cities (
    name            text,
    population      float,
    altitude        int     -- (in ft)
);

CREATE TABLE capitals (
    state           char(2)
) INHERITS (cities);

In this case, a row of capitals inherits all attributes (name, population, and altitude) from its parent, cities. The type of the attribute name is text, a native PostgreSQL type for variable length character strings. The type of the attribute population is float, a native PostgreSQL type for double precision floating-point numbers. State capitals have an extra attribute, state, that shows their state. In PostgreSQL, a table can inherit from zero or more other tables, and a query can reference either all rows of a table or all rows of a table plus all of its descendants.

Note: The inheritance hierarchy is actually a directed acyclic graph.

For example, the following query finds the names of all cities, including state capitals, that are located at an altitude over 500ft:

SELECT name, altitude
    FROM cities
    WHERE altitude > 500;

which returns:

   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953
 Madison   |      845

On the other hand, the following query finds all the cities that are not state capitals and are situated at an altitude over 500ft:

SELECT name, altitude
    FROM ONLY cities
    WHERE altitude > 500;

   name    | altitude
-----------+----------
 Las Vegas |     2174
 Mariposa  |     1953

Here the "ONLY" before cities indicates that the query should be run over only cities and not tables below cities in the inheritance hierarchy. Many of the commands that we have already discussed -- SELECT, UPDATE and DELETE -- support this "ONLY" notation.

In some cases you may wish to know which table a particular row originated from. There is a system column called TABLEOID in each table which can tell you the originating table:

SELECT c.tableoid, c.name, c.altitude
FROM cities c
WHERE c.altitude > 500;

which returns:

 tableoid |   name    | altitude
----------+-----------+----------
   139793 | Las Vegas |     2174
   139793 | Mariposa  |     1953
   139798 | Madison   |      845

(If you try to reproduce this example, you will probably get different numeric OIDs.) By doing a join with pg_class you can see the actual table names:

SELECT p.relname, c.name, c.altitude
FROM cities c, pg_class p
WHERE c.altitude > 500 and c.tableoid = p.oid;

which returns:

 relname  |   name    | altitude
----------+-----------+----------
 cities   | Las Vegas |     2174
 cities   | Mariposa  |     1953
 capitals | Madison   |      845

Deprecated: In previous versions of PostgreSQL, the default behavior was not to include child tables in queries. This was found to be error prone and is also in violation of the SQL99 standard. Under the old syntax, to get the sub-tables you append * to the table name. For example

SELECT * from cities*;

You can still explicitly specify scanning child tables by appending *, as well as explicitly specify not scanning child tables by writing "ONLY". But beginning in version 7.1, the default behavior for an undecorated table name is to scan its child tables too, whereas before the default was not to do so. To get the old default behavior, set the configuration option SQL_Inheritance to off, e.g.,

SET SQL_Inheritance TO OFF;

or add a line in your postgresql.conf file.

A limitation of the inheritance feature is that indexes (including unique constraints) and foreign key constraints only apply to single tables, not to their inheritance children. Thus, in the above example, specifying that another table's column REFERENCES cities(name) would allow the other table to contain city names but not capital names. This deficiency will probably be fixed in some future release.

Comments


Sept. 16, 2004, 2:20 p.m.

To second \"Fra. 219\", inheriting referential integrity contraints would be a nice feature, the same goes for primary key indices (It\'s possibly to insert a duplicate \"primary key\" into an inherited table, when the primary key was inherited from a supertable).

But there is a simple, but ugly, work-around:

CREATE TABLE super ( id serial primary key, ref int references main);
CREATE TABLE sub ( value text, primary key(id), foreign key(ref) references main) INHERITS(super);


Dec. 29, 2004, 3:05 p.m.

This example for inheritance is not very good, in my humble opinion - it would be easier to add a boolean toggle in the cities table to indicate if it is or not a capital. A much better example, in my opinion, is this :

CREATE TABLE baseinfo (
name text,
address text,
zipcode text
);

CREATE TABLE regularclient (
client_id char(25)
) INHERITS (baseinfo);

CREATE TABLE supplierclient (
supplier_id char(25)
) INHERITS (baseinfo);


Jan. 13, 2005, 12:40 p.m.

Replicating PRIMARY KEY in child tables allows only referencing 'em from other tables. It doesn't solve the "duplicated primary key" problem in the parent table. The only way I could find is adding :
CREATE OR REPLACE FUNCTION base_notexists(integer)
RETURNS boolean
STABLE
LANGUAGE 'SQL'
AS 'SELECT NOT EXISTS(SELECT id FROM base WHERE id=$1)';
and the constraint
CHECK (base_notexists(id))

If only it could be possible to reference an already existing index...


April 18, 2006, 4:10 p.m.

if a boolean were added to cities to indicate that it is a capital, you then don't know the state. You could add a state column (you might want that anyhow) but a nice thing with the example is that you could also enforce that there is only one capital per state.

the example is OK to make the point though.

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group