Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 8f65db5

Browse filesBrowse 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 2033d10 commit 8f65db5
Copy full SHA for 8f65db5

File tree

Expand file treeCollapse file tree

1 file changed

+26
-2
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+26
-2
lines changed

‎doc/src/sgml/ddl.sgml

Copy file name to clipboardExpand all lines: doc/src/sgml/ddl.sgml
+26-2Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,11 @@ CREATE TABLE orders (
770770
referenced table is used as the referenced column(s).
771771
</para>
772772

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

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

794818
<para>

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.