Movatterモバイル変換


[0]ホーム

URL:



Facebook
Postgres Pro
Facebook
Downloads

5.8. Inheritance

PostgreSQL implements table inheritance, which can be a useful tool for database designers. (SQL:1999 and later define a type inheritance feature, which differs in many respects from the features described here.)

Let's start with an example: suppose we are trying to build a data model for cities. Each state has many cities, but only one capital. We want to be able to quickly retrieve the capital city for any particular state. This can be done by creating two tables, one for state capitals and one for cities that are not capitals. However, what happens when we want to ask for data about a city, regardless of whether it is a capital or not? The inheritance feature can help to resolve this problem. We define thecapitals table so that it inherits fromcities:

CREATE TABLE cities (    name            text,    population      float,    altitude        int     -- in feet);CREATE TABLE capitals (    state           char(2)) INHERITS (cities);

In this case, thecapitals tableinherits all the columns of its parent table,cities. State capitals also have an extra column,state, that shows their state.

InPostgreSQL, 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 descendant tables. The latter behavior is the default. For example, the following query finds the names of all cities, including state capitals, that are located at an altitude over 500 feet:

SELECT name, altitude    FROM cities    WHERE altitude > 500;

Given the sample data from thePostgreSQL tutorial (seeSection 2.1), this 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 500 feet:

SELECT name, altitude    FROM ONLY cities    WHERE altitude > 500;   name    | altitude-----------+---------- Las Vegas |     2174 Mariposa  |     1953

Here theONLY keyword indicates that the query should apply only tocities, and not any tables belowcities in the inheritance hierarchy. Many of the commands that we have already discussed —SELECT,UPDATE andDELETE — support theONLY keyword.

You can also write the table name with a trailing* to explicitly specify that descendant tables are included:

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

Writing* is not necessary, since this behavior is the default (unless you have changed the setting of thesql_inheritance configuration option). However writing* might be useful to emphasize that additional tables will be searched.

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

SELECT c.tableoid, c.name, c.altitudeFROM cities cWHERE 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 withpg_class you can see the actual table names:

SELECT p.relname, c.name, c.altitudeFROM cities c, pg_class pWHERE c.altitude > 500 AND c.tableoid = p.oid;

which returns:

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

Inheritance does not automatically propagate data fromINSERT orCOPY commands to other tables in the inheritance hierarchy. In our example, the followingINSERT statement will fail:

INSERT INTO cities (name, population, altitude, state)VALUES ('New York', NULL, NULL, 'NY');

We might hope that the data would somehow be routed to thecapitals table, but this does not happen:INSERT always inserts into exactly the table specified. In some cases it is possible to redirect the insertion using a rule (seeChapter 38). However that does not help for the above case because thecities table does not contain the columnstate, and so the command will be rejected before the rule can be applied.

All check constraints and not-null constraints on a parent table are automatically inherited by its children. Other types of constraints (unique, primary key, and foreign key constraints) are not inherited.

A table can inherit from more than one parent table, in which case it has the union of the columns defined by the parent tables. Any columns declared in the child table's definition are added to these. If the same column name appears in multiple parent tables, or in both a parent table and the child's definition, then these columns are"merged" so that there is only one such column in the child table. To be merged, columns must have the same data types, else an error is raised. The merged column will have copies of all the check constraints coming from any one of the column definitions it came from, and will be marked not-null if any of them are.

Table inheritance is typically established when the child table is created, using theINHERITS clause of theCREATE TABLE statement. Alternatively, a table which is already defined in a compatible way can have a new parent relationship added, using theINHERIT variant ofALTER TABLE. To do this the new child table must already include columns with the same names and types as the columns of the parent. It must also include check constraints with the same names and check expressions as those of the parent. Similarly an inheritance link can be removed from a child using theNO INHERIT variant ofALTER TABLE. Dynamically adding and removing inheritance links like this can be useful when the inheritance relationship is being used for table partitioning (seeSection 5.9).

One convenient way to create a compatible table that will later be made a new child is to use theLIKE clause inCREATE TABLE. This creates a new table with the same columns as the source table. If there are anyCHECK constraints defined on the source table, theINCLUDING CONSTRAINTS option toLIKE should be specified, as the new child must have constraints matching the parent to be considered compatible.

A parent table cannot be dropped while any of its children remain. Neither can columns or check constraints of child tables be dropped or altered if they are inherited from any parent tables. If you wish to remove a table and all of its descendants, one easy way is to drop the parent table with theCASCADE option.

ALTER TABLE will propagate any changes in column data definitions and check constraints down the inheritance hierarchy. Again, dropping columns that are depended on by other tables is only possible when using theCASCADE option.ALTER TABLE follows the same rules for duplicate column merging and rejection that apply duringCREATE TABLE.

Note how table access permissions are handled. Querying a parent table can automatically access data in child tables without further access privilege checking. This preserves the appearance that the data is (also) in the parent table. Accessing the child tables directly is, however, not automatically allowed and would require further privileges to be granted.

5.8.1. Caveats

Note that not all SQL commands are able to work on inheritance hierarchies. Commands that are used for data querying, data modification, or schema modification (e.g.,SELECT,UPDATE,DELETE, most variants ofALTER TABLE, but notINSERT orALTER TABLE ... RENAME) typically default to including child tables and support theONLY notation to exclude them. Commands that do database maintenance and tuning (e.g.,REINDEX,VACUUM) typically only work on individual, physical tables and do not support recursing over inheritance hierarchies. The respective behavior of each individual command is documented in its reference page (Reference I,SQL Commands).

A serious 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. This is true on both the referencing and referenced sides of a foreign key constraint. Thus, in the terms of the above example:

  • If we declaredcities.name to beUNIQUE or aPRIMARY KEY, this would not stop thecapitals table from having rows with names duplicating rows incities. And those duplicate rows would by default show up in queries fromcities. In fact, by defaultcapitals would have no unique constraint at all, and so could contain multiple rows with the same name. You could add a unique constraint tocapitals, but this would not prevent duplication compared tocities.

  • Similarly, if we were to specify thatcities.nameREFERENCES some other table, this constraint would not automatically propagate tocapitals. In this case you could work around it by manually adding the sameREFERENCES constraint tocapitals.

  • Specifying that another table's columnREFERENCES cities(name) would allow the other table to contain city names, but not capital names. There is no good workaround for this case.

These deficiencies will probably be fixed in some future release, but in the meantime considerable care is needed in deciding whether inheritance is useful for your application.


PrevHomeNext
SchemasUpPartitioning
Go to PostgreSQL 9.4
By continuing to browse this website, you agree to the use of cookies. Go toPrivacy Policy.

[8]ページ先頭

©2009-2025 Movatter.jp