バージョンごとのドキュメント一覧

5.3. 生成列 #

<title>Generated Columns</title>

A generated column is a special column that is always computed from other columns. Thus, it is for columns what a view is for tables. There are two kinds of generated columns: stored and virtual. A stored generated column is computed when it is written (inserted or updated) and occupies storage as if it were a normal column. A virtual generated column occupies no storage and is computed when it is read. Thus, a virtual generated column is similar to a view and a stored generated column is similar to a materialized view (except that it is always updated automatically). PostgreSQL currently implements only stored generated columns. 生成列は常に他の列から計算される特別な列です。 ですから、これは列におけるテーブルに対するビューのようなものです。 生成列には格納と仮想の2種類があります。 格納生成列はそれが書かれた(挿入または更新)時に計算され、あたかも通常の列のようにストレージが割り当てられます。 仮想列にはストレージは割り当てられず、列が読み出された時に計算されます。 つまり、仮想生成列はビューに似ており、格納生成列はマテリアライズドビューに似ています。(常に自動的に更新される点は除きます。) 今の所PostgreSQLは格納生成列のみを実装しています。

To create a generated column, use the <literal>GENERATED ALWAYS AS</literal> clause in <command>CREATE TABLE</command>, for example: 生成列を作るには、CREATE TABLEGENERATED ALWAYS AS節を使ってください。例を示します。

CREATE TABLE people (
    ...,
    height_cm numeric,
    height_in numeric GENERATED ALWAYS AS (height_cm / 2.54) STORED
);

The keyword <literal>STORED</literal> must be specified to choose the stored kind of generated column. See <xref linkend="sql-createtable"/> for more details. 種類を格納生成列として選択するためにキーワードSTOREDを選択する必要があります。 より詳しくはCREATE TABLEをご覧ください。

A generated column cannot be written to directly. In <command>INSERT</command> or <command>UPDATE</command> commands, a value cannot be specified for a generated column, but the keyword <literal>DEFAULT</literal> may be specified. 生成列には直接書き込みができません。 INSERTあるいはUPDATEコマンドでは値を生成列に指定できませんが、キーワードDEFAULTが指定できます。

Consider the differences between a column with a default and a generated column. The column default is evaluated once when the row is first inserted if no other value was provided; a generated column is updated whenever the row changes and cannot be overridden. A column default may not refer to other columns of the table; a generation expression would normally do so. A column default can use volatile functions, for example <literal>random()</literal> or functions referring to the current time; this is not allowed for generated columns. デフォルトを備えた列と生成列の違いを考えてみましょう。 列のデフォルトは、他に値が指定されないときに、最初に行が挿入された時に一度だけ評価されます。 生成列は、行が変更された時に常に更新され、上書きはできません。 デフォルトを備えた列はテーブルの他の列を参照することはできませんが、生成式は通常それを行います。 デフォルトを備えた列は揮発性の関数、たとえばrandom()や現在時刻を参照する関数を使用できますが、これは生成列では許されていません。

Several restrictions apply to the definition of generated columns and tables involving generated columns: 生成列の定義と生成列を伴うテーブルには以下の制限が適用されます。

Additional considerations apply to the use of generated columns. 生成列の利用の際には以下の追加の考慮が必要です。