Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e6f9539

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 386e64e commit e6f9539

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

doc/src/sgml/ddl.sgml

+26-2
Original file line numberDiff line numberDiff line change
@@ -915,6 +915,11 @@ CREATE TABLE orders (
915915
referenced table is used as the referenced column(s).
916916
</para>
917917

918+
<para>
919+
You can assign your own name for a foreign key constraint,
920+
in the usual way.
921+
</para>
922+
918923
<para>
919924
A foreign key can also constrain and reference a group of columns.
920925
As usual, it then needs to be written in table constraint form.
@@ -931,9 +936,28 @@ CREATE TABLE t1 (
931936
match the number and type of the referenced columns.
932937
</para>
933938

939+
<indexterm>
940+
<primary>foreign key</primary>
941+
<secondary>self-referential</secondary>
942+
</indexterm>
943+
934944
<para>
935-
You can assign your own name for a foreign key constraint,
936-
in the usual way.
945+
Sometimes it is useful for the <quote>other table</quote> of a
946+
foreign key constraint to be the same table; this is called
947+
a <firstterm>self-referential</firstterm> foreign key. For
948+
example, if you want rows of a table to represent nodes of a tree
949+
structure, you could write
950+
<programlisting>
951+
CREATE TABLE tree (
952+
node_id integer PRIMARY KEY,
953+
parent_id integer REFERENCES tree,
954+
name text,
955+
...
956+
);
957+
</programlisting>
958+
A top-level node would have NULL <structfield>parent_id</structfield>,
959+
but non-NULL <structfield>parent_id</structfield> entries would be
960+
constrained to reference valid rows of the table.
937961
</para>
938962

939963
<para>

0 commit comments

Comments
 (0)