すべてのプロダクト
Search
ドキュメントセンター

AnalyticDB:生成された列

最終更新日:Sep 29, 2024

AnalyticDB for PostgreSQL V7.0は、生成された列機能をサポートしています。 生成された列は、別の列の値に基づいて定義できます。 INSERTまたはUPDATEを使用して、生成された列にデータを直接書き込むことはできません。 1つ以上の元の列にデータが書き込まれると、式の自動計算結果が生成された列に書き込まれます。

構文

GENERATED ALWAYS AS ( generation_expr ) STORED

パラメーター

パラメーター

説明

generation_expr

参照する元の列。

説明
  • 元の列には、不変型の関数と操作のみを含めることができます。

  • 元の列は、現在のテーブルの生成されていない列である必要があります。

保存

生成された列のデータをディスクに格納するように指定します。 STOREDを指定する必要があります。

例:

  1. t1という名前のテストテーブルを作成します。

    CREATE TABLE t1 (stuid int4, chinese int2, math int2, sum_score int2 GENERATED ALWAYS AS (chinese+math) STORED ) distributed by (stuid);
  2. t1テーブルのスキーマを照会します。

    psqlで \d t1コマンドを実行して、テーブルスキーマを照会します。 次の情報が返されます:

    Table "public.t1"
      Column   |   Type   | Collation | Nullable |                   Default
    -----------+----------+-----------+----------+---------------------------------------------
     stuid     | integer  |           |          |
     chinese   | smallint |           |          |
     math      | smallint |           |          |
     sum_score | smallint |           |          | generated always as (chinese + math) stored
    Distributed by: (stuid)
  3. t1テーブルにデータを挿入します。

    INSERT INTO t1(stuid,chinese,math) VALUES(1, 90, 95);
  4. t1テーブルのクエリデータをします。

    SELECT * FROM t1;

    次の情報が返されます:

    stuid | chinese | math | sum_score
    -------+---------+------+-----------
         1 |      90 |   95 |       185
    (1 row)
  5. 生成された列に直接データを書き込みます。

    INSERT INTO t1 (stuid, chinese, math, sum_score) VALUES(1,80,70,100);

    次のエラーメッセージが返されます。 生成された列にデータを直接書き込むことはできません。

    ERROR:  cannot insert into column "sum_score"
    DETAIL:  Column "sum_score" is a generated column

    です

  6. 生成された列にインデックスを作成します。

    CREATE INDEX ON t1 USING BTREE(sum_score);                              
  7. t1テーブルのスキーマを照会します。

    psqlで \d t1コマンドを実行して、テーブルスキーマを照会します。 次の情報が返されます。 生成された列にインデックスが作成されます。

     Table "public.t1"
      Column   |   Type   | Collation | Nullable |                   Default
    -----------+----------+-----------+----------+---------------------------------------------
     stuid     | integer  |           |          |
     chinese   | smallint |           |          |
     math      | smallint |           |          |
     sum_score | smallint |           |          | generated always as (chinese + math) stored
    Indexes:
        "t1_sum_score_idx" btree (sum_score)
    Distributed by: (stuid)