From: Tom Lane Date: Fri, 30 Apr 2021 19:37:57 +0000 (-0400) Subject: Doc: add an example of a self-referential foreign key to ddl.sgml. X-Git-Tag: REL_10_17~8 X-Git-Url: http://git.postgresql.org/gitweb/?a=commitdiff_plain;h=7dcec3ed45d5a128fcc8bce23b9a2879fc520aa0;p=postgresql.git Doc: add an example of a self-referential foreign key to ddl.sgml. While we've always allowed such cases, the documentation didn't say you could do it. Discussion: https://postgr.es/m/161969805833.690.13680986983883602407@wrigleys.postgresql.org --- diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index be9e75832ce..6cb179728d7 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -771,6 +771,11 @@ CREATE TABLE orders ( referenced table is used as the referenced column(s). + + You can assign your own name for a foreign key constraint, + in the usual way. + + A foreign key can also constrain and reference a group of columns. As usual, it then needs to be written in table constraint form. @@ -787,9 +792,28 @@ CREATE TABLE t1 ( match the number and type of the referenced columns. + + foreign key + self-referential + + - You can assign your own name for a foreign key constraint, - in the usual way. + Sometimes it is useful for the other table of a + foreign key constraint to be the same table; this is called + a self-referential foreign key. For + example, if you want rows of a table to represent nodes of a tree + structure, you could write + +CREATE TABLE tree ( + node_id integer PRIMARY KEY, + parent_id integer REFERENCES tree, + name text, + ... +); + + A top-level node would have NULL parent_id, + but non-NULL parent_id entries would be + constrained to reference valid rows of the table.