diff options
author | Tom Lane <tgl@sss.pgh.pa.us> | 2021-04-30 15:37:56 -0400 |
---|---|---|
committer | Tom Lane <tgl@sss.pgh.pa.us> | 2021-04-30 15:37:56 -0400 |
commit | 3eeadc425ccf30d5738bb1204adb2e50a8bea8c1 (patch) | |
tree | 361782fbe0dc4a4ad59496fe6dd9450632b7c5d3 | |
parent | 7c810bd028a7be3ce32beb438db072bd02592869 (diff) | |
download | postgresql-3eeadc425ccf30d5738bb1204adb2e50a8bea8c1.tar.gz postgresql-3eeadc425ccf30d5738bb1204adb2e50a8bea8c1.zip |
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
-rw-r--r-- | doc/src/sgml/ddl.sgml | 28 |
1 files changed, 26 insertions, 2 deletions
diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml index 23fa832742f..605027e8535 100644 --- a/doc/src/sgml/ddl.sgml +++ b/doc/src/sgml/ddl.sgml @@ -916,6 +916,11 @@ CREATE TABLE orders ( </para> <para> + You can assign your own name for a foreign key constraint, + in the usual way. + </para> + + <para> A foreign key can also constrain and reference a group of columns. As usual, it then needs to be written in table constraint form. Here is a contrived syntax example: @@ -931,9 +936,28 @@ CREATE TABLE t1 ( match the number and type of the referenced columns. </para> + <indexterm> + <primary>foreign key</primary> + <secondary>self-referential</secondary> + </indexterm> + <para> - You can assign your own name for a foreign key constraint, - in the usual way. + Sometimes it is useful for the <quote>other table</quote> of a + foreign key constraint to be the same table; this is called + a <firstterm>self-referential</firstterm> foreign key. For + example, if you want rows of a table to represent nodes of a tree + structure, you could write +<programlisting> +CREATE TABLE tree ( + node_id integer PRIMARY KEY, + parent_id integer REFERENCES tree, + name text, + ... +); +</programlisting> + A top-level node would have NULL <structfield>parent_id</structfield>, + but non-NULL <structfield>parent_id</structfield> entries would be + constrained to reference valid rows of the table. </para> <para> |