Doc: add an example of a self-referential foreign key to ddl.sgml.
authorTom Lane
Fri, 30 Apr 2021 19:37:56 +0000 (15:37 -0400)
committerTom Lane
Fri, 30 Apr 2021 19:37:56 +0000 (15:37 -0400)
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

doc/src/sgml/ddl.sgml

index 7d587b226cbd1476dabaec2d0c60ff4a555bab5f..513112a216d96b6a293f712b453b3f94bf411858 100644 (file)
@@ -915,6 +915,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.
@@ -931,9 +936,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.