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

4.2. 評価式 #

<title>Value Expressions</title>

Value expressions are used in a variety of contexts, such as in the target list of the <command>SELECT</command> command, as new column values in <command>INSERT</command> or <command>UPDATE</command>, or in search conditions in a number of commands. The result of a value expression is sometimes called a <firstterm>scalar</firstterm>, to distinguish it from the result of a table expression (which is a table). Value expressions are therefore also called <firstterm>scalar expressions</firstterm> (or even simply <firstterm>expressions</firstterm>). The expression syntax allows the calculation of values from primitive parts using arithmetic, logical, set, and other operations. 評価式は、例えばSELECTコマンドの目的リストとして、INSERTUPDATEの新しい列の値として、もしくはいくつかのコマンドの検索条件として様々な文脈の中で使われます。 評価式の結果は、テーブル式の結果(つまりテーブル)から区別するために、スカラと呼ばれることもあります。 したがって、評価式はスカラ式(またはもっと簡単に)とも呼ばれます。 式の構文によって、基本的な部分から算術、論理、集合などの演算を使って値の計算を行うことができます。

A value expression is one of the following: 評価式は下記のうちのいずれかです。

In addition to this list, there are a number of constructs that can be classified as an expression but do not follow any general syntax rules. These generally have the semantics of a function or operator and are explained in the appropriate location in <xref linkend="functions"/>. An example is the <literal>IS NULL</literal> clause. これ以外にも、式として分類されるけれども一般的な構文規約には従わない、いくつかの構成要素があります。 これらは一般的に関数あるいは演算子の意味を持ちます。 第9章の該当部分で説明されています。 例を挙げるとIS NULL句があります。

We have already discussed constants in <xref linkend="sql-syntax-constants"/>. The following sections discuss the remaining options. 4.1.2で既に定数については説明しました。 続く節では残りのオプションについて説明します。

4.2.1. 列の参照 #

<title>Column References</title>

A column can be referenced in the form: 列は、下記のような形式で参照できます。

correlation.columnname

<replaceable>correlation</replaceable> is the name of a table (possibly qualified with a schema name), or an alias for a table defined by means of a <literal>FROM</literal> clause. The correlation name and separating dot can be omitted if the column name is unique across all the tables being used in the current query. (See also <xref linkend="queries"/>.) correlationは、テーブル名(スキーマで修飾されている場合もあります)、あるいはFROM句で定義されたテーブルの別名です。 correlationの名前と区切り用のドットは、もし列名が現在の問い合わせで使われる全てのテーブルを通して一意である場合は省略できます。 (第7章も参照してください)。

4.2.2. 位置パラメータ #

<title>Positional Parameters</title>

A positional parameter reference is used to indicate a value that is supplied externally to an SQL statement. Parameters are used in SQL function definitions and in prepared queries. Some client libraries also support specifying data values separately from the SQL command string, in which case parameters are used to refer to the out-of-line data values. The form of a parameter reference is: 位置パラメータ参照は、外部からSQL文に渡される値を示すために使用されます。 パラメータはSQL関数定義およびプリペアド問い合わせの中で使用されます。 また、クライアントライブラリの中には、SQLコマンド文字列とデータ値を分離して指定できる機能をサポートするものもあります。 この場合、パラメータは行外データ値を参照するために使用されます。 パラメータ参照の形式は以下のとおりです。

$number

For example, consider the definition of a function, <function>dept</function>, as: 例えば、関数 dept の定義が以下のようにされたとします。

CREATE FUNCTION dept(text) RETURNS dept
    AS $$ SELECT * FROM dept WHERE name = $1 $$
    LANGUAGE SQL;

Here the <literal>$1</literal> references the value of the first function argument whenever the function is invoked. ここで$1は関数が呼び出される時に最初の関数引数の値を参照します。

4.2.3. 添字 #

<title>Subscripts</title>

If an expression yields a value of an array type, then a specific element of the array value can be extracted by writing 式が配列型の値となる場合、配列値の特定要素は以下のように記述することで抽出できます。

expression[subscript]

or multiple adjacent elements (an <quote>array slice</quote>) can be extracted by writing また、隣接する複数の要素(配列の一部分)は以下のように記述することで抽出できます。

expression[lower_subscript:upper_subscript]

(Here, the brackets <literal>[ ]</literal> are meant to appear literally.) Each <replaceable>subscript</replaceable> is itself an expression, which will be rounded to the nearest integer value. (ここで大括弧[ ]は文字通りに記述してください(訳注:これはオプション部分を表す大括弧ではありません)。) 各subscriptはそれ自体が式であり、最も近い整数値へと丸められます。

In general the array <replaceable>expression</replaceable> must be parenthesized, but the parentheses can be omitted when the expression to be subscripted is just a column reference or positional parameter. Also, multiple subscripts can be concatenated when the original array is multidimensional. For example: 一般的には、配列expressionは括弧で括らなければなりませんが、添字を付けるそのexpressionが単なる列参照や位置パラメータであった場合、その括弧を省略できます。 また、元の配列が多次元の場合は複数の添字を連結できます。 以下に例を示します。

mytable.arraycolumn[4]
mytable.two_d_column[17][34]
$1[10:42]
(arrayfunction(a,b))[42]

The parentheses in the last example are required. See <xref linkend="arrays"/> for more about arrays. 最後の例では括弧が必要です。 配列の詳細は8.15を参照してください。

4.2.4. フィールド選択 #

<title>Field Selection</title>

If an expression yields a value of a composite type (row type), then a specific field of the row can be extracted by writing 式が複合型(行型)の値を生成する場合、行の特定のフィールドは以下のように記述することで抽出できます。

expression.fieldname

In general the row <replaceable>expression</replaceable> must be parenthesized, but the parentheses can be omitted when the expression to be selected from is just a table reference or positional parameter. For example: 一般的には、行expressionは括弧で括らなければなりません。 しかし、選択元となる式が単なるテーブル参照や位置パラメータの場合、括弧を省略できます。 以下に例を示します。

mytable.mycolumn
$1.somecolumn
(rowfunction(a,b)).col3

(Thus, a qualified column reference is actually just a special case of the field selection syntax.) An important special case is extracting a field from a table column that is of a composite type: (したがって、修飾された列参照は実際のところ、単なるこのフィールド選択構文の特殊な場合です。) 重要となる特殊な場合としては、複合型のテーブル列からフィールドを抽出するときです。

(compositecol).somefield
(mytable.compositecol).somefield

The parentheses are required here to show that <structfield>compositecol</structfield> is a column name not a table name, or that <structname>mytable</structname> is a table name not a schema name in the second case. compositecolがテーブル名でなく列名であること、または2番目の場合のmytableがスキーマ名でなくテーブル名であることを示すため丸括弧が要求されます。

You can ask for all fields of a composite value by writing <literal>.*</literal>: .*を記述することで、複合型の全ての値を問い合わせることが可能です。

(compositecol).*

This notation behaves differently depending on context; see <xref linkend="rowtypes-usage"/> for details. この表記はコンテキストに依存して異なった振る舞いをします。詳細は8.16.5を参照してください。

4.2.5. 演算子の呼び出し #

<title>Operator Invocations</title>

There are two possible syntaxes for an operator invocation: 演算子の呼び出しには以下の2構文が可能です。

expression operator expression (二項中置演算子)
operator expression (単項前置演算子)

where the <replaceable>operator</replaceable> token follows the syntax rules of <xref linkend="sql-syntax-operators"/>, or is one of the key words <token>AND</token>, <token>OR</token>, and <token>NOT</token>, or is a qualified operator name in the form: ここでoperatorトークンは、4.1.3構文規則に従うもの、もしくはキーワードANDORNOTのいずれか、または以下の形式の修飾された演算子名です。

OPERATOR(schema.operatorname)

Which particular operators exist and whether they are unary or binary depends on what operators have been defined by the system or the user. <xref linkend="functions"/> describes the built-in operators. 具体的にどんな演算子が存在し、それが単項か二項かどうかは、システムやユーザによってどんな演算子が定義されたかに依存します。 第9章にて、組み込み演算子について説明します。

4.2.6. 関数呼び出し #

<title>Function Calls</title>

The syntax for a function call is the name of a function (possibly qualified with a schema name), followed by its argument list enclosed in parentheses: 関数呼び出しの構文は、関数名(スキーマ名で修飾されている場合があります)に続けてその引数を丸括弧で囲んで列挙したものです。

function_name ([expression [, expression ... ]] )

For example, the following computes the square root of 2: 例えば、以下のものは2の平方根を計算します。

sqrt(2)

The list of built-in functions is in <xref linkend="functions"/>. Other functions can be added by the user. 組み込み関数の一覧は第9章にあります。 他の関数はユーザが追加できます。

When issuing queries in a database where some users mistrust other users, observe security precautions from <xref linkend="typeconv-func"/> when writing function calls. あるユーザが他のユーザを信用しないデータベースで問い合わせを発行する場合には、関数呼び出しを書く時に10.3のセキュリティの事前の対策を守ってください。

The arguments can optionally have names attached. See <xref linkend="sql-syntax-calling-funcs"/> for details. 引数には名前を任意で付与できます。詳細は4.3を見てください。

注記

A function that takes a single argument of composite type can optionally be called using field-selection syntax, and conversely field selection can be written in functional style. That is, the notations <literal>col(table)</literal> and <literal>table.col</literal> are interchangeable. This behavior is not SQL-standard but is provided in <productname>PostgreSQL</productname> because it allows use of functions to emulate <quote>computed fields</quote>. For more information see <xref linkend="rowtypes-usage"/>. 複合型の単一引数をとる関数はフィールド選択の構文を使っても呼び出すことができます。 反対にフィールド選択を関数形式で記述することもできます。 つまり、col(table)table.colのどちらを使っても良いということです。 この動作は標準SQLにはありませんが、PostgreSQLでは、これにより計算されたフィールドのエミュレートをする関数の利用が可能になるため、提供しています。 詳しくは8.16.5を参照してください。

4.2.7. 集約式 #

<title>Aggregate Expressions</title>

An <firstterm>aggregate expression</firstterm> represents the application of an aggregate function across the rows selected by a query. An aggregate function reduces multiple inputs to a single output value, such as the sum or average of the inputs. The syntax of an aggregate expression is one of the following: 集約式は、問い合わせによって選択される行に対して集約関数を適用することを表現します。 集約関数は、例えば入力の合計や平均などのように、複数の入力を単一の出力値にします。 集約式の構文は下記のうちのいずれかです。

aggregate_name (expression [ , ... ] [ order_by_clause ] ) [ FILTER ( WHERE filter_clause ) ]
aggregate_name (ALL expression [ , ... ] [ order_by_clause ] ) [ FILTER ( WHERE filter_clause ) ]
aggregate_name (DISTINCT expression [ , ... ] [ order_by_clause ] ) [ FILTER ( WHERE filter_clause ) ]
aggregate_name ( * ) [ FILTER ( WHERE filter_clause ) ]
aggregate_name ( [ expression [ , ... ] ] ) WITHIN GROUP ( order_by_clause ) [ FILTER ( WHERE filter_clause ) ]

where <replaceable>aggregate_name</replaceable> is a previously defined aggregate (possibly qualified with a schema name) and <replaceable>expression</replaceable> is any value expression that does not itself contain an aggregate expression or a window function call. The optional <replaceable>order_by_clause</replaceable> and <replaceable>filter_clause</replaceable> are described below. ここで、aggregate_nameは事前に定義された集約(スキーマ名で修飾された場合もあります)、expressionはそれ自体に集約式またはウィンドウ関数呼び出しを含まない任意の値評価式です。 省略可能なorder_by_clausefilter_clauseは後述します。

The first form of aggregate expression invokes the aggregate once for each input row. The second form is the same as the first, since <literal>ALL</literal> is the default. The third form invokes the aggregate once for each distinct value of the expression (or distinct set of values, for multiple expressions) found in the input rows. The fourth form invokes the aggregate once for each input row; since no particular input value is specified, it is generally only useful for the <function>count(*)</function> aggregate function. The last form is used with <firstterm>ordered-set</firstterm> aggregate functions, which are described below. 集約式の最初の構文は、それぞれの入力行に対して1回ずつ集約を呼び出します。 ALLはデフォルトなので、2つ目の形式は最初の形式と同じです。 3番目の形式は、入力行の中にある式の、全ての重複しない値(複数式では重複しない値集合)の集約を呼び出します。 4番目の形式はそれぞれの入力行に対して1回ずつ集約を呼び出します。具体的な入力値が指定されていないため、これは一般的にcount(*)集約関数でのみ役に立ちます。 最後の形式は順序集合集約関数で使われるもので、順序集合集約関数については後述します。

Most aggregate functions ignore null inputs, so that rows in which one or more of the expression(s) yield null are discarded. This can be assumed to be true, unless otherwise specified, for all built-in aggregates. ほとんどの集約関数はNULL入力を無視するため、行内の1つ以上の式がNULLを返す行は破棄されます。 特記されていない限り、すべての組み込み集約がそのような動作になると想定して良いです。

For example, <literal>count(*)</literal> yields the total number of input rows; <literal>count(f1)</literal> yields the number of input rows in which <literal>f1</literal> is non-null, since <function>count</function> ignores nulls; and <literal>count(distinct f1)</literal> yields the number of distinct non-null values of <literal>f1</literal>. 例えば、count(*)は入力行の合計数を求めます。 countはNULLを無視しますので、count(f1)f1が非NULLである入力行の数を求めます。 count(distinct f1)f1の重複しない非NULL値の数を求めます。

Ordinarily, the input rows are fed to the aggregate function in an unspecified order. In many cases this does not matter; for example, <function>min</function> produces the same result no matter what order it receives the inputs in. However, some aggregate functions (such as <function>array_agg</function> and <function>string_agg</function>) produce results that depend on the ordering of the input rows. When using such an aggregate, the optional <replaceable>order_by_clause</replaceable> can be used to specify the desired ordering. The <replaceable>order_by_clause</replaceable> has the same syntax as for a query-level <literal>ORDER BY</literal> clause, as described in <xref linkend="queries-order"/>, except that its expressions are always just expressions and cannot be output-column names or numbers. For example: 通常、入力行は順序を指定されずに集約関数に与えられます。 多くの場合では問題になりません。たとえばminは入力順序に関係なく同一の結果を返します。 しかし一部の集約関数(array_aggおよびstring_aggなど)は入力行の順序に依存した結果を返します。 こうした集約関数を使用する際は、オプションのorder_by_clauseを使用して必要とする順序を指定できます。 order_by_clauseは、7.5で説明する問い合わせレベルのORDER BY句と同じ構文を取りますが、その式は常に単なる式であり、出力列名や序数とすることはできません。 以下に例を示します。

SELECT array_agg(a ORDER BY b DESC) FROM table;

When dealing with multiple-argument aggregate functions, note that the <literal>ORDER BY</literal> clause goes after all the aggregate arguments. For example, write this: 複数の引数を取る集約関数を扱う場合、ORDER BY句はすべての集約引数の後に指定することに注意してください。 例えば、

SELECT string_agg(a, ',' ORDER BY a) FROM table;

not this: であり、

SELECT string_agg(a ORDER BY a, ',') FROM table;  -- incorrect

ではありません。 The latter is syntactically valid, but it represents a call of a single-argument aggregate function with two <literal>ORDER BY</literal> keys (the second one being rather useless since it's a constant). 後者は構文的には有効なものですが、2つのORDER BYキーを持つ単一引数の集約関数の呼び出しを表しています。(2つ目のキーは定数なので役には立ちません。)

If <literal>DISTINCT</literal> is specified in addition to an <replaceable>order_by_clause</replaceable>, then all the <literal>ORDER BY</literal> expressions must match regular arguments of the aggregate; that is, you cannot sort on an expression that is not included in the <literal>DISTINCT</literal> list. order_by_clauseに加えDISTINCTが指定された場合、すべてのORDER BY式が集約関数の通常の引数に一致しなければなりません。つまり、DISTINCTリストに含まれない式でソートすることはできません。

注記

The ability to specify both <literal>DISTINCT</literal> and <literal>ORDER BY</literal> in an aggregate function is a <productname>PostgreSQL</productname> extension. 集約関数においてDISTINCTORDER BYの両方を指定できる機能はPostgreSQLの拡張です。

Placing <literal>ORDER BY</literal> within the aggregate's regular argument list, as described so far, is used when ordering the input rows for general-purpose and statistical aggregates, for which ordering is optional. There is a subclass of aggregate functions called <firstterm>ordered-set aggregates</firstterm> for which an <replaceable>order_by_clause</replaceable> is <emphasis>required</emphasis>, usually because the aggregate's computation is only sensible in terms of a specific ordering of its input rows. Typical examples of ordered-set aggregates include rank and percentile calculations. For an ordered-set aggregate, the <replaceable>order_by_clause</replaceable> is written inside <literal>WITHIN GROUP (...)</literal>, as shown in the final syntax alternative above. The expressions in the <replaceable>order_by_clause</replaceable> are evaluated once per input row just like regular aggregate arguments, sorted as per the <replaceable>order_by_clause</replaceable>'s requirements, and fed to the aggregate function as input arguments. (This is unlike the case for a non-<literal>WITHIN GROUP</literal> <replaceable>order_by_clause</replaceable>, which is not treated as argument(s) to the aggregate function.) The argument expressions preceding <literal>WITHIN GROUP</literal>, if any, are called <firstterm>direct arguments</firstterm> to distinguish them from the <firstterm>aggregated arguments</firstterm> listed in the <replaceable>order_by_clause</replaceable>. Unlike regular aggregate arguments, direct arguments are evaluated only once per aggregate call, not once per input row. This means that they can contain variables only if those variables are grouped by <literal>GROUP BY</literal>; this restriction is the same as if the direct arguments were not inside an aggregate expression at all. Direct arguments are typically used for things like percentile fractions, which only make sense as a single value per aggregation calculation. The direct argument list can be empty; in this case, write just <literal>()</literal> not <literal>(*)</literal>. (<productname>PostgreSQL</productname> will actually accept either spelling, but only the first way conforms to the SQL standard.) 上記のように集約の通常の引数リストにORDER BYを置くことは、汎用的で統計的な集約への入力行を整列する時に使いますが、その整列は省略可能です。 たいていは集約の計算がその入力行の特定の順序に関してのみ意味を持つために、order_by_clause必要な順序集合集約と呼ばれる集約関数の副クラスがあります。 順序集合集約の典型的な例は順位や百分位数の計算を含みます。 順序集合集約では、order_by_clauseは上の構文の最後に示したようにWITHIN GROUP (...)の中に書かれます。 order_by_clauseの式は、通常の集約の引数のように入力行1行につき一度評価され、order_by_clauseの要求に従って整列され、集約関数に入力引数として渡されます。 (非WITHIN GROUP order_by_clauseではない場合はこれとは異なり、集約関数の引数としては扱われません。) WITHIN GROUPの前に引数の式があれば、order_by_clauseに書かれた集約引数と区別するために直接引数と呼ばれます。 通常の集約引数とは異なり、直接引数は集約の呼び出しの時に一度だけ評価され、入力行1行に一度ではありません。 これは、変数がGROUP BYによりグループ化された場合にのみ、その変数を含むことが可能であることを意味します。この制限は直接引数が集約式の中に全くない場合と同じです。 直接引数は、典型的には1度の集約計算で1つの値だけが意味がある百分位数のようなもので使われます。 直接引数のリストは空でも構いません。この場合、(*)ではなく()と書いてください。 (PostgreSQLは実際にどちらの綴りも受け付けますが、後者だけが標準SQLに準拠しています。)

An example of an ordered-set aggregate call is: 順序集合集約の例は以下のとおりです。

SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY income) FROM households;
 percentile_cont
-----------------
           50489

which obtains the 50th percentile, or median, value of the <structfield>income</structfield> column from table <structname>households</structname>. Here, <literal>0.5</literal> is a direct argument; it would make no sense for the percentile fraction to be a value varying across rows. これは、テーブルhouseholdsからincome列の50番目の百分位数、すなわち中央値を得ます。 ここで0.5は直接引数です。百分位数が行毎に変化する値であったら意味がありません。

If <literal>FILTER</literal> is specified, then only the input rows for which the <replaceable>filter_clause</replaceable> evaluates to true are fed to the aggregate function; other rows are discarded. For example: FILTERが指定されていれば、filter_clauseが真と評価した入力行のみがウィンドウ関数に渡されます。それ以外の行は破棄されます。 例えば、

SELECT
    count(*) AS unfiltered,
    count(*) FILTER (WHERE i < 5) AS filtered
FROM generate_series(1,10) AS s(i);
 unfiltered | filtered
------------+----------
         10 |        4
(1 row)

The predefined aggregate functions are described in <xref linkend="functions-aggregate"/>. Other aggregate functions can be added by the user. 定義済みの集約関数は9.21で説明されています。 ユーザは他の集約関数を追加できます。

An aggregate expression can only appear in the result list or <literal>HAVING</literal> clause of a <command>SELECT</command> command. It is forbidden in other clauses, such as <literal>WHERE</literal>, because those clauses are logically evaluated before the results of aggregates are formed. 集約式は、SELECTコマンドの結果リストもしくはHAVING句内でのみ記述できます。 WHEREなどの他の句では許されません。 これらの句は集約結果が形成される前に論理的に評価されるためです。

When an aggregate expression appears in a subquery (see <xref linkend="sql-syntax-scalar-subqueries"/> and <xref linkend="functions-subquery"/>), the aggregate is normally evaluated over the rows of the subquery. But an exception occurs if the aggregate's arguments (and <replaceable>filter_clause</replaceable> if any) contain only outer-level variables: the aggregate then belongs to the nearest such outer level, and is evaluated over the rows of that query. The aggregate expression as a whole is then an outer reference for the subquery it appears in, and acts as a constant over any one evaluation of that subquery. The restriction about appearing only in the result list or <literal>HAVING</literal> clause applies with respect to the query level that the aggregate belongs to. 集約式が副問い合わせ(4.2.119.23を参照)内に現れた場合、通常、集約は副問い合わせの行全体に対して評価されます。 しかし、その集約の引数(と、もしあればfilter_clause)が上位レベルの変数のみを持つ場合は例外です。 その場合、集約は最も近い外側のレベルに属し、その問い合わせの行全体に対して評価されます。 全体として、その集約式は、その後、その集約を含む副問い合わせでは外部参照となり、その副問い合わせにおける評価に対しては定数として動作します。 結果リストもしくはHAVING句にのみ現れるという制約は、その集約が属する問い合わせレベルに関連して適用されます。

4.2.8. ウィンドウ関数呼び出し #

<title>Window Function Calls</title>

A <firstterm>window function call</firstterm> represents the application of an aggregate-like function over some portion of the rows selected by a query. Unlike non-window aggregate calls, this is not tied to grouping of the selected rows into a single output row &mdash; each row remains separate in the query output. However the window function has access to all the rows that would be part of the current row's group according to the grouping specification (<literal>PARTITION BY</literal> list) of the window function call. The syntax of a window function call is one of the following: ウィンドウ関数呼び出しは、問い合わせにより選択された行のある部分に渡って集約のような機能を実現することを表します。 非ウィンドウ集約関数呼び出しと異なり、これは選択された行を1つの行にグループ化することに束縛されず、各行は別途問い合わせ出力に残ります。 しかしウィンドウ関数は、ウィンドウ関数呼び出しのグループ化指定(PARTITION BYリスト)に従った、現在の行のグループの一部となる行にすべてアクセスできます。 ウィンドウ関数呼び出しの構文は以下のいずれかです。

function_name ([expression [, expression ... ]]) [ FILTER ( WHERE filter_clause ) ] OVER window_name
function_name ([expression [, expression ... ]]) [ FILTER ( WHERE filter_clause ) ] OVER ( window_definition )
function_name ( * ) [ FILTER ( WHERE filter_clause ) ] OVER window_name
function_name ( * ) [ FILTER ( WHERE filter_clause ) ] OVER ( window_definition )

where <replaceable class="parameter">window_definition</replaceable> has the syntax ここで、window_definitionは以下の構文になります。

[ existing_window_name ]
[ PARTITION BY expression [, ...] ]
[ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
[ frame_clause ]

The optional <replaceable class="parameter">frame_clause</replaceable> can be one of オプションのframe_clauseは次の中の1つです。

{ RANGE | ROWS | GROUPS } frame_start [ frame_exclusion ]
{ RANGE | ROWS | GROUPS } BETWEEN frame_start AND frame_end [ frame_exclusion ]

where <replaceable>frame_start</replaceable> and <replaceable>frame_end</replaceable> can be one of ここでframe_startおよびframe_endは以下のいずれかです。

UNBOUNDED PRECEDING
offset PRECEDING
CURRENT ROW
offset FOLLOWING
UNBOUNDED FOLLOWING

and <replaceable>frame_exclusion</replaceable> can be one of そして、frame_exclusionは以下のいずれかです。

EXCLUDE CURRENT ROW
EXCLUDE GROUP
EXCLUDE TIES
EXCLUDE NO OTHERS

Here, <replaceable>expression</replaceable> represents any value expression that does not itself contain window function calls. ここで、expressionはそれ自身のウィンドウ関数呼び出しを含まない任意の値式を表わします。

<replaceable>window_name</replaceable> is a reference to a named window specification defined in the query's <literal>WINDOW</literal> clause. Alternatively, a full <replaceable>window_definition</replaceable> can be given within parentheses, using the same syntax as for defining a named window in the <literal>WINDOW</literal> clause; see the <xref linkend="sql-select"/> reference page for details. It's worth pointing out that <literal>OVER wname</literal> is not exactly equivalent to <literal>OVER (wname ...)</literal>; the latter implies copying and modifying the window definition, and will be rejected if the referenced window specification includes a frame clause. window_nameは、問い合わせのWINDOW句で定義された名前付きウィンドウ仕様への参照です。 あるいはまた、完全なwindow_definitionWINDOW句で定義された名前付きウィンドウと同じ構文を使って丸括弧の中に書くことができます。 詳細はSELECTマニュアルページを見てください。 OVER wnameOVER (wname ...)と厳密には等価でないことを指摘しておくのは価値のあることでしょう。 後者はウィンドウ定義をコピーしたり修正したりすることを示唆しており、参照されるウィンドウ仕様がフレーム句を含む場合には拒絶されます。

The <literal>PARTITION BY</literal> clause groups the rows of the query into <firstterm>partitions</firstterm>, which are processed separately by the window function. <literal>PARTITION BY</literal> works similarly to a query-level <literal>GROUP BY</literal> clause, except that its expressions are always just expressions and cannot be output-column names or numbers. Without <literal>PARTITION BY</literal>, all rows produced by the query are treated as a single partition. The <literal>ORDER BY</literal> clause determines the order in which the rows of a partition are processed by the window function. It works similarly to a query-level <literal>ORDER BY</literal> clause, but likewise cannot use output-column names or numbers. Without <literal>ORDER BY</literal>, rows are processed in an unspecified order. PARTITION BY句は問い合わせの行をパーティションに纏め、パーティションはウィンドウ関数により別々に処理されます。 PARTITION BYは、その式が常に式であって出力列名や番号ではないという点を除いて、問い合わせレベルのGROUP BY句と同様に動作します。 PARTITION BYがなければ、問い合わせで生じる行すべてが一つのパーティションとして扱われます。 ORDER BY句はパーティションの行がウィンドウ関数により処理される順序を決定します。 問い合わせレベルのORDER BY句と同様に動作しますが、やはり出力列名や番号は使えません。 ORDER BYがなければ、行は不定の順序で処理されます。

The <replaceable class="parameter">frame_clause</replaceable> specifies the set of rows constituting the <firstterm>window frame</firstterm>, which is a subset of the current partition, for those window functions that act on the frame instead of the whole partition. The set of rows in the frame can vary depending on which row is the current row. The frame can be specified in <literal>RANGE</literal>, <literal>ROWS</literal> or <literal>GROUPS</literal> mode; in each case, it runs from the <replaceable>frame_start</replaceable> to the <replaceable>frame_end</replaceable>. If <replaceable>frame_end</replaceable> is omitted, the end defaults to <literal>CURRENT ROW</literal>. frame_clauseは、パーティション全体ではなくフレーム上で作動するウィンドウ関数に対して、ウィンドウフレームを構成する行の集合を指定します。 ウィンドウフレームは現在のパーティションの部分集合になります。 フレームの中の行の集合は、どの行が現在の行であるかによって変わります。 フレームはRANGEモード、ROWSモード、GROUPSでも指定できます。 どちらの場合でもframe_startからframe_endまでです。 frame_endを省略した場合のデフォルトはCURRENT ROWです。

A <replaceable>frame_start</replaceable> of <literal>UNBOUNDED PRECEDING</literal> means that the frame starts with the first row of the partition, and similarly a <replaceable>frame_end</replaceable> of <literal>UNBOUNDED FOLLOWING</literal> means that the frame ends with the last row of the partition. frame_startUNBOUNDED PRECEDINGならばフレームがパーティションの最初の行から始まることを意味し、同様に、frame_endUNBOUNDED FOLLOWINGならばフレームがパーティションの最後の行で終わることを意味します。

In <literal>RANGE</literal> or <literal>GROUPS</literal> mode, a <replaceable>frame_start</replaceable> of <literal>CURRENT ROW</literal> means the frame starts with the current row's first <firstterm>peer</firstterm> row (a row that the window's <literal>ORDER BY</literal> clause sorts as equivalent to the current row), while a <replaceable>frame_end</replaceable> of <literal>CURRENT ROW</literal> means the frame ends with the current row's last peer row. In <literal>ROWS</literal> mode, <literal>CURRENT ROW</literal> simply means the current row. RANGEあるいはGROUPSモードでは、frame_startCURRENT ROWならば、フレームが現在行の最初のピア行(ウィンドウのORDER BY句が現在行と同じ順序とみなす行)から始まることを意味し、一方、frame_endCURRENT ROWならばフレームが現在行の最後の同等なORDER BYピア行で終わることを意味します。 ROWSモードでは、CURRENT ROWは単に現在行を意味します。

In the <replaceable>offset</replaceable> <literal>PRECEDING</literal> and <replaceable>offset</replaceable> <literal>FOLLOWING</literal> frame options, the <replaceable>offset</replaceable> must be an expression not containing any variables, aggregate functions, or window functions. The meaning of the <replaceable>offset</replaceable> depends on the frame mode: offset PRECEDINGoffset FOLLOWINGフレームオプションでは、offsetは一切の変数、集約関数、あるいはウィンドウ関数を含まない式でなければなりません。 offsetの意味はフレームモードに依存します。

  • In <literal>ROWS</literal> mode, the <replaceable>offset</replaceable> must yield a non-null, non-negative integer, and the option means that the frame starts or ends the specified number of rows before or after the current row. ROWSモードでは、offsetの評価値は非NULL、非負の整数でなければならず、このオプションは現在行の前あるいは後の指定した数の行でフレームが開始あるいは終了することを意味します。

  • In <literal>GROUPS</literal> mode, the <replaceable>offset</replaceable> again must yield a non-null, non-negative integer, and the option means that the frame starts or ends the specified number of <firstterm>peer groups</firstterm> before or after the current row's peer group, where a peer group is a set of rows that are equivalent in the <literal>ORDER BY</literal> ordering. (There must be an <literal>ORDER BY</literal> clause in the window definition to use <literal>GROUPS</literal> mode.) GROUPSモードでも、offsetの評価値は非NULL、非負の整数でなければならず、このオプションは現在行のピアグループ(peer group)の前あるいは後の指定した数のピアグループでフレームが開始あるいは終了することを意味します。 ここでピアグループは、ORDER BYによる順序付け中で等しい行の集合です。 (ウィンドウ定義でGROUPSモードを使うには、ORDER BY句が存在しなければなりません。)

  • In <literal>RANGE</literal> mode, these options require that the <literal>ORDER BY</literal> clause specify exactly one column. The <replaceable>offset</replaceable> specifies the maximum difference between the value of that column in the current row and its value in preceding or following rows of the frame. The data type of the <replaceable>offset</replaceable> expression varies depending on the data type of the ordering column. For numeric ordering columns it is typically of the same type as the ordering column, but for datetime ordering columns it is an <type>interval</type>. For example, if the ordering column is of type <type>date</type> or <type>timestamp</type>, one could write <literal>RANGE BETWEEN '1 day' PRECEDING AND '10 days' FOLLOWING</literal>. The <replaceable>offset</replaceable> is still required to be non-null and non-negative, though the meaning of <quote>non-negative</quote> depends on its data type. RANGEモードでは、ORDER BY句が正確に一つの列を指定することがこれらのオプションによって要求されます。 offsetは現在行の列の値と、フレーム中の前あるいは後ろの行の値の最大の差を指定します。 offset式のデータ型は、順序付けをしている列のデータ型に依存して変わります。 数値型の順序付け列では、典型的には順序付け列と同じですが、日付時間の順序付け列では、intervalになります。 たとえば、順序付け列の型がdateあるいはtimestampなら、RANGE BETWEEN '1 day' PRECEDING AND '10 days' FOLLOWINGと書くことができるでしょう。 ここでもoffsetは非NULLかつ非負である必要があります。 ただし、非負の意味はデータ型に依存します。

In any case, the distance to the end of the frame is limited by the distance to the end of the partition, so that for rows near the partition ends the frame might contain fewer rows than elsewhere. どの場合でも、フレームの最後までの距離はパーティションの最後までの距離に制限されます。 ですからパーティションの最後近くの行では他の場合に比べてフレームには少ない行が含まれるかも知れません。

Notice that in both <literal>ROWS</literal> and <literal>GROUPS</literal> mode, <literal>0 PRECEDING</literal> and <literal>0 FOLLOWING</literal> are equivalent to <literal>CURRENT ROW</literal>. This normally holds in <literal>RANGE</literal> mode as well, for an appropriate data-type-specific meaning of <quote>zero</quote>. ROWSGROUPSモードでは、0 PRECEDING0 FOLLOWINGCURRENT ROWと同じであることに注意してください。 データ型固有の意味で0が適切ならば、通常RANGEにおいても同様です。

The <replaceable>frame_exclusion</replaceable> option allows rows around the current row to be excluded from the frame, even if they would be included according to the frame start and frame end options. <literal>EXCLUDE CURRENT ROW</literal> excludes the current row from the frame. <literal>EXCLUDE GROUP</literal> excludes the current row and its ordering peers from the frame. <literal>EXCLUDE TIES</literal> excludes any peers of the current row from the frame, but not the current row itself. <literal>EXCLUDE NO OTHERS</literal> simply specifies explicitly the default behavior of not excluding the current row or its peers. フレームの開始、終了オプションで含まれることになる行であっても、frame_exclusionオプションで現在行周辺の行がフレームに含まれないようにできます。 EXCLUDE CURRENT ROWは、現在の行をフレームから除外します。 EXCLUDE GROUPは、現在行とその順序付ピアをフレームから除外します。 EXCLUDE TIESは、現在行そのものを除き、フレームにおける現在行のピアをフレームから除外します。 EXCLUDE NO OTHERSは、現在の行あるいはそのピアを除外しないというデフォルトの挙動を明示的に指定するだけです。

The default framing option is <literal>RANGE UNBOUNDED PRECEDING</literal>, which is the same as <literal>RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW</literal>. With <literal>ORDER BY</literal>, this sets the frame to be all rows from the partition start up through the current row's last <literal>ORDER BY</literal> peer. Without <literal>ORDER BY</literal>, this means all rows of the partition are included in the window frame, since all rows become peers of the current row. デフォルトのフレーム化オプションはRANGE UNBOUNDED PRECEDINGで、RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWと同じです。 ORDER BYがあると、フレームはパーティションの開始から現在行の最後のORDER BYピア行までのすべての行になります。 ORDER BYが無い場合は、すべての行が現在行のピアとなるので、パーティションのすべての行がウィンドウフレームに含まれることを意味することになります。

Restrictions are that <replaceable>frame_start</replaceable> cannot be <literal>UNBOUNDED FOLLOWING</literal>, <replaceable>frame_end</replaceable> cannot be <literal>UNBOUNDED PRECEDING</literal>, and the <replaceable>frame_end</replaceable> choice cannot appear earlier in the above list of <replaceable>frame_start</replaceable> and <replaceable>frame_end</replaceable> options than the <replaceable>frame_start</replaceable> choice does &mdash; for example <literal>RANGE BETWEEN CURRENT ROW AND <replaceable>offset</replaceable> PRECEDING</literal> is not allowed. But, for example, <literal>ROWS BETWEEN 7 PRECEDING AND 8 PRECEDING</literal> is allowed, even though it would never select any rows. 制限は、frame_startUNBOUNDED FOLLOWINGとすることができない点、frame_endUNBOUNDED PRECEDINGとすることができない点、および、上記のframe_startframe_endのオプションのリストで、frame_endの選択がframe_startの選択よりも先に現れるものであってはならない点です。 例えば、RANGE BETWEEN CURRENT ROW AND offset PRECEDINGは許されません。 しかし、例えば、決してどの行も選択しないとしても、ROWS BETWEEN 7 PRECEDING AND 8 PRECEDINGは許されます。

If <literal>FILTER</literal> is specified, then only the input rows for which the <replaceable>filter_clause</replaceable> evaluates to true are fed to the window function; other rows are discarded. Only window functions that are aggregates accept a <literal>FILTER</literal> clause. FILTERが指定されていれば、filter_clauseが真と評価した入力行のみがウィンドウ関数に渡されます。それ以外の行は破棄されます。 集約ウィンドウ関数だけがFILTER句を受け付けます。

The built-in window functions are described in <xref linkend="functions-window-table"/>. Other window functions can be added by the user. Also, any built-in or user-defined general-purpose or statistical aggregate can be used as a window function. (Ordered-set and hypothetical-set aggregates cannot presently be used as window functions.) 組み込みウィンドウ関数は表 9.64に記載されています。その他のウィンドウ関数をユーザが追加できます。 また、全ての組み込み、またはユーザ定義の、汎用または統計集約関数もウィンドウ関数として使用できます。 (順序集合と仮想集合集約は現在のところウィンドウ関数として使用できません。)

The syntaxes using <literal>*</literal> are used for calling parameter-less aggregate functions as window functions, for example <literal>count(*) OVER (PARTITION BY x ORDER BY y)</literal>. The asterisk (<literal>*</literal>) is customarily not used for window-specific functions. Window-specific functions do not allow <literal>DISTINCT</literal> or <literal>ORDER BY</literal> to be used within the function argument list. *を使用した構文は、例えばcount(*) OVER (PARTITION BY x ORDER BY y)のように、パラメータのない集約関数をウィンドウ関数として呼び出すために使用されます。 アスタリスク(*)は習慣的にウィンドウ固有の関数には使われません。 ウィンドウ固有の関数は、関数引数リストの中でDISTINCTORDER BYが使われることを許可しません。

Window function calls are permitted only in the <literal>SELECT</literal> list and the <literal>ORDER BY</literal> clause of the query. ウィンドウ関数呼び出しは問い合わせのSELECTリストとORDER BY句の中でのみ許可されます。

More information about window functions can be found in <xref linkend="tutorial-window"/>, <xref linkend="functions-window"/>, and <xref linkend="queries-window"/>. さらなるウィンドウ関数についての情報は3.59.227.2.5にあります。

4.2.9. 型キャスト #

<title>Type Casts</title>

A type cast specifies a conversion from one data type to another. <productname>PostgreSQL</productname> accepts two equivalent syntaxes for type casts: 型キャストは、あるデータ型から他のデータ型への変換を指定します。 PostgreSQLは型キャストに2つの等価な構文を受け付けます。

CAST ( expression AS type )
expression::type

The <literal>CAST</literal> syntax conforms to SQL; the syntax with <literal>::</literal> is historical <productname>PostgreSQL</productname> usage. CAST構文はSQLに準拠したものです。 ::を使用する構文は、PostgreSQLで伝統的に使用されている方法です。

When a cast is applied to a value expression of a known type, it represents a run-time type conversion. The cast will succeed only if a suitable type conversion operation has been defined. Notice that this is subtly different from the use of casts with constants, as shown in <xref linkend="sql-syntax-constants-generic"/>. A cast applied to an unadorned string literal represents the initial assignment of a type to a literal constant value, and so it will succeed for any type (if the contents of the string literal are acceptable input syntax for the data type). キャストが既知の型の評価式に適用された場合、それは実行時型変換を表します。 このキャストは、適切な型変換操作が定義されている場合のみ成功します。 4.1.2.7で示すように、これと定数のキャストの使用との微妙な違いに注意してください。 修飾されていない文字列リテラルに対するキャストは、リテラル定数値の初期に割り当てられる型を表します。 ですから、これは(文字列リテラル定数の内容がそのデータ型の入力構文で受け付けられるのであれば)全ての型で成功します。

An explicit type cast can usually be omitted if there is no ambiguity as to the type that a value expression must produce (for example, when it is assigned to a table column); the system will automatically apply a type cast in such cases. However, automatic casting is only done for casts that are marked <quote>OK to apply implicitly</quote> in the system catalogs. Other casts must be invoked with explicit casting syntax. This restriction is intended to prevent surprising conversions from being applied silently. 評価式が生成しなければならない型に曖昧さがない場合(例えばテーブル列への代入時など)、明示的な型キャストは通常は省略できます。 その場合、システムは自動的に型キャストを適用します。 しかし、自動キャストは、システムカタログに暗黙的に適用しても問題なしと示されている場合にのみ実行されます。 その他のキャストは明示的なキャスト構文で呼び出す必要があります。 この制限は、知らないうちに変換が実行されてしまうことを防ぐためのものです。

It is also possible to specify a type cast using a function-like syntax: また、関数のような構文を使用して型キャストを指定することもできます。

typename ( expression )

However, this only works for types whose names are also valid as function names. For example, <literal>double precision</literal> cannot be used this way, but the equivalent <literal>float8</literal> can. Also, the names <literal>interval</literal>, <literal>time</literal>, and <literal>timestamp</literal> can only be used in this fashion if they are double-quoted, because of syntactic conflicts. Therefore, the use of the function-like cast syntax leads to inconsistencies and should probably be avoided. しかし、これはその型の名前が関数の名前としても有効な場合にのみ動作します。 例えば、double precision はこの方式で使用できませんが、同等のfloat8は使用できます。 また、intervaltimetimestampという名前は、構文が衝突するため、二重引用符で括った場合にのみこの方式で使用できます。 このように、この関数のようなキャスト構文は一貫性がなくなりがちですので、おそらくアプリケーションで使用すべきではありません。

注記

The function-like syntax is in fact just a function call. When one of the two standard cast syntaxes is used to do a run-time conversion, it will internally invoke a registered function to perform the conversion. By convention, these conversion functions have the same name as their output type, and thus the <quote>function-like syntax</quote> is nothing more than a direct invocation of the underlying conversion function. Obviously, this is not something that a portable application should rely on. For further details see <xref linkend="sql-createcast"/>. この関数のような構文は、実際には単なる関数呼び出しです。 2つの標準的なキャスト構文のうちの1つが実行時変換で使用されると、この構文は登録済みの関数を内部的に呼び出して変換を実行します。 慣習的に、これらの変換関数は自身の出力型と同じ名前を持ち、これにより、関数のような構文は背後にある変換用関数を直接呼び出す以上のことを行いません。 移植性を持つアプリケーションが依存すべきものでないことは明確です。 詳細についてはCREATE CASTを参照してください。

4.2.10. 照合順序式 #

<title>Collation Expressions</title>

The <literal>COLLATE</literal> clause overrides the collation of an expression. It is appended to the expression it applies to: COLLATE句は式の照合順序規則を上書きします。 適用するため次のように式の後に追記します。

expr COLLATE collation

where <replaceable>collation</replaceable> is a possibly schema-qualified identifier. The <literal>COLLATE</literal> clause binds tighter than operators; parentheses can be used when necessary. ここでcollationは識別子で、スキーマ修飾可能です。 COLLATE句は演算子よりも結合優先度が高いです。 必要に応じて括弧で囲うことができます。

If no collation is explicitly specified, the database system either derives a collation from the columns involved in the expression, or it defaults to the default collation of the database if no column is involved in the expression. もし照合順序が何も指定されなければ、データベースシステムは式にある列から照合順序を取得します。もし列に関する照合順序が式になければ、データベースのデフォルトの照合順序を使います。

The two common uses of the <literal>COLLATE</literal> clause are overriding the sort order in an <literal>ORDER BY</literal> clause, for example: COLLATE句の主な使われ方が2つあります。 1つはORDER BY句での並べ替え順序を上書きするもので、例えば次のようにします。

SELECT a, b, c FROM tbl WHERE ... ORDER BY a COLLATE "C";

and overriding the collation of a function or operator call that has locale-sensitive results, for example: もう一つは、計算結果がロケールに依存する関数や演算子の呼び出しについて、照合順序を上書きするもので、例えば次のようにします。

SELECT * FROM tbl WHERE a > 'foo' COLLATE "C";

Note that in the latter case the <literal>COLLATE</literal> clause is attached to an input argument of the operator we wish to affect. It doesn't matter which argument of the operator or function call the <literal>COLLATE</literal> clause is attached to, because the collation that is applied by the operator or function is derived by considering all arguments, and an explicit <literal>COLLATE</literal> clause will override the collations of all other arguments. (Attaching non-matching <literal>COLLATE</literal> clauses to more than one argument, however, is an error. For more details see <xref linkend="collation"/>.) Thus, this gives the same result as the previous example: 後者の場合、COLLATE句が、処理対象と想定している入力演算子の引数に対して付与されることに注意してください。 演算子や関数の呼び出しのどの引数に対してCOLLATE句が付与されるかは問題ではありません。演算子や関数により適用される照合順序は対象となる全ての引数を考慮して引き出され、そして明示的に指定されたCOLLATE句がその他の全ての引数に対しての照合順序を上書きするからです。 (しかし、複数の引数に対して一致しないCOLLATE句の付与はエラーとなります。詳細は24.2を参照してください。) このため、前述の例と同じ結果を次のようにして取得できます。

SELECT * FROM tbl WHERE a COLLATE "C" > 'foo';

But this is an error: ただし、次の例はエラーになります。

SELECT * FROM tbl WHERE (a > 'foo') COLLATE "C";

because it attempts to apply a collation to the result of the <literal>&gt;</literal> operator, which is of the non-collatable data type <type>boolean</type>. >演算子の結果に対して照合順序を適用しようとしますが、>演算子は照合不可能なデータ型であるbooleanとなるからです。

4.2.11. スカラ副問い合わせ #

<title>Scalar Subqueries</title>

A scalar subquery is an ordinary <command>SELECT</command> query in parentheses that returns exactly one row with one column. (See <xref linkend="queries"/> for information about writing queries.) The <command>SELECT</command> query is executed and the single returned value is used in the surrounding value expression. It is an error to use a query that returns more than one row or more than one column as a scalar subquery. (But if, during a particular execution, the subquery returns no rows, there is no error; the scalar result is taken to be null.) The subquery can refer to variables from the surrounding query, which will act as constants during any one evaluation of the subquery. See also <xref linkend="functions-subquery"/> for other expressions involving subqueries. スカラ副問い合わせは、正確に1行1列を返す、括弧内の通常のSELECT問い合わせです (問い合わせの記述方法については第7章を参照してください)。 そのSELECT問い合わせは実行され、返される単一の値はその値の前後の評価式で使用されます。 1行を超える行や1列を超える列がスカラ副問い合わせ用の問い合わせとして使用された場合はエラーになります (しかし、ある実行時に、副問い合わせが行を返さない場合はエラーになりません。 そのスカラ結果はNULLとして扱われます)。 副問い合わせは、その周りの問い合わせ内の値を参照できます。 その値は副問い合わせの評価時には定数として扱われます。 副問い合わせに関する他の式については9.23も参照してください。

For example, the following finds the largest city population in each state: 例えば、以下は各州の最大都市の人口を検索します。

SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name)
    FROM states;

4.2.12. 配列コンストラクタ #

<title>Array Constructors</title>

An array constructor is an expression that builds an array value using values for its member elements. A simple array constructor consists of the key word <literal>ARRAY</literal>, a left square bracket <literal>[</literal>, a list of expressions (separated by commas) for the array element values, and finally a right square bracket <literal>]</literal>. For example: 配列コンストラクタは、メンバー要素に対する値を用いて配列値を構築する式です。 単純な配列コンストラクタの構成は、ARRAYキーワード、左大括弧[、(カンマで区切った)配列要素値用の式のリストで、最後に右大括弧]です。 以下に例を示します。

SELECT ARRAY[1,2,3+4];
  array
---------
 {1,2,7}
(1 row)

By default, the array element type is the common type of the member expressions, determined using the same rules as for <literal>UNION</literal> or <literal>CASE</literal> constructs (see <xref linkend="typeconv-union-case"/>). You can override this by explicitly casting the array constructor to the desired type, for example: デフォルトで配列要素型は、メンバ式の型と同じで、UNIONCASE構文と同じ規則を使用して決定されます(10.5を参照してください)。 これを明示的に配列コンストラクタを希望する型にキャストすることで書き換えることができます。例をあげます。

SELECT ARRAY[1,2,22.7]::integer[];
  array
----------
 {1,2,23}
(1 row)

This has the same effect as casting each expression to the array element type individually. For more on casting, see <xref linkend="sql-syntax-type-casts"/>. これはそれぞれの式を配列要素の型に個別にキャストするのと同じ効果があります。 キャストについてより多くは4.2.9を参照してください。

Multidimensional array values can be built by nesting array constructors. In the inner constructors, the key word <literal>ARRAY</literal> can be omitted. For example, these produce the same result: 多次元配列値は、配列コンストラクタを入れ子にすることで構築できます。 内側のコンストラクタではARRAYキーワードは省略可能です。 例えば、以下は同じ結果になります。

SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
     array
---------------
 {{1,2},{3,4}}
(1 row)

SELECT ARRAY[[1,2],[3,4]];
     array
---------------
 {{1,2},{3,4}}
(1 row)

Since multidimensional arrays must be rectangular, inner constructors at the same level must produce sub-arrays of identical dimensions. Any cast applied to the outer <literal>ARRAY</literal> constructor propagates automatically to all the inner constructors. 多次元配列は長方形配列でなければなりませんので、同一レベルの内部コンストラクタは同一次元の副配列を生成しなければなりません。外部ARRAYコンストラクタに適用される全てのキャストは自動的に全ての内部コンストラクタに伝播します。

Multidimensional array constructor elements can be anything yielding an array of the proper kind, not only a sub-<literal>ARRAY</literal> construct. For example: 多次元配列コンストラクタの要素は、副ARRAY構文だけでなく、適切な種類の配列を生成するものをとることができます。 以下に例を示します。

CREATE TABLE arr(f1 int[], f2 int[]);

INSERT INTO arr VALUES (ARRAY[[1,2],[3,4]], ARRAY[[5,6],[7,8]]);

SELECT ARRAY[f1, f2, '{{9,10},{11,12}}'::int[]] FROM arr;
                     array
------------------------------------------------
 {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
(1 row)

You can construct an empty array, but since it's impossible to have an array with no type, you must explicitly cast your empty array to the desired type. For example: 空配列を構築できますが、型を所有しない配列を持つことは不可能なので、空配列を望まれる型に明示的にキャストしなければなりません。例をあげます。

SELECT ARRAY[]::integer[];
 array
-------
 {}
(1 row)

It is also possible to construct an array from the results of a subquery. In this form, the array constructor is written with the key word <literal>ARRAY</literal> followed by a parenthesized (not bracketed) subquery. For example: また、副問い合わせの結果から配列を構成することも可能です。 この形式の場合、配列コンストラクタはARRAYキーワードの後に括弧(大括弧ではない)で括られた副問い合わせとして記述されます。 以下に例を示します。

SELECT ARRAY(SELECT oid FROM pg_proc WHERE proname LIKE 'bytea%');
                              array
------------------------------------------------------------------
 {2011,1954,1948,1952,1951,1244,1950,2005,1949,1953,2006,31,2412}
(1 row)

SELECT ARRAY(SELECT ARRAY[i, i*2] FROM generate_series(1,5) AS a(i));
              array
----------------------------------
 {{1,2},{2,4},{3,6},{4,8},{5,10}}
(1 row)

The subquery must return a single column. If the subquery's output column is of a non-array type, the resulting one-dimensional array will have an element for each row in the subquery result, with an element type matching that of the subquery's output column. If the subquery's output column is of an array type, the result will be an array of the same type but one higher dimension; in this case all the subquery rows must yield arrays of identical dimensionality, else the result would not be rectangular. 副問い合わせは単一の列を返さなければなりません。 副問い合わせの出力列が非配列型であれば、その結果である一次元配列は、副問い合わせの出力列と一致する型を要素型とした、副問い合わせの結果内の各行を要素として持ちます。 副問い合わせの出力列が配列型であれば、その結果は、同じ型で1つ次元の高い配列になります。この場合、副問い合わせの列はすべて同じ次元の配列とならなければなりません。そうでないと結果が長方形になりません。

The subscripts of an array value built with <literal>ARRAY</literal> always begin with one. For more information about arrays, see <xref linkend="arrays"/>. ARRAYで構築された配列値の添字は、常に1から始まります。 配列についての詳細は8.15を参照してください。

4.2.13. 行コンストラクタ #

<title>Row Constructors</title>

A row constructor is an expression that builds a row value (also called a composite value) using values for its member fields. A row constructor consists of the key word <literal>ROW</literal>, a left parenthesis, zero or more expressions (separated by commas) for the row field values, and finally a right parenthesis. For example: 行コンストラクタは、そのメンバフィールドに対する値を用いて行値(複合値とも呼ばれます)を構築する式です。 行コンストラクタは、ROWキーワード、左括弧、行のフィールド値用の0個以上の式(カンマ区切り)、最後に右括弧からなります。 以下に例を示します。

SELECT ROW(1,2.5,'this is a test');

The key word <literal>ROW</literal> is optional when there is more than one expression in the list. ROWキーワードは、2つ以上の式がリスト内にある場合は省略できます。

A row constructor can include the syntax <replaceable>rowvalue</replaceable><literal>.*</literal>, which will be expanded to a list of the elements of the row value, just as occurs when the <literal>.*</literal> syntax is used at the top level of a <command>SELECT</command> list (see <xref linkend="rowtypes-usage"/>). For example, if table <literal>t</literal> has columns <literal>f1</literal> and <literal>f2</literal>, these are the same: 行コンストラクタにはrowvalue.*構文を含めることができます。 これは、SELECTリストの最上位レベルで.*構文が使用された時とまったく同様に、行値の要素の列挙に展開されます(8.16.5参照)。 たとえば、テーブルtf1列とf2列を持つ場合、以下は同一です。

SELECT ROW(t.*, 42) FROM t;
SELECT ROW(t.f1, t.f2, 42) FROM t;

注記

Before <productname>PostgreSQL</productname> 8.2, the <literal>.*</literal> syntax was not expanded in row constructors, so that writing <literal>ROW(t.*, 42)</literal> created a two-field row whose first field was another row value. The new behavior is usually more useful. If you need the old behavior of nested row values, write the inner row value without <literal>.*</literal>, for instance <literal>ROW(t, 42)</literal>. PostgreSQL 8.2より前では、.*構文は行コンストラクタ内では展開されませんでした。 ROW(t.*, 42)と記述すると、1つ目のフィールドにもう一つの行値を持つ、2つのフィールドからなる行が作成されました。 たいていの場合、新しい動作はより使いやすくなっています。 入れ子状の行値という古い動作が必要であれば、内側の行値には.*を使用せずに、たとえばROW(t, 42)と記述してください。

By default, the value created by a <literal>ROW</literal> expression is of an anonymous record type. If necessary, it can be cast to a named composite type &mdash; either the row type of a table, or a composite type created with <command>CREATE TYPE AS</command>. An explicit cast might be needed to avoid ambiguity. For example: デフォルトでは、ROW式により作成される値は匿名レコード型になります。 必要に応じて、名前付きの複合型、つまりテーブルの行型あるいはCREATE TYPE ASで作成された複合型にキャストできます。 曖昧性を防止するために明示的なキャストが必要となることもあります。 以下に例を示します。

CREATE TABLE mytable(f1 int, f2 float, f3 text);

CREATE FUNCTION getf1(mytable) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;


&#45;- No cast needed since only one getf1() exists

-- getf1()が1つしか存在しないためキャスト不要。
SELECT getf1(ROW(1,2.5,'this is a test'));
 getf1
-------
     1
(1 row)

CREATE TYPE myrowtype AS (f1 int, f2 text, f3 numeric);

CREATE FUNCTION getf1(myrowtype) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;


&#45;- Now we need a cast to indicate which function to call:

-- ここでは、どの関数を呼び出すのかを示すためにキャストが必要。
SELECT getf1(ROW(1,2.5,'this is a test'));
ERROR:  function getf1(record) is not unique

SELECT getf1(ROW(1,2.5,'this is a test')::mytable);
 getf1
-------
     1
(1 row)

SELECT getf1(CAST(ROW(11,'this is a test',2.5) AS myrowtype));
 getf1
-------
    11
(1 row)

Row constructors can be used to build composite values to be stored in a composite-type table column, or to be passed to a function that accepts a composite parameter. Also, it is possible to compare two row values or test a row with <literal>IS NULL</literal> or <literal>IS NOT NULL</literal>, for example: 行コンストラクタは、複合型のテーブル列に格納する複合型の値を構築するため、あるいは複合型のパラメータを受け付ける関数に渡すために使用できます。 また、以下の例のように、2つの行値を比較することも、IS NULLもしくはIS NOT NULLで行を検査することも可能です。

SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');


SELECT ROW(table.*) IS NULL FROM table;  &#45;- detect all-null rows

SELECT ROW(table.*) IS NULL FROM table;  -- すべてがNULLの行を検出します。

For more detail see <xref linkend="functions-comparisons"/>. Row constructors can also be used in connection with subqueries, as discussed in <xref linkend="functions-subquery"/>. 詳細は9.24を参照してください。 行コンストラクタは、9.23で説明するように、副問い合わせと一緒に使用することもできます。

4.2.14. 式の評価規則 #

<title>Expression Evaluation Rules</title>

The order of evaluation of subexpressions is not defined. In particular, the inputs of an operator or function are not necessarily evaluated left-to-right or in any other fixed order. 副式の評価の順序は定義されていません。 特に演算子や関数の入力は、必ずしも左から右などの決まった順序で評価されるわけではありません。

Furthermore, if the result of an expression can be determined by evaluating only some parts of it, then other subexpressions might not be evaluated at all. For instance, if one wrote: さらに、その式の一部を評価しただけで式の結果を決定できる場合には、他の副式がまったく評価されないこともあります。 例えば、

SELECT true OR somefunc();

then <literal>somefunc()</literal> would (probably) not be called at all. The same would be the case if one wrote: では、(おそらく)somefunc()は呼び出されないでしょう。 以下の場合も同様です。

SELECT somefunc() OR true;

Note that this is not the same as the left-to-right <quote>short-circuiting</quote> of Boolean operators that is found in some programming languages. これは一部のプログラミング言語に見られる、論理演算子での左から右への短絡評価とは異なることに注意してください。

As a consequence, it is unwise to use functions with side effects as part of complex expressions. It is particularly dangerous to rely on side effects or evaluation order in <literal>WHERE</literal> and <literal>HAVING</literal> clauses, since those clauses are extensively reprocessed as part of developing an execution plan. Boolean expressions (<literal>AND</literal>/<literal>OR</literal>/<literal>NOT</literal> combinations) in those clauses can be reorganized in any manner allowed by the laws of Boolean algebra. そのため、副次作用がある関数を複雑な式の一部として使用することは推奨されません。 特に、WHERE句およびHAVING句で副次作用や評価順に依存するのは危険です。 これらの句は、実行計画を作成する過程で頻繁に再処理されるからです。 これらの句のブール式(AND/OR/NOTの組み合わせ)は、ブール代数の規則で許されるあらゆる方式で再編成される可能性があります。

When it is essential to force evaluation order, a <literal>CASE</literal> construct (see <xref linkend="functions-conditional"/>) can be used. For example, this is an untrustworthy way of trying to avoid division by zero in a <literal>WHERE</literal> clause: 評価の順序を強制することが重要であれば、CASE構文(9.18を参照)を使用できます。 例えば、次の式はWHERE句で0除算を避ける方法としては信頼性の低いものです。

SELECT ... WHERE x > 0 AND y/x > 1.5;

But this is safe: しかし、次のようにすれば安全です。

SELECT ... WHERE CASE WHEN x > 0 THEN y/x > 1.5 ELSE false END;

A <literal>CASE</literal> construct used in this fashion will defeat optimization attempts, so it should only be done when necessary. (In this particular example, it would be better to sidestep the problem by writing <literal>y &gt; 1.5*x</literal> instead.) このような方法で使用されるCASE構文は最適化を妨げるものなので、必要な場合にのみ使用してください。 (特に、この例では、y > 1.5*xと代わりに記述することが問題を回避するより優れた方法です。)

<literal>CASE</literal> is not a cure-all for such issues, however. One limitation of the technique illustrated above is that it does not prevent early evaluation of constant subexpressions. As described in <xref linkend="xfunc-volatility"/>, functions and operators marked <literal>IMMUTABLE</literal> can be evaluated when the query is planned rather than when it is executed. Thus for example しかしながら、CASEはそのような問題に対する万能薬ではありません。 上で示したような方法の限界の1つは、定数副式が早く評価されるのを防げないことです。 38.7に記すように、IMMUTABLEと印をつけられた関数と演算子は、実行される時ではなく問い合わせが計画される時に評価されるかもしれません。 そのため、例えば

SELECT CASE WHEN x > 0 THEN x ELSE 1/0 END FROM tab;

is likely to result in a division-by-zero failure due to the planner trying to simplify the constant subexpression, even if every row in the table has <literal>x &gt; 0</literal> so that the <literal>ELSE</literal> arm would never be entered at run time. は、たとえテーブルのすべての行がx > 0であり、実行時にはELSE節に決して入らないとしても、プランナが定数副式を単純化しようとするためにゼロによる除算での失敗という結果に終わるでしょう。

While that particular example might seem silly, related cases that don't obviously involve constants can occur in queries executed within functions, since the values of function arguments and local variables can be inserted into queries as constants for planning purposes. Within <application>PL/pgSQL</application> functions, for example, using an <literal>IF</literal>-<literal>THEN</literal>-<literal>ELSE</literal> statement to protect a risky computation is much safer than just nesting it in a <literal>CASE</literal> expression. この特別な例は馬鹿げたものに見えるかもしれませんが、定数を含むことが明らかではない関連する場合が関数の中で実行される問い合わせで起こり得ます。関数の引数とローカル変数は計画作成の都合で定数として問い合わせに入れられることがあるからです。 例えば、PL/pgSQL関数の中では、IF-THEN-ELSE文を使って危険な計算を保護する方がCASE式の中で入れ子にするよりもずっと安全です。

Another limitation of the same kind is that a <literal>CASE</literal> cannot prevent evaluation of an aggregate expression contained within it, because aggregate expressions are computed before other expressions in a <literal>SELECT</literal> list or <literal>HAVING</literal> clause are considered. For example, the following query can cause a division-by-zero error despite seemingly having protected against it: 同種の別の限界は、その中に含まれる集約式の評価をCASEが防げないことです。なぜなら、SELECTリストやHAVING句の別の式が考慮される前に、集約式が計算されるからです。 例えば、以下の問い合わせは対策を施しているように見えるにも関わらずゼロ除算エラーになり得ます。

SELECT CASE WHEN min(employees) > 0
            THEN avg(expenses / employees)
       END
    FROM departments;

The <function>min()</function> and <function>avg()</function> aggregates are computed concurrently over all the input rows, so if any row has <structfield>employees</structfield> equal to zero, the division-by-zero error will occur before there is any opportunity to test the result of <function>min()</function>. Instead, use a <literal>WHERE</literal> or <literal>FILTER</literal> clause to prevent problematic input rows from reaching an aggregate function in the first place. min()avg()集約は入力行すべてに対して同時に計算されますので、もしemployeesがゼロになる行があれば、min()の結果が検査される機会の前にゼロ除算エラーが起こります。 代わりに、まずは問題のある入力行が集約関数に渡されないようにするためにWHEREまたはFILTER句を使ってください。