Skip to content

Commit 4fd7c79

Browse files
committed
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
1 parent d25997f commit 4fd7c79

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

doc/src/sgml/ddl.sgml

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -771,6 +771,11 @@ CREATE TABLE orders (
771771
referenced table is used as the referenced column(s).
772772
</para>
773773

774+
<para>
775+
You can assign your own name for a foreign key constraint,
776+
in the usual way.
777+
</para>
778+
774779
<para>
775780
A foreign key can also constrain and reference a group of columns.
776781
As usual, it then needs to be written in table constraint form.
@@ -787,9 +792,28 @@ CREATE TABLE t1 (
787792
match the number and type of the referenced columns.
788793
</para>
789794

795+
<indexterm>
796+
<primary>foreign key</primary>
797+
<secondary>self-referential</secondary>
798+
</indexterm>
799+
790800
<para>
791-
You can assign your own name for a foreign key constraint,
792-
in the usual way.
801+
Sometimes it is useful for the <quote>other table</quote> of a
802+
foreign key constraint to be the same table; this is called
803+
a <firstterm>self-referential</firstterm> foreign key. For
804+
example, if you want rows of a table to represent nodes of a tree
805+
structure, you could write
806+
<programlisting>
807+
CREATE TABLE tree (
808+
node_id integer PRIMARY KEY,
809+
parent_id integer REFERENCES tree,
810+
name text,
811+
...
812+
);
813+
</programlisting>
814+
A top-level node would have NULL <structfield>parent_id</structfield>,
815+
but non-NULL <structfield>parent_id</structfield> entries would be
816+
constrained to reference valid rows of the table.
793817
</para>
794818

795819
<para>

0 commit comments

Comments
 (0)