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 3eeadc4

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 7c810bd commit 3eeadc4
Copy full SHA for 3eeadc4

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
@@ -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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.