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

11.7. 式に対するインデックス #

<title>Indexes on Expressions</title>

An index column need not be just a column of the underlying table, but can be a function or scalar expression computed from one or more columns of the table. This feature is useful to obtain fast access to tables based on the results of computations. インデックス列は、基礎をなすテーブルにある列である必要はなく、そのテーブルの1つ以上の列から計算される関数やスカラ式とすることもできます。 この機能は、ある演算結果に基づいた高速テーブルアクセスを行う時に有用です。

For example, a common way to do case-insensitive comparisons is to use the <function>lower</function> function: 例えば、大文字小文字を区別せずに比較するための一般的な方法である、lower関数での使用例を以下に示します。

SELECT * FROM test1 WHERE lower(col1) = 'value';

This query can use an index if one has been defined on the result of the <literal>lower(col1)</literal> function: lower(col1)関数の結果にインデックスが定義されていれば、この問い合わせでインデックスを使用することができます。

CREATE INDEX test1_lower_col1_idx ON test1 (lower(col1));

If we were to declare this index <literal>UNIQUE</literal>, it would prevent creation of rows whose <literal>col1</literal> values differ only in case, as well as rows whose <literal>col1</literal> values are actually identical. Thus, indexes on expressions can be used to enforce constraints that are not definable as simple unique constraints. このインデックスをUNIQUEと宣言したとすると、col1の値が同一となる行だけでなく、col1の大文字小文字だけが違う行の生成を防ぐことになります。 したがって、式に対するインデックスを使用して、単なる一意性制約では定義できないような制約を強制することができます。

As another example, if one often does queries like: 別の例として、以下のような問い合わせが頻繁に行われる場合を考えます。

SELECT * FROM people WHERE (first_name || ' ' || last_name) = 'John Smith';

then it might be worth creating an index like this: この場合、以下のようなインデックスを作成する価値があるでしょう。

CREATE INDEX people_names ON people ((first_name || ' ' || last_name));

The syntax of the <command>CREATE INDEX</command> command normally requires writing parentheses around index expressions, as shown in the second example. The parentheses can be omitted when the expression is just a function call, as in the first example. 2番目の例に示すようにCREATE INDEXコマンドの構文は通常、インデックス式を括弧で括る必要があります。 最初の例のように、式が単なる関数呼び出しの場合には括弧を省略することができます。

Index expressions are relatively expensive to maintain, because the derived expression(s) must be computed for each row insertion and <link linkend="storage-hot">non-HOT update.</link> However, the index expressions are <emphasis>not</emphasis> recomputed during an indexed search, since they are already stored in the index. In both examples above, the system sees the query as just <literal>WHERE indexedcolumn = 'constant'</literal> and so the speed of the search is equivalent to any other simple index query. Thus, indexes on expressions are useful when retrieval speed is more important than insertion and update speed. 派生した式が、行挿入と非HOT更新の度に計算されなければなりませんので、インデックス式は相対的に見て維持が高価です。 しかし、インデックス式はインデックス内にすでに格納されているため、インデックスを使用する検索の間は再計算されません。 上の両方の例では、システムは問い合わせを単なるWHERE indexedcolumn = 'constant'と理解しますので、この検索速度は他の単純なインデックス問い合わせと同じです。 したがって、式に対するインデックスは取り出し速度が挿入、更新速度より重要な場合に有用です。