@@ -771,6 +771,11 @@ CREATE TABLE orders (
771
771
referenced table is used as the referenced column(s).
772
772
</para>
773
773
774
+ <para>
775
+ You can assign your own name for a foreign key constraint,
776
+ in the usual way.
777
+ </para>
778
+
774
779
<para>
775
780
A foreign key can also constrain and reference a group of columns.
776
781
As usual, it then needs to be written in table constraint form.
@@ -787,9 +792,28 @@ CREATE TABLE t1 (
787
792
match the number and type of the referenced columns.
788
793
</para>
789
794
795
+ <indexterm>
796
+ <primary>foreign key</primary>
797
+ <secondary>self-referential</secondary>
798
+ </indexterm>
799
+
790
800
<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.
793
817
</para>
794
818
795
819
<para>
0 commit comments