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

SELECT

SELECT, TABLE, WITH <refpurpose>retrieve rows from a table or view</refpurpose> — テーブルもしくはビューから行を検索する

概要

[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
    [ * | expression [ [ AS ] output_name ] [, ...] ]
    [ FROM from_item [, ...] ]
    [ WHERE condition ]
    [ GROUP BY [ ALL | DISTINCT ] grouping_element [, ...] ]
    [ HAVING condition ]
    [ WINDOW window_name AS ( window_definition ) [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select ]
    [ ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...] ]
    [ LIMIT { count | ALL } ]
    [ OFFSET start [ ROW | ROWS ] ]
    [ FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES } ]
    [ FOR { UPDATE | NO KEY UPDATE | SHARE | KEY SHARE } [ OF table_name [, ...] ] [ NOWAIT | SKIP LOCKED ] [...] ]


<phrase>where <replaceable class="parameter">from_item</replaceable> can be one of:</phrase>

ここでfrom_itemは以下のいずれかです。

    [ ONLY ] table_name [ * ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
                [ TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ] ]
    [ LATERAL ] ( select ) [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    with_query_name [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    [ LATERAL ] function_name ( [ argument [, ...] ] )
                [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    [ LATERAL ] function_name ( [ argument [, ...] ] ) [ AS ] alias ( column_definition [, ...] )
    [ LATERAL ] function_name ( [ argument [, ...] ] ) AS ( column_definition [, ...] )
    [ LATERAL ] ROWS FROM( function_name ( [ argument [, ...] ] ) [ AS ( column_definition [, ...] ) ] [, ...] )
                [ WITH ORDINALITY ] [ [ AS ] alias [ ( column_alias [, ...] ) ] ]
    from_item join_type from_item { ON join_condition | USING ( join_column [, ...] ) [ AS join_using_alias ] }
    from_item NATURAL join_type from_item
    from_item CROSS JOIN from_item


<phrase>and <replaceable class="parameter">grouping_element</replaceable> can be one of:</phrase>

またgrouping_elementは以下のいずれかです。

    ( )
    expression
    ( expression [, ...] )
    ROLLUP ( { expression | ( expression [, ...] ) } [, ...] )
    CUBE ( { expression | ( expression [, ...] ) } [, ...] )
    GROUPING SETS ( grouping_element [, ...] )


<phrase>and <replaceable class="parameter">with_query</replaceable> is:</phrase>

またwith_queryは以下の通りです。

    with_query_name [ ( column_name [, ...] ) ] AS [ [ NOT ] MATERIALIZED ] ( select | values | insert | update | delete )
        [ SEARCH { BREADTH | DEPTH } FIRST BY column_name [, ...] SET search_seq_col_name ]
        [ CYCLE column_name [, ...] SET cycle_mark_col_name [ TO cycle_mark_value DEFAULT cycle_mark_default ] USING cycle_path_col_name ]

TABLE [ ONLY ] table_name [ * ]

説明

<title>Description</title>

<command>SELECT</command> retrieves rows from zero or more tables. The general processing of <command>SELECT</command> is as follows: SELECTは0個以上のテーブルから行を返します。 SELECTの一般的な処理は以下の通りです。

  1. All queries in the <literal>WITH</literal> list are computed. These effectively serve as temporary tables that can be referenced in the <literal>FROM</literal> list. A <literal>WITH</literal> query that is referenced more than once in <literal>FROM</literal> is computed only once, unless specified otherwise with <literal>NOT MATERIALIZED</literal>. (See <xref linkend="sql-with"/> below.) WITHリスト内のすべての問い合わせが計算されます。 これらは実質的には、FROMリスト内から参照可能な一時テーブルとして提供されます。 NOT MATERIALIZEDが指定された場合を除き、FROM内で2回以上参照されるWITH問い合わせは一度のみ計算されます。 (後述のWITH句を参照してください。)

  2. All elements in the <literal>FROM</literal> list are computed. (Each element in the <literal>FROM</literal> list is a real or virtual table.) If more than one element is specified in the <literal>FROM</literal> list, they are cross-joined together. (See <xref linkend="sql-from"/> below.) FROMリストにある全要素が計算されます (FROMリストの要素は実テーブルか仮想テーブルのいずれかです)。 FROMリストに複数の要素が指定された場合、それらはクロス結合されます (後述のFROM句を参照してください)。

  3. If the <literal>WHERE</literal> clause is specified, all rows that do not satisfy the condition are eliminated from the output. (See <xref linkend="sql-where"/> below.) WHERE句が指定された場合、条件を満たさない行は全て出力から取り除かれます (後述のWHERE句を参照してください)。

  4. If the <literal>GROUP BY</literal> clause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed. If the <literal>HAVING</literal> clause is present, it eliminates groups that do not satisfy the given condition. (See <xref linkend="sql-groupby"/> and <xref linkend="sql-having"/> below.) GROUP BY句が指定された場合、および集約関数の呼び出しがある場合は、1つまたは複数の値が条件に合う行ごとにグループに組み合わせて出力され、また集約関数の結果が計算されます。 HAVING句が指定された場合、指定した条件を満たさないグループは取り除かれます (後述のGROUP BY句HAVING句を参照してください)。

  5. The actual output rows are computed using the <command>SELECT</command> output expressions for each selected row or row group. (See <xref linkend="sql-select-list"/> below.) 実際には、選択された各行または行グループに対して、SELECTの出力式を使用して計算した結果の行が出力されます (後述のSELECTリストを参照してください)。

  6. <para><literal>SELECT DISTINCT</literal> eliminates duplicate rows from the result. <literal>SELECT DISTINCT ON</literal> eliminates rows that match on all the specified expressions. <literal>SELECT ALL</literal> (the default) will return all candidate rows, including duplicates. (See <xref linkend="sql-distinct"/> below.)

    SELECT DISTINCTは結果から重複行を取り除きます。 SELECT DISTINCT ONは指定した全ての式に一致する行を取り除きます。 SELECT ALLでは、重複行も含め、全ての候補行を返します(これがデフォルトです。 詳しくは、後述のDISTINCT句を参照してください)。

  7. Using the operators <literal>UNION</literal>, <literal>INTERSECT</literal>, and <literal>EXCEPT</literal>, the output of more than one <command>SELECT</command> statement can be combined to form a single result set. The <literal>UNION</literal> operator returns all rows that are in one or both of the result sets. The <literal>INTERSECT</literal> operator returns all rows that are strictly in both result sets. The <literal>EXCEPT</literal> operator returns the rows that are in the first result set but not in the second. In all three cases, duplicate rows are eliminated unless <literal>ALL</literal> is specified. The noise word <literal>DISTINCT</literal> can be added to explicitly specify eliminating duplicate rows. Notice that <literal>DISTINCT</literal> is the default behavior here, even though <literal>ALL</literal> is the default for <command>SELECT</command> itself. (See <xref linkend="sql-union"/>, <xref linkend="sql-intersect"/>, and <xref linkend="sql-except"/> below.) UNIONINTERSECTEXCEPT演算子を使用すると、複数のSELECT文の出力を1つの結果集合にまとめることができます。 UNION演算子は、両方の結果集合に存在する行と、片方の結果集合に存在する行を全て返します。 INTERSECT演算子は、両方の結果集合に存在する行を返します。 EXCEPT演算子は、最初の結果集合にあり、2番目の結果集合にない行を返します。 ALLが指定されない限り、いずれの場合も、重複する行は取り除かれます。 無意味なDISTINCTという単語を付けて、明示的に重複行を除去することを指定することができます。 SELECT自体はALLがデフォルトですが、この場合はDISTINCTがデフォルトの動作であることに注意してください。 (後述のUNION句INTERSECT句EXCEPT句を参照してください。)

  8. If the <literal>ORDER BY</literal> clause is specified, the returned rows are sorted in the specified order. If <literal>ORDER BY</literal> is not given, the rows are returned in whatever order the system finds fastest to produce. (See <xref linkend="sql-orderby"/> below.) ORDER BY句が指定された場合、返される行は指定した順番でソートされます。 ORDER BYが指定されない場合は、システムが計算過程で見つけた順番で行が返されます (後述のORDER BY句を参照してください)。

  9. If the <literal>LIMIT</literal> (or <literal>FETCH FIRST</literal>) or <literal>OFFSET</literal> clause is specified, the <command>SELECT</command> statement only returns a subset of the result rows. (See <xref linkend="sql-limit"/> below.) LIMIT(またはFETCH FIRST)あるいはOFFSET句が指定された場合、SELECT文は結果行の一部分のみを返します (詳しくは、後述のLIMIT句を参照してください)。

  10. If <literal>FOR UPDATE</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> or <literal>FOR KEY SHARE</literal> is specified, the <command>SELECT</command> statement locks the selected rows against concurrent updates. (See <xref linkend="sql-for-update-share"/> below.) FOR UPDATEFOR NO KEY UPDATEFOR SHAREまたはFOR KEY SHARE句を指定すると、SELECT文は引き続き行われる更新に備えて選択行をロックします (詳しくは、後述のロック処理句を参照してください)。

You must have <literal>SELECT</literal> privilege on each column used in a <command>SELECT</command> command. The use of <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> or <literal>FOR KEY SHARE</literal> requires <literal>UPDATE</literal> privilege as well (for at least one column of each table so selected). SELECTコマンド内で使われる列それぞれに対するSELECT権限が必要です。 FOR NO KEY UPDATEFOR UPDATEFOR SHAREまたはFOR KEY SHAREを使用するためには、さらに、(選択された各テーブルで少なくとも1列に対する)UPDATE権限が必要です。

パラメータ

<title>Parameters</title> <refsect2 id="sql-with" xreflabel="WITH Clause">

WITH

<title><literal>WITH</literal> Clause</title>

The <literal>WITH</literal> clause allows you to specify one or more subqueries that can be referenced by name in the primary query. The subqueries effectively act as temporary tables or views for the duration of the primary query. Each subquery can be a <command>SELECT</command>, <command>TABLE</command>, <command>VALUES</command>, <command>INSERT</command>, <command>UPDATE</command> or <command>DELETE</command> statement. When writing a data-modifying statement (<command>INSERT</command>, <command>UPDATE</command> or <command>DELETE</command>) in <literal>WITH</literal>, it is usual to include a <literal>RETURNING</literal> clause. It is the output of <literal>RETURNING</literal>, <emphasis>not</emphasis> the underlying table that the statement modifies, that forms the temporary table that is read by the primary query. If <literal>RETURNING</literal> is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query. WITH句により主問い合わせ内で名前により参照可能な、1つ以上の副問い合わせを指定することができます。 副問い合わせは実質的に主問い合わせの間の一時的なテーブルかビューのように動作します。 各副問い合わせはSELECTTABLEVALUESINSERTUPDATEDELETEにすることができます。 WITH内でデータ変更文(INSERTUPDATEDELETE)を記述する場合は、RETURNING句を含めるのが普通です。 主問い合わせで読み取られる一時テーブルを形成するのは、RETURNINGの出力であり、文が変更する背後のテーブルではありませんRETURNINGを省いても文は実行されますが、出力を生成しませんので、主問い合わせでテーブルとして参照することができません。

A name (without schema qualification) must be specified for each <literal>WITH</literal> query. Optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery. (スキーマ修飾がない)名前を各WITH問い合わせで指定しなければなりません。 列名のリストをオプションで指定することもできます。 これを省略すると、列名は副問い合わせから推定されます。

If <literal>RECURSIVE</literal> is specified, it allows a <command>SELECT</command> subquery to reference itself by name. Such a subquery must have the form RECURSIVEが指定されると、SELECT副問い合わせは自身で名前により参照することができます。 こうした副問い合わせは以下のような形式でなければなりません。

non_recursive_term UNION [ ALL | DISTINCT ] recursive_term

where the recursive self-reference must appear on the right-hand side of the <literal>UNION</literal>. Only one recursive self-reference is permitted per query. Recursive data-modifying statements are not supported, but you can use the results of a recursive <command>SELECT</command> query in a data-modifying statement. See <xref linkend="queries-with"/> for an example. ここで再帰的な自己参照はUNIONの右辺に現れなければなりません。 問い合わせ当たり1つの再帰的な自己参照のみが許されます。 再帰的なデータ変更文はサポートされていませんが、データ変更文で再帰的なSELECTの結果を使用することができます。 例は7.8を参照してください。

Another effect of <literal>RECURSIVE</literal> is that <literal>WITH</literal> queries need not be ordered: a query can reference another one that is later in the list. (However, circular references, or mutual recursion, are not implemented.) Without <literal>RECURSIVE</literal>, <literal>WITH</literal> queries can only reference sibling <literal>WITH</literal> queries that are earlier in the <literal>WITH</literal> list. RECURSIVEには他にも、WITH問い合わせが順序通りでなくても構わないという効果があります。 つまり、問い合わせはリストの後にある別のものを参照することができます。 (しかし巡回する参照や相互的な参照は実装されていません。) RECURSIVEがないと、WITH問い合わせは主問い合わせが共通するWITH問い合わせのうち、WITHリストの前方にあるもののみを参照することができます。

When there are multiple queries in the <literal>WITH</literal> clause, <literal>RECURSIVE</literal> should be written only once, immediately after <literal>WITH</literal>. It applies to all queries in the <literal>WITH</literal> clause, though it has no effect on queries that do not use recursion or forward references. WITH句に複数の問い合わせがある場合、RECURSIVEWITHの直後に一度だけ書くべきです。 再帰や前方参照を使わない問い合わせには効果はないですが、WITH句内の問い合わせすべてに適用されます。

The optional <literal>SEARCH</literal> clause computes a <firstterm>search sequence column</firstterm> that can be used for ordering the results of a recursive query in either breadth-first or depth-first order. The supplied column name list specifies the row key that is to be used for keeping track of visited rows. A column named <replaceable>search_seq_col_name</replaceable> will be added to the result column list of the <literal>WITH</literal> query. This column can be ordered by in the outer query to achieve the respective ordering. See <xref linkend="queries-with-search"/> for examples. 省略可能なSEARCH句では、再帰問い合わせの結果を幅優先順か深さ優先順で並べるのに使える検索シーケンス列を計算します。 与えられた列名のリストは、訪れた行を追跡するのに使う行キーを指定します。 search_seq_col_nameという名前の列が、WITH問い合わせの結果列のリストに追加されます。 この列により、外側の問い合わせでそれぞれの順序を導入できます。 例は7.8.2.1を参照してください。

The optional <literal>CYCLE</literal> clause is used to detect cycles in recursive queries. The supplied column name list specifies the row key that is to be used for keeping track of visited rows. A column named <replaceable>cycle_mark_col_name</replaceable> will be added to the result column list of the <literal>WITH</literal> query. This column will be set to <replaceable>cycle_mark_value</replaceable> when a cycle has been detected, else to <replaceable>cycle_mark_default</replaceable>. Furthermore, processing of the recursive union will stop when a cycle has been detected. <replaceable>cycle_mark_value</replaceable> and <replaceable>cycle_mark_default</replaceable> must be constants and they must be coercible to a common data type, and the data type must have an inequality operator. (The SQL standard requires that they be Boolean constants or character strings, but PostgreSQL does not require that.) By default, <literal>TRUE</literal> and <literal>FALSE</literal> (of type <type>boolean</type>) are used. Furthermore, a column named <replaceable>cycle_path_col_name</replaceable> will be added to the result column list of the <literal>WITH</literal> query. This column is used internally for tracking visited rows. See <xref linkend="queries-with-cycle"/> for examples. 省略可能なCYCLE句は、再帰問い合わせで循環を検出するのに使われます。 与えられた列名のリストは、訪れた行を追跡するのに使う行キーを指定します。 cycle_mark_col_nameという名前の列が、WITH問い合わせの結果列のリストに追加されます。 この列は、循環が検出された場合にはcycle_mark_valueに、そうでない場合にはcycle_mark_defaultに設定されます。 さらに、循環が検出された場合、再帰的な和の処理は停止します。 cycle_mark_valuecycle_mark_defaultは定数でなければならず、強制的に共通のデータ型でなければならず、そのデータ型には不等価演算子がなければなりません。 (標準SQLは、論理定数か文字列であることを要求しますが、PostgreSQLは要求しません。) デフォルトでは(boolean型の)TRUEFALSEが使われます。 さらに、cycle_path_col_nameという名前の列が、WITH問い合わせの結果列のリストに追加されます。 この列は訪れた行を追跡するために内部的に使われます。 例は7.8.2.2を参照してください。

Both the <literal>SEARCH</literal> and the <literal>CYCLE</literal> clause are only valid for recursive <literal>WITH</literal> queries. The <replaceable>with_query</replaceable> must be a <literal>UNION</literal> (or <literal>UNION ALL</literal>) of two <literal>SELECT</literal> (or equivalent) commands (no nested <literal>UNION</literal>s). If both clauses are used, the column added by the <literal>SEARCH</literal> clause appears before the columns added by the <literal>CYCLE</literal> clause. SEARCH句、CYCLE句とも再帰的なWITH問い合わせに対してのみ有効です。 with_queryは、(入れ子になったUNIONのない)2つのSELECT(またはそれに相当する)コマンドのUNION(またはUNION ALL)でなければなりません。 両方の句が使われた場合、SEARCH句で追加された列はCYCLE句で追加された列の前に現れます。

The primary query and the <literal>WITH</literal> queries are all (notionally) executed at the same time. This implies that the effects of a data-modifying statement in <literal>WITH</literal> cannot be seen from other parts of the query, other than by reading its <literal>RETURNING</literal> output. If two such data-modifying statements attempt to modify the same row, the results are unspecified. 主問い合わせとWITH問い合わせは(理論的には)同時に実行されます。 このことは、WITH中のデータ更新文の効果は、RETURNING出力の読み込みを行ったことによるものを除き、問い合わせ中の他の部分から見えないことを意味します。 2つのそうしたデータ更新文が同じ行を更新しようとした時の結果は不定です。

A key property of <literal>WITH</literal> queries is that they are normally evaluated only once per execution of the primary query, even if the primary query refers to them more than once. In particular, data-modifying statements are guaranteed to be executed once and only once, regardless of whether the primary query reads all or any of their output. WITH問い合わせの重要な特性は、これらを主問い合わせが複数回参照していたとしても、主問い合わせの実行当たり通常一度のみ評価される点です。 特にデータ変更文は、主問い合わせがその出力のすべてまたは一部を読み取るかに関係なく、本当に一度のみ実行されることが保証されています。

However, a <literal>WITH</literal> query can be marked <literal>NOT MATERIALIZED</literal> to remove this guarantee. In that case, the <literal>WITH</literal> query can be folded into the primary query much as though it were a simple sub-<literal>SELECT</literal> in the primary query's <literal>FROM</literal> clause. This results in duplicate computations if the primary query refers to that <literal>WITH</literal> query more than once; but if each such use requires only a few rows of the <literal>WITH</literal> query's total output, <literal>NOT MATERIALIZED</literal> can provide a net savings by allowing the queries to be optimized jointly. <literal>NOT MATERIALIZED</literal> is ignored if it is attached to a <literal>WITH</literal> query that is recursive or is not side-effect-free (i.e., is not a plain <literal>SELECT</literal> containing no volatile functions). しかし、WITH問い合わせにNOT MATERIALIZEDと印を付けることにより、この保証を取り除くことができます。 その場合、WITH問い合わせは、主問い合わせのFROM句中の単純な副SELECTであるかのように可能な限り主問い合わせ中に畳み込むことができます。 この結果、主問い合わせがWITH問い合わせを複数回参照している場合には複数回の計算が行われます。 しかし、そこで使用される問い合わせがWITH問い合わせ全体の出力のうちの数行しか必要としないなら、NOT MATERIALIZEDは問い合わせを連携して最適化することができるので、全体のコストの節約ができます。 再帰的であるか、あるいは副作用のある(すなわち揮発性の関数を含まない単純SELECTではない)WITH問い合わせにNOT MATERIALIZEDを適用しても無視されます。

By default, a side-effect-free <literal>WITH</literal> query is folded into the primary query if it is used exactly once in the primary query's <literal>FROM</literal> clause. This allows joint optimization of the two query levels in situations where that should be semantically invisible. However, such folding can be prevented by marking the <literal>WITH</literal> query as <literal>MATERIALIZED</literal>. That might be useful, for example, if the <literal>WITH</literal> query is being used as an optimization fence to prevent the planner from choosing a bad plan. <productname>PostgreSQL</productname> versions before v12 never did such folding, so queries written for older versions might rely on <literal>WITH</literal> to act as an optimization fence. デフォルトでは、主問い合わせ中のFROM句で正確に一度だけ使われているなら、副作用のないWITH問い合わせは主問い合わせに畳み込まれます。 これにより意味論的に不可視の二つの問い合わせレベルが共同して最適化されることを可能にします。 しかし、WITH問い合わせにMATERIALIZEDと印を付けることにより、そうした畳込みを防ぐことができます。 たとえば、プランナが悪いプランを選択するのを防ぐために最適化障壁としてWITH問い合わせを使っている場合にこれは有用です。 PostgreSQLバージョン12よりも前ではそうした畳込みは決して行われていなかったので、古いバージョン用に書かれた問い合わせはWITHが最適化障壁として働くことに依存しているかもしれません。

See <xref linkend="queries-with"/> for additional information. 追加情報については7.8を参照してください。

<refsect2 id="sql-from" xreflabel="FROM Clause">

FROM

<title><literal>FROM</literal> Clause</title>

The <literal>FROM</literal> clause specifies one or more source tables for the <command>SELECT</command>. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added (via <literal>WHERE</literal>) to restrict the returned rows to a small subset of the Cartesian product. FROM句にはSELECTの対象となるソーステーブルを1つ以上指定します。 複数のソースが指定された場合、結果は全てのソースの直積(クロス結合)となります。 しかし、通常は(WHEREを介して)制約条件を付けて、直積のごく一部を返すように結果行を限定します。

The <literal>FROM</literal> clause can contain the following elements: FROM句には以下の要素を指定できます。

table_name

The name (optionally schema-qualified) of an existing table or view. If <literal>ONLY</literal> is specified before the table name, only that table is scanned. If <literal>ONLY</literal> is not specified, the table and all its descendant tables (if any) are scanned. Optionally, <literal>*</literal> can be specified after the table name to explicitly indicate that descendant tables are included. 既存のテーブルもしくはビューの名前です(スキーマ修飾名も可)。 テーブル名の前にONLYが指定された場合、そのテーブルのみがスキャンされます。 ONLYが指定されない場合、テーブルと(もしあれば)それを継承する全てのテーブルがスキャンされます。 省略することもできますが、テーブル名の後に*を指定することで、明示的に継承するテーブルも含まれることを示すことができます。

alias

A substitute name for the <literal>FROM</literal> item containing the alias. An alias is used for brevity or to eliminate ambiguity for self-joins (where the same table is scanned multiple times). When an alias is provided, it completely hides the actual name of the table or function; for example given <literal>FROM foo AS f</literal>, the remainder of the <command>SELECT</command> must refer to this <literal>FROM</literal> item as <literal>f</literal> not <literal>foo</literal>. If an alias is written, a column alias list can also be written to provide substitute names for one or more columns of the table. 別名を含むFROM項目の代替名です。 別名は、指定を簡潔にするため、もしくは、自己結合(同じテーブルを複数回スキャンする結合)の曖昧さをなくすために使われます。 別名が指定されている場合は、その別名によって実際のテーブル名または関数名が完全に隠されます。 例えば、FROM foo AS fと指定されている場合、SELECT文の以降の部分ではこのFROM項目をfooではなくfとして参照する必要があります。 テーブルの別名があれば、そのテーブルの複数の列の名前を置き換える列の別名リストを記述することができます。

TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ]

A <literal>TABLESAMPLE</literal> clause after a <replaceable class="parameter">table_name</replaceable> indicates that the specified <replaceable class="parameter">sampling_method</replaceable> should be used to retrieve a subset of the rows in that table. This sampling precedes the application of any other filters such as <literal>WHERE</literal> clauses. The standard <productname>PostgreSQL</productname> distribution includes two sampling methods, <literal>BERNOULLI</literal> and <literal>SYSTEM</literal>, and other sampling methods can be installed in the database via extensions. table_nameの後のTABLESAMPLE句は、そのテーブルの行の部分集合を取り出すときに、指定したsampling_methodを使うべきであることを示唆します。 このサンプリングはWHEREなど他のすべてのフィルタの適用に先立って行われます。 PostgreSQLの標準ディストリビューションには、BERNOULLISYSTEMの2つのサンプリングメソッドが含まれています。 他のサンプリングメソッドも拡張(extension)によりデータベースにインストールすることができます。

The <literal>BERNOULLI</literal> and <literal>SYSTEM</literal> sampling methods each accept a single <replaceable class="parameter">argument</replaceable> which is the fraction of the table to sample, expressed as a percentage between 0 and 100. This argument can be any <type>real</type>-valued expression. (Other sampling methods might accept more or different arguments.) These two methods each return a randomly-chosen sample of the table that will contain approximately the specified percentage of the table's rows. The <literal>BERNOULLI</literal> method scans the whole table and selects or ignores individual rows independently with the specified probability. The <literal>SYSTEM</literal> method does block-level sampling with each block having the specified chance of being selected; all rows in each selected block are returned. The <literal>SYSTEM</literal> method is significantly faster than the <literal>BERNOULLI</literal> method when small sampling percentages are specified, but it may return a less-random sample of the table as a result of clustering effects. サンプリングメソッドBERNOULLISYSTEMはいずれも1つだけargumentを取り、これはテーブルからサンプリングする割合で0から100までのパーセントで表現されます。 この引数はreal型の値を取る任意の式にできます。 (他のサンプリングメソッドは、複数の、あるいは異なる引数を受け取るかもしれません。) これら2つの方法はいずれも、テーブルのうち指定された割合に近い行数を含む、ランダムに選択されたサンプルテーブルを返します。 BERNOULLIでは、テーブル全体を走査し、個々の行を別々に、指定された確率に従って、選択あるいは無視します。 SYSTEMではブロックレベルのサンプリングを行います。 各ブロックは指定された確率で選択され、選択されたブロック内のすべての行が返されます。 サンプリングに小さな割合が指定された場合、SYSTEMBERNOULLIよりもかなり高速ですが、クラスタリング効果により、BERNOULLIに比べてランダムでないサンプルを返すかもしれません。

The optional <literal>REPEATABLE</literal> clause specifies a <replaceable class="parameter">seed</replaceable> number or expression to use for generating random numbers within the sampling method. The seed value can be any non-null floating-point value. Two queries that specify the same seed and <replaceable class="parameter">argument</replaceable> values will select the same sample of the table, if the table has not been changed meanwhile. But different seed values will usually produce different samples. If <literal>REPEATABLE</literal> is not given then a new random sample is selected for each query, based upon a system-generated seed. Note that some add-on sampling methods do not accept <literal>REPEATABLE</literal>, and will always produce new samples on each use. 省略可能なREPEATABLE句では、サンプリングメソッドで乱数を生成するためのseedの数あるいは式を指定します。 シード値はNULL以外の任意の浮動点小数値とすることができます。 シードとargumentの値が同じ2つの問い合わせは、その間にテーブルに変更がなければ、同じサンプルテーブルを返します。 しかし、シードの値が異なれば、通常は異なるサンプルが生成されます。 REPEATABLEが指定されていなければ、システムが生成したシードに基づいて、問い合わせ毎に新しくランダムなサンプルが生成されます。 一部のアドオンのサンプリングメソッドではREPEATABLEが利用できず、使用の度に常に新しいサンプルを生成することに注意してください。

select

A sub-<command>SELECT</command> can appear in the <literal>FROM</literal> clause. This acts as though its output were created as a temporary table for the duration of this single <command>SELECT</command> command. Note that the sub-<command>SELECT</command> must be surrounded by parentheses, and an alias can be provided in the same way as for a table. A <link linkend="sql-values"><command>VALUES</command></link> command can also be used here. FROM句では、副SELECTを使うことができます。 SELECTコマンドの実行中、副SELECTの出力は一時テーブルであるかのように動作します。 副SELECTは括弧で囲まれなければなりません。また、テーブルと同じようにして別名を与えることができます。 VALUESコマンドをここで使用することもできます。

with_query_name

A <literal>WITH</literal> query is referenced by writing its name, just as though the query's name were a table name. (In fact, the <literal>WITH</literal> query hides any real table of the same name for the purposes of the primary query. If necessary, you can refer to a real table of the same name by schema-qualifying the table's name.) An alias can be provided in the same way as for a table. WITH問い合わせは、問い合わせの名前があたかもテーブル名であるかのように、名前を記述することで参照されます。 (実際にはWITH問い合わせは主問い合わせの対象とするテーブルと同じ名前の実テーブルを隠蔽します。 必要ならばテーブル名をスキーマ修飾することで同じ名前の実テーブルを参照することができます。) テーブルと同様の方法で別名を提供することができます。

function_name

Function calls can appear in the <literal>FROM</literal> clause. (This is especially useful for functions that return result sets, but any function can be used.) This acts as though the function's output were created as a temporary table for the duration of this single <command>SELECT</command> command. If the function's result type is composite (including the case of a function with multiple <literal>OUT</literal> parameters), each attribute becomes a separate column in the implicit table. FROM句では、関数呼び出しを使用できます。 (これは特に関数が結果セットを返す場合に有用ですが、任意の関数を使用できます。) SELECTコマンドの実行中は、この関数の出力は一時テーブルであるかのように動作します。 関数の結果型が(複数のOUTパラメータを持つ関数の場合を含む)複合型なら、各属性はその暗黙のテーブルの別々の列になります。

When the optional <command>WITH ORDINALITY</command> clause is added to the function call, an additional column of type <type>bigint</type> will be appended to the function's result column(s). This column numbers the rows of the function's result set, starting from 1. By default, this column is named <literal>ordinality</literal>. 関数呼び出しに省略可能なWITH ORDINALITY句を追加した時は、bigint型の追加の列が関数の結果列に追加されます。 この列は関数の結果セットの行に1から始まる番号を付けます。 デフォルトでは、この列はordinalityという名前です。

An alias can be provided in the same way as for a table. If an alias is written, a column alias list can also be written to provide substitute names for one or more attributes of the function's composite return type, including the ordinality column if present. テーブルに対するのと同じように、別名を使用することができます。 別名が記述されていれば、列の別名リストを記述して、関数の複合型の戻り値の1つ以上の、存在する場合にはordinality列を含め、属性に対する代替名を提供することもできます。

Multiple function calls can be combined into a single <literal>FROM</literal>-clause item by surrounding them with <literal>ROWS FROM( ... )</literal>. The output of such an item is the concatenation of the first row from each function, then the second row from each function, etc. If some of the functions produce fewer rows than others, null values are substituted for the missing data, so that the total number of rows returned is always the same as for the function that produced the most rows. 複数の関数呼び出しをROWS FROM( ... )で括ることにより、1つのFROM句の項目にまとめることができます。 このような項目の出力は各関数の最初の行を結合した項目、次いで各関数の2番目の行、といった具合になります。 一部の関数が他の関数より少ない行数を出力した場合は、存在しないデータについてNULL値が代用され、戻される行数はいつでも最大の行数を返した関数と同じになります。

If the function has been defined as returning the <type>record</type> data type, then an alias or the key word <literal>AS</literal> must be present, followed by a column definition list in the form <literal>( <replaceable class="parameter">column_name</replaceable> <replaceable class="parameter">data_type</replaceable> <optional>, ... </optional>)</literal>. The column definition list must match the actual number and types of columns returned by the function. 関数がrecordデータ型を返すと定義されている場合は、別名すなわちASキーワードと、それに続くcolumn_name data_type [, ... ])という形式の列定義リストが必要です。 列定義リストは、関数によって返される実際の列の数およびデータ型に一致していなければなりません。

When using the <literal>ROWS FROM( ... )</literal> syntax, if one of the functions requires a column definition list, it's preferred to put the column definition list after the function call inside <literal>ROWS FROM( ... )</literal>. A column definition list can be placed after the <literal>ROWS FROM( ... )</literal> construct only if there's just a single function and no <literal>WITH ORDINALITY</literal> clause. ROWS FROM( ... )の構文を使う時、関数の1つが列定義のリストを必要としている場合は、ROWS FROM( ... )内の関数呼び出しの後に列定義のリストを置くのが望ましいです。 関数が1つだけで、WITH ORDINALITY句がない場合に限り、列定義のリストをROWS FROM( ... )の後に置くことができます。

To use <literal>ORDINALITY</literal> together with a column definition list, you must use the <literal>ROWS FROM( ... )</literal> syntax and put the column definition list inside <literal>ROWS FROM( ... )</literal>. ORDINALITYを列定義のリストと一緒に使うには、ROWS FROM( ... )構文を使い、列定義のリストをROWS FROM( ... )の内側に置かなければなりません。

join_type

One of 以下のいずれかです。

  • [ INNER ] JOIN

  • LEFT [ OUTER ] JOIN

  • RIGHT [ OUTER ] JOIN

  • FULL [ OUTER ] JOIN

For the <literal>INNER</literal> and <literal>OUTER</literal> join types, a join condition must be specified, namely exactly one of <literal>ON <replaceable class="parameter">join_condition</replaceable></literal>, <literal>USING (<replaceable class="parameter">join_column</replaceable> [, ...])</literal>, or <literal>NATURAL</literal>. See below for the meaning. INNERおよびOUTER結合型では、結合条件、すなわち、ON join_conditionUSING (join_column [, ...])NATURALのいずれか1つのみを指定する必要があります。 それぞれの意味は後述します。

A <literal>JOIN</literal> clause combines two <literal>FROM</literal> items, which for convenience we will refer to as <quote>tables</quote>, though in reality they can be any type of <literal>FROM</literal> item. Use parentheses if necessary to determine the order of nesting. In the absence of parentheses, <literal>JOIN</literal>s nest left-to-right. In any case <literal>JOIN</literal> binds more tightly than the commas separating <literal>FROM</literal>-list items. All the <literal>JOIN</literal> options are just a notational convenience, since they do nothing you couldn't do with plain <literal>FROM</literal> and <literal>WHERE</literal>. JOIN句は、2つのFROM項目を結び付けます。 便宜上テーブルと呼びますが、実際には任意の種類のFROM項目とすることができます。 入れ子の順番を決めるために、必要ならば括弧を使用してください。 括弧がないと、JOINは左から右へ入れ子にします。 どのような場合でもJOINは、カンマで分けられたFROM項目よりも強い結び付きを持ちます。 JOINオプションは記述上の便宜のためだけに用意されています。 なぜなら、通常のFROMWHEREでできないことは何もしないからです。

<para><literal>LEFT OUTER JOIN</literal> returns all rows in the qualified Cartesian product (i.e., all combined rows that pass its join condition), plus one copy of each row in the left-hand table for which there was no right-hand row that passed the join condition. This left-hand row is extended to the full width of the joined table by inserting null values for the right-hand columns. Note that only the <literal>JOIN</literal> clause's own condition is considered while deciding which rows have matches. Outer conditions are applied afterwards.

LEFT OUTER JOINは、条件に合う直積の全ての行(つまり、その結合条件を満たす全ての組み合わせ)に加え、左側テーブルの中で、右側テーブルには結合条件を満たす行が存在しなかった行のコピーも返します。 この左側テーブルの行を結合結果のテーブルの幅に拡張するために、右側テーブルが入る列にはNULL値が挿入されます。 マッチする行を決める時は、JOIN句自身の条件のみが考慮されることに注意してください。 外部結合条件は後で適用されます。

Conversely, <literal>RIGHT OUTER JOIN</literal> returns all the joined rows, plus one row for each unmatched right-hand row (extended with nulls on the left). This is just a notational convenience, since you could convert it to a <literal>LEFT OUTER JOIN</literal> by switching the left and right tables. 逆に、RIGHT OUTER JOINは、全ての結合行と、左側テーブルに当てはまるものがなかった右側の行(左側はNULLで拡張されています)の1行ずつを返します。 左右のテーブルを入れ替えればLEFT OUTER JOINに変換できるので、RIGHT OUTER JOINは記述上の便宜を図るため用意されているに過ぎません。

<para><literal>FULL OUTER JOIN</literal> returns all the joined rows, plus one row for each unmatched left-hand row (extended with nulls on the right), plus one row for each unmatched right-hand row (extended with nulls on the left).

FULL OUTER JOINは、全ての結合行に加え、一致しなかった左側の行(右側はNULLで拡張)、一致しなかった右側の行(左側はNULLで拡張)を全て返します。

ON join_condition
<para><replaceable class="parameter">join_condition</replaceable> is an expression resulting in a value of type <type>boolean</type> (similar to a <literal>WHERE</literal> clause) that specifies which rows in a join are considered to match.

join_conditionは、結合においてどの行が一致するかを指定する、boolean型の値を返す式です(WHERE句に類似しています)。

USING ( join_column [, ...] ) [ AS join_using_alias ]

A clause of the form <literal>USING ( a, b, ... )</literal> is shorthand for <literal>ON left_table.a = right_table.a AND left_table.b = right_table.b ...</literal>. Also, <literal>USING</literal> implies that only one of each pair of equivalent columns will be included in the join output, not both. USING ( a, b, ... )という形式の句はON left_table.a = right_table.a AND left_table.b = right_table.b ...の省略形です。 またUSINGは等価な列の両方ではなく片方のみが結合の出力に含まれることを意味します。

If a <replaceable class="parameter">join_using_alias</replaceable> name is specified, it provides a table alias for the join columns. Only the join columns listed in the <literal>USING</literal> clause are addressable by this name. Unlike a regular <replaceable class="parameter">alias</replaceable>, this does not hide the names of the joined tables from the rest of the query. Also unlike a regular <replaceable class="parameter">alias</replaceable>, you cannot write a column alias list &mdash; the output names of the join columns are the same as they appear in the <literal>USING</literal> list. join_using_alias名が指定されれば、結合列に対するテーブルの別名を提供します。 USING句に列挙されている結合列だけが、この名前で指定できます。 普通のaliasとは異なり、これは問い合わせの残りから結合されたテーブルの名前を隠しません。 また、普通のaliasとは異なり、列の別名リストを書くことはできません — 結合列の出力名はUSINGリストに現れるのと同じです。

NATURAL

<literal>NATURAL</literal> is shorthand for a <literal>USING</literal> list that mentions all columns in the two tables that have matching names. If there are no common column names, <literal>NATURAL</literal> is equivalent to <literal>ON TRUE</literal>. NATURALは、2つのテーブル内の同じ名前を持つ列を全て指定したUSINGリストの省略形です。 共通の列名がない場合、NATURALON TRUEと同等になります。

CROSS JOIN

<literal>CROSS JOIN</literal> is equivalent to <literal>INNER JOIN ON (TRUE)</literal>, that is, no rows are removed by qualification. They produce a simple Cartesian product, the same result as you get from listing the two tables at the top level of <literal>FROM</literal>, but restricted by the join condition (if any). CROSS JOININNER JOIN ON(TRUE)と同じです。 つまり、条件によって削除される行はありません。 これらは単純なデカルト積を生成します。 これは、FROMの最上位レベルにある2つのテーブルをリストした場合と同じ結果ですが、(存在すれば)結合条件によって制限されます。

LATERAL

The <literal>LATERAL</literal> key word can precede a sub-<command>SELECT</command> <literal>FROM</literal> item. This allows the sub-<command>SELECT</command> to refer to columns of <literal>FROM</literal> items that appear before it in the <literal>FROM</literal> list. (Without <literal>LATERAL</literal>, each sub-<command>SELECT</command> is evaluated independently and so cannot cross-reference any other <literal>FROM</literal> item.) LATERALキーワードを副SELECTFROM項目の前に付けることができます。 これにより、副SELECTFROMリストの中で前に現れるFROM項目の列を参照することができます。 (LATERALがないと、副SELECTそれぞれが個別に評価され、他のFROM項目とのクロス参照を行うことができません。)

<para><literal>LATERAL</literal> can also precede a function-call <literal>FROM</literal> item, but in this case it is a noise word, because the function expression can refer to earlier <literal>FROM</literal> items in any case.

LATERALを関数を呼び出すFROMの前に付けることもできます。 しかしこの場合、無意味な単語になります。 関数式はどのような場合でもより前のFROM項目を参照することができるからです。

A <literal>LATERAL</literal> item can appear at top level in the <literal>FROM</literal> list, or within a <literal>JOIN</literal> tree. In the latter case it can also refer to any items that are on the left-hand side of a <literal>JOIN</literal> that it is on the right-hand side of. LATERAL項目はFROMの最上位レベルやJOINツリー内に記述することができます。 後者の場合、JOINの右辺にあれば、左辺にある任意の項目を参照することができます。

When a <literal>FROM</literal> item contains <literal>LATERAL</literal> cross-references, evaluation proceeds as follows: for each row of the <literal>FROM</literal> item providing the cross-referenced column(s), or set of rows of multiple <literal>FROM</literal> items providing the columns, the <literal>LATERAL</literal> item is evaluated using that row or row set's values of the columns. The resulting row(s) are joined as usual with the rows they were computed from. This is repeated for each row or set of rows from the column source table(s). FROM項目がLATERALクロス参照を含む場合、評価は次のように行われます。 クロス参照される列を提供するFROM項目の各行、または、その列を提供する複数のFROM項目の行集合に対して、 LATERAL項目は列の行または行集合を使用して評価されます。 結果となる行は、計算された行と通常通り結合されます。 これが各行または列ソーステーブルからの行集合に対して繰り返されます。

The column source table(s) must be <literal>INNER</literal> or <literal>LEFT</literal> joined to the <literal>LATERAL</literal> item, else there would not be a well-defined set of rows from which to compute each set of rows for the <literal>LATERAL</literal> item. Thus, although a construct such as <literal><replaceable>X</replaceable> RIGHT JOIN LATERAL <replaceable>Y</replaceable></literal> is syntactically valid, it is not actually allowed for <replaceable>Y</replaceable> to reference <replaceable>X</replaceable>. 列ソーステーブルはLATERAL項目とINNERまたはLEFT結合されていなければなりません。 さもないと、 LATERAL項目において各行集合を計算するための行集合が完全に定義することができません。 したがってX RIGHT JOIN LATERAL Yという式は構文としては有効ですが、実際にはYではXを参照することができません。

<refsect2 id="sql-where" xreflabel="WHERE Clause">

WHERE

<title><literal>WHERE</literal> Clause</title>

The optional <literal>WHERE</literal> clause has the general form WHERE句の一般的な構文は以下の通りです(この句は省略可能です)。

WHERE condition

where <replaceable class="parameter">condition</replaceable> is any expression that evaluates to a result of type <type>boolean</type>. Any row that does not satisfy this condition will be eliminated from the output. A row satisfies the condition if it returns true when the actual row values are substituted for any variable references. conditionは、評価の結果としてboolean型を返す任意の式です。 この条件を満たさない行は全て出力から取り除かれます。 全ての変数に実際の行の値を代入して、式が真を返す場合、その行は条件を満たすとみなされます。

<refsect2 id="sql-groupby" xreflabel="GROUP BY Clause">

GROUP BY

<title><literal>GROUP BY</literal> Clause</title>

The optional <literal>GROUP BY</literal> clause has the general form GROUP BY句の一般的な構文は以下の通りです(この句は省略可能です)。

GROUP BY [ ALL | DISTINCT ] grouping_element [, ...]

<literal>GROUP BY</literal> will condense into a single row all selected rows that share the same values for the grouped expressions. An <replaceable class="parameter">expression</replaceable> used inside a <replaceable class="parameter">grouping_element</replaceable> can be an input column name, or the name or ordinal number of an output column (<command>SELECT</command> list item), or an arbitrary expression formed from input-column values. In case of ambiguity, a <literal>GROUP BY</literal> name will be interpreted as an input-column name rather than an output column name. GROUP BYは、グループ化のために与えられた式を評価し、結果が同じ値になった行を1つの行にまとめる機能を持ちます。 grouping_elementの内側で使われるexpressionには、入力列の名前、出力列(SELECTリスト項目)の名前/序数、あるいは入力列の値から計算される任意の式を取ることができます。 判断がつかない時は、GROUP BYの名前は出力列名ではなく入力列名として解釈されます。

If any of <literal>GROUPING SETS</literal>, <literal>ROLLUP</literal> or <literal>CUBE</literal> are present as grouping elements, then the <literal>GROUP BY</literal> clause as a whole defines some number of independent <replaceable>grouping sets</replaceable>. The effect of this is equivalent to constructing a <literal>UNION ALL</literal> between subqueries with the individual grouping sets as their <literal>GROUP BY</literal> clauses. The optional <literal>DISTINCT</literal> clause removes duplicate sets before processing; it does <emphasis>not</emphasis> transform the <literal>UNION ALL</literal> into a <literal>UNION DISTINCT</literal>. For further details on the handling of grouping sets see <xref linkend="queries-grouping-sets"/>. グループ化の要素としてGROUPING SETSROLLUPCUBEのいずれかが指定されている場合、GROUP BY句は全体でいくつかの独立したグループ化セットを定義します。 この効果は、個々のグループ化セットをGROUP BY句で定義する副問い合わせをUNION ALLするのと同等です。 省略可能なDISTINCT句では処理の前に重複するセットを削除します。UNION ALLUNION DISTINCTに変換はしません。 グループ化セットの処理の詳細については、7.2.4を参照してください。

Aggregate functions, if any are used, are computed across all rows making up each group, producing a separate value for each group. (If there are aggregate functions but no <literal>GROUP BY</literal> clause, the query is treated as having a single group comprising all the selected rows.) The set of rows fed to each aggregate function can be further filtered by attaching a <literal>FILTER</literal> clause to the aggregate function call; see <xref linkend="syntax-aggregates"/> for more information. When a <literal>FILTER</literal> clause is present, only those rows matching it are included in the input to that aggregate function. 集約関数が使用された場合、各グループ内の全ての行を対象に計算が行われ、グループごとに別々の値が生成されます (集約関数が使われていてGROUP BYがない場合、その問い合わせは選択された全ての行からなる1つのグループを持つものとして扱われます)。 集約関数の入力となる行の集合は、集約関数の呼び出しにFILTER句を付けることで、さらに絞り込むことができます。 詳しくは4.2.7を参照してください。 FILTER句があると、その条件に適合する行だけが集約関数の入力行に取り込まれます。

When <literal>GROUP BY</literal> is present, or any aggregate functions are present, it is not valid for the <command>SELECT</command> list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column. GROUP BYが存在する場合、あるいは集約関数が存在する場合、集約関数内部以外で、グループ化されていない列を参照する、あるいはグループ化されていない列がグループ化された列に関数依存するSELECTリストの式は無効になります。 こうしないとグループ化されていない列について返される値は複数の値になってしまう可能性があるからです。 グループ化された列(またはその部分集合)がグループ化されていない列を含むテーブルの主キーである場合、関数従属性が存在します。

Keep in mind that all aggregate functions are evaluated before evaluating any <quote>scalar</quote> expressions in the <literal>HAVING</literal> clause or <literal>SELECT</literal> list. This means that, for example, a <literal>CASE</literal> expression cannot be used to skip evaluation of an aggregate function; see <xref linkend="syntax-express-eval"/>. すべての集約関数は、HAVING句やSELECTリストのどのスカラー式よりも先に評価されることに注意してください。 これは例えば、CASE式を集約関数の評価をスキップするために使うことはできない、ということを意味します。 4.2.14を参照してください。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified with <literal>GROUP BY</literal>. 現在は、FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHAREGROUP BYと合わせて使うことはできません。

<refsect2 id="sql-having" xreflabel="HAVING Clause">

HAVING

<title><literal>HAVING</literal> Clause</title>

The optional <literal>HAVING</literal> clause has the general form HAVING句の一般的な構文は以下の通りです(この句は省略可能です)。

HAVING condition

where <replaceable class="parameter">condition</replaceable> is the same as specified for the <literal>WHERE</literal> clause. conditionWHERE句で指定するものと同じです。

<literal>HAVING</literal> eliminates group rows that do not satisfy the condition. <literal>HAVING</literal> is different from <literal>WHERE</literal>: <literal>WHERE</literal> filters individual rows before the application of <literal>GROUP BY</literal>, while <literal>HAVING</literal> filters group rows created by <literal>GROUP BY</literal>. Each column referenced in <replaceable class="parameter">condition</replaceable> must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns. HAVINGは、グループ化された行の中で、条件を満たさない行を取り除く機能を持ちます。 HAVINGWHEREは次の点が異なります。 WHEREが、GROUP BYの適用前に個々の行に対してフィルタを掛けるのに対し、HAVINGは、GROUP BYの適用後に生成されたグループ化された行に対してフィルタをかけます。 condition内で使用する列は、集約関数内で使用される場合とグループ化されない列がグループ化される列に関数依存する場合を除き、グループ化された列を一意に参照するものでなければなりません。

The presence of <literal>HAVING</literal> turns a query into a grouped query even if there is no <literal>GROUP BY</literal> clause. This is the same as what happens when the query contains aggregate functions but no <literal>GROUP BY</literal> clause. All the selected rows are considered to form a single group, and the <command>SELECT</command> list and <literal>HAVING</literal> clause can only reference table columns from within aggregate functions. Such a query will emit a single row if the <literal>HAVING</literal> condition is true, zero rows if it is not true. HAVING句があると、GROUP BY句がなかったとしても問い合わせはグループ化された問い合わせになります。 GROUP BY句を持たない問い合わせが集約関数を含む場合と同様です。 選択された行はすべて、1つのグループを形成するものとみなされます。また、SELECTリストとHAVING句では、集約関数が出力するテーブル列しか参照することができません。 こうした問い合わせでは、HAVINGが真の場合には単一の行を、真以外の場合は0行を出力します。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified with <literal>HAVING</literal>. 現在は、FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHAREHAVINGと合わせて使うことはできません。

<refsect2 id="sql-window" xreflabel="WINDOW Clause">

WINDOW

<title><literal>WINDOW</literal> Clause</title>

The optional <literal>WINDOW</literal> clause has the general form WINDOW句の一般的な構文は以下の通りです(この句は省略可能です)。

WINDOW window_name AS ( window_definition ) [, ...]

where <replaceable class="parameter">window_name</replaceable> is a name that can be referenced from <literal>OVER</literal> clauses or subsequent window definitions, and <replaceable class="parameter">window_definition</replaceable> is ここでwindow_nameは、OVER句やこの後のウィンドウ定義で参照することができる名前です。 また、window_definitionは以下の通りです。

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

If an <replaceable class="parameter">existing_window_name</replaceable> is specified it must refer to an earlier entry in the <literal>WINDOW</literal> list; the new window copies its partitioning clause from that entry, as well as its ordering clause if any. In this case the new window cannot specify its own <literal>PARTITION BY</literal> clause, and it can specify <literal>ORDER BY</literal> only if the copied window does not have one. The new window always uses its own frame clause; the copied window must not specify a frame clause. existing_window_nameを指定する場合、それはWINDOWリスト内のそれより前にある項目を参照しなければなりません。 新しいウィンドウはそのPARTITION BY句をその項目からコピーします。 ORDER BY句があった場合も同様です。 この場合、新しいウィンドウでは独自のPARTITION BY句を指定することはできません。 また、コピーされたウィンドウがORDER BYを持たない場合のみORDER BYを指定することができます。 新しいウィンドウは常に独自のフレーム句を使用します。 コピーされたウィンドウはフレーム句を指定してはなりません。

The elements of the <literal>PARTITION BY</literal> list are interpreted in much the same fashion as elements of a <link linkend="sql-groupby"><literal>GROUP BY</literal></link> clause, except that they are always simple expressions and never the name or number of an output column. Another difference is that these expressions can contain aggregate function calls, which are not allowed in a regular <literal>GROUP BY</literal> clause. They are allowed here because windowing occurs after grouping and aggregation. PARTITION BYリストの要素はGROUP BY句の要素とほとんど同じように解釈されます。 ただし、こちらは常に単純な式であり、出力列の名前や番号ではないことが異なります。 他にも違いがあり、これらの式は、通常のGROUP BY句では許されない、集約関数を含めることができるという点です。 グループ化および集約処理の後にウィンドウ処理が動作するため、これらでは許されています。

Similarly, the elements of the <literal>ORDER BY</literal> list are interpreted in much the same fashion as elements of a statement-level <link linkend="sql-orderby"><literal>ORDER BY</literal></link> clause, except that the expressions are always taken as simple expressions and never the name or number of an output column. 同様に、ORDER BYリストの要素は文レベルのORDER BY句の要素とほとんど同じように解釈されます。 ただし、この式は常に単純な式であり、出力列の名前や番号ではないことが異なります。

The optional <replaceable class="parameter">frame_clause</replaceable> defines the <firstterm>window frame</firstterm> for window functions that depend on the frame (not all do). The window frame is a set of related rows for each row of the query (called the <firstterm>current row</firstterm>). The <replaceable class="parameter">frame_clause</replaceable> can be one of frame_clauseを指定すると、(すべてではありませんが)フレームに依存するウィンドウ関数用のウィンドウフレームを定義できます。 ウィンドウフレームは、問い合わせの各行(現在の行と呼ばれます)に関連する行の集合です。 frame_clauseは以下のいずれかを取ることができます。

{ 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_startframe_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

If <replaceable>frame_end</replaceable> is omitted it defaults to <literal>CURRENT ROW</literal>. 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. frame_endが省略された場合、デフォルトでCURRENT ROWとなります。 frame_startUNBOUNDED FOLLOWINGとすることができない、frame_endUNBOUNDED PRECEDINGとすることができない、また、frame_startframe_endのオプションの上記リストでframe_endの選択をframe_startの選択よりも手前に現れるものにはできない、という制限があります。 例えばRANGE BETWEEN CURRENT ROW AND offset PRECEDINGは許されません。

The default framing option is <literal>RANGE UNBOUNDED PRECEDING</literal>, which is the same as <literal>RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW</literal>; it sets the frame to be all rows from the partition start up through the current row's last <firstterm>peer</firstterm> (a row that the window's <literal>ORDER BY</literal> clause considers equivalent to the current row; all rows are peers if there is no <literal>ORDER BY</literal>). In general, <literal>UNBOUNDED PRECEDING</literal> means that the frame starts with the first row of the partition, and similarly <literal>UNBOUNDED FOLLOWING</literal> means that the frame ends with the last row of the partition, regardless of <literal>RANGE</literal>, <literal>ROWS</literal> or <literal>GROUPS</literal> mode. In <literal>ROWS</literal> mode, <literal>CURRENT ROW</literal> means that the frame starts or ends with the current row; but in <literal>RANGE</literal> or <literal>GROUPS</literal> mode it means that the frame starts or ends with the current row's first or last peer in the <literal>ORDER BY</literal> ordering. The <replaceable>offset</replaceable> <literal>PRECEDING</literal> and <replaceable>offset</replaceable> <literal>FOLLOWING</literal> options vary in meaning depending on the frame mode. In <literal>ROWS</literal> mode, the <replaceable>offset</replaceable> is an integer indicating that the frame starts or ends that many rows before or after the current row. In <literal>GROUPS</literal> mode, the <replaceable>offset</replaceable> is an integer indicating that the frame starts or ends that many peer groups before or after the current row's peer group, where a <firstterm>peer group</firstterm> is a group of rows that are equivalent according to the window's <literal>ORDER BY</literal> clause. In <literal>RANGE</literal> mode, use of an <replaceable>offset</replaceable> option requires that there be exactly one <literal>ORDER BY</literal> column in the window definition. Then the frame contains those rows whose ordering column value is no more than <replaceable>offset</replaceable> less than (for <literal>PRECEDING</literal>) or more than (for <literal>FOLLOWING</literal>) the current row's ordering column value. In these cases the data type of the <replaceable>offset</replaceable> expression depends 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>. In all these cases, the value of the <replaceable>offset</replaceable> must be non-null and non-negative. Also, while the <replaceable>offset</replaceable> does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions. デフォルトのフレーム化オプションはRANGE UNBOUNDED PRECEDINGです。 これはRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROWと同じで、 パーティションの先頭から現在の行の最後のピア(ウィンドウのORDER BY句が現在行と同等とみなす行、ORDER BYが無ければ全ての行がピア)までのすべての行をフレームとします。 一般的に、RANGEROWSGROUPSのモードにかかわらず、UNBOUNDED PRECEDINGはフレームがパーティションの先頭行から開始することを意味し、同様にUNBOUNDED FOLLOWINGはフレームがパーティションの最終行で終了することを意味します。 ROWSモードではCURRENT ROWはフレームが現在の行で開始または終了することを意味しますが、RANGEあるいはGROUPSモードではフレームがORDER BY順序における現在行の最初または最後のピアで開始または終了することを意味します。 offset PRECEDINGおよびoffset FOLLOWINGオプションの意味はフレームのモードによって異なります。 ROWSモードでは、offsetはフレームが現在行の何行前または何行後に開始または終了するかを示す整数です。 GROUPSモードでは、offsetはフレームが現在行のピアグループからピアグループ何個、前または後で開始または終了するかを示す整数です。 ここでピアグループとはウィンドウのORDER BY句において等価の行のグループです。 RANGEモードでは、offsetオプションを使うには、ウィンドウ定義に一つだけORDER BY列があることが必要です。 それで、整列する列の値がoffsetを超えないだけ、現在行の整列する列の値より小さい(PRECEDINGに対して)、あるいは、より大きい(FOLLOWINGに対して)行がフレームに含まれます。 この場合、offset式のデータ型は整列する列のデータ型によって決まります。 数値の整列する列に対するoffsetは一般的に整列する列と同じ型ですが、日付時刻の整列する列に対してはintervalになります。 これら全ての場合で、offsetの値は非NULLかつ非負でなければなりません。 また、offsetが単純な定数である必要はありませんが、変数や集約関数、ウィンドウ関数を含めることはできません。

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は単に、現在行もそのピアも除外しないというデフォルトの振る舞いを明示的に指定します。

Beware that the <literal>ROWS</literal> mode can produce unpredictable results if the <literal>ORDER BY</literal> ordering does not order the rows uniquely. The <literal>RANGE</literal> and <literal>GROUPS</literal> modes are designed to ensure that rows that are peers in the <literal>ORDER BY</literal> ordering are treated alike: all rows of a given peer group will be in the frame or excluded from it. ORDER BY順序によりその行を一意に順序付けできない場合、ROWSモードが予期できない結果をもたらす可能性があることに注意して下さい。 RANGEおよびGROUPSモードは、ORDER BY順序におけるピアとなる行が同等に扱われる、すなわち、与えられたピアグループの全行がフレームに入るか除外されるように設計されています。

The purpose of a <literal>WINDOW</literal> clause is to specify the behavior of <firstterm>window functions</firstterm> appearing in the query's <link linkend="sql-select-list"><command>SELECT</command> list</link> or <link linkend="sql-orderby"><literal>ORDER BY</literal></link> clause. These functions can reference the <literal>WINDOW</literal> clause entries by name in their <literal>OVER</literal> clauses. A <literal>WINDOW</literal> clause entry does not have to be referenced anywhere, however; if it is not used in the query it is simply ignored. It is possible to use window functions without any <literal>WINDOW</literal> clause at all, since a window function call can specify its window definition directly in its <literal>OVER</literal> clause. However, the <literal>WINDOW</literal> clause saves typing when the same window definition is needed for more than one window function. WINDOW句の目的は、問い合わせのSELECTリストまたはORDER BY句に記載されるウィンドウ関数の動作を規定することです。 これらの関数はそのOVER句において名前でWINDOW句の項目を参照することができます。 しかしWINDOW句の項目は他で参照される必要はありません。 問い合わせ内で使用されなかったものは、単に無視されます。 ウィンドウ関数呼び出しはOVER句でウィンドウ定義を直接規定することができますので、WINDOW句を全く使わずにウィンドウ関数を使用することができます。 しかしWINDOW句は、同じウィンドウ定義が複数のウィンドウ関数で必要とされる場合に入力量を省くことができます。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified with <literal>WINDOW</literal>. 現在は、FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHAREWINDOWと合わせて使うことはできません。

Window functions are described in detail in <xref linkend="tutorial-window"/>, <xref linkend="syntax-window-functions"/>, and <xref linkend="queries-window"/>. ウィンドウ関数に関する詳細については3.54.2.87.2.5を参照してください。

<refsect2 id="sql-select-list" xreflabel="SELECT List">

SELECTリスト

<title><command>SELECT</command> List</title>

The <command>SELECT</command> list (between the key words <literal>SELECT</literal> and <literal>FROM</literal>) specifies expressions that form the output rows of the <command>SELECT</command> statement. The expressions can (and usually do) refer to columns computed in the <literal>FROM</literal> clause. SELECTリスト(SELECTキーワードとFROMキーワードの間にあるもの)は、SELECT文の出力行を形成する式を指定するものです。 この式では、FROM句で処理後の列を参照することができます(通常は実際に参照します)。

Just as in a table, every output column of a <command>SELECT</command> has a name. In a simple <command>SELECT</command> this name is just used to label the column for display, but when the <command>SELECT</command> is a sub-query of a larger query, the name is seen by the larger query as the column name of the virtual table produced by the sub-query. To specify the name to use for an output column, write <literal>AS</literal> <replaceable class="parameter">output_name</replaceable> after the column's expression. (You can omit <literal>AS</literal>, but only if the desired output name does not match any <productname>PostgreSQL</productname> keyword (see <xref linkend="sql-keywords-appendix"/>). For protection against possible future keyword additions, it is recommended that you always either write <literal>AS</literal> or double-quote the output name.) If you do not specify a column name, a name is chosen automatically by <productname>PostgreSQL</productname>. If the column's expression is a simple column reference then the chosen name is the same as that column's name. In more complex cases a function or type name may be used, or the system may fall back on a generated name such as <literal>?column?</literal>. テーブルの場合と同様に、SELECTの出力列はすべて名前を持ちます。 簡単なSELECTでは、この名前は列に表示用のラベルを付けるために使用されるだけです。 しかしSELECTが大規模な問い合わせの副問い合わせである場合、大規模な問い合わせ側で副問い合わせで生成された仮想のテーブルの列名としてこの名前が参照されます。 出力列として使用するための名前を指定するためには、列式の後にAS output_nameと記述してください。 (希望する列名がPostgreSQLのキーワード(付録Cを参照)に一致しない場合にのみASを省略することができます。 将来あり得るキーワードの追加に備えるために、常にASを記述する、あるいは、出力名を二重引用符で括ることを推奨します。) 列名を指定しない場合、名前はPostgreSQLにより自動的に付けられます。 列式が単純な列参照であれば、つけられる名前はその列の名前と同じものです。 より複雑な場合では、関数名または型名が使用されるかもしれません。さもなければ?column?のように生成される名前になるかもしれません。

An output column's name can be used to refer to the column's value in <literal>ORDER BY</literal> and <literal>GROUP BY</literal> clauses, but not in the <literal>WHERE</literal> or <literal>HAVING</literal> clauses; there you must write out the expression instead. ORDER BY句とGROUP BY句内で列の値を参照する時も、出力列名を使用できます。 しかし、WHEREHAVING句では使用できません。これらでは式を書かなければなりません。

Instead of an expression, <literal>*</literal> can be written in the output list as a shorthand for all the columns of the selected rows. Also, you can write <literal><replaceable class="parameter">table_name</replaceable>.*</literal> as a shorthand for the columns coming from just that table. In these cases it is not possible to specify new names with <literal>AS</literal>; the output column names will be the same as the table columns' names. リストには、選択された行の全ての列を表す省略形として、式ではなく*と書くことができます。 また、そのテーブルに由来する列のみを表す省略形として、table_name.*と書くこともできます。 このような場合、ASにより新しい名前を指定することはできません。 出力列名はテーブルの列名と同一になります。

According to the SQL standard, the expressions in the output list should be computed before applying <literal>DISTINCT</literal>, <literal>ORDER BY</literal>, or <literal>LIMIT</literal>. This is obviously necessary when using <literal>DISTINCT</literal>, since otherwise it's not clear what values are being made distinct. However, in many cases it is convenient if output expressions are computed after <literal>ORDER BY</literal> and <literal>LIMIT</literal>; particularly if the output list contains any volatile or expensive functions. With that behavior, the order of function evaluations is more intuitive and there will not be evaluations corresponding to rows that never appear in the output. <productname>PostgreSQL</productname> will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced in <literal>DISTINCT</literal>, <literal>ORDER BY</literal> or <literal>GROUP BY</literal>. (As a counterexample, <literal>SELECT f(x) FROM tab ORDER BY 1</literal> clearly must evaluate <function>f(x)</function> before sorting.) Output expressions that contain set-returning functions are effectively evaluated after sorting and before limiting, so that <literal>LIMIT</literal> will act to cut off the output from a set-returning function. 標準SQLによれば、出力リスト内の式は、DISTINCTORDER BYLIMITを適用する前に計算することになっています。 DISTINCTを使う場合は、これは明らかに必要です。 なぜなら、そうしなければどの値がDISTINCTであるかわからないからです。 しかし、多くの場合、ORDER BYLIMITの後で出力式を計算する方が便利です。 特に出力式が揮発性(volatile)あるいは高価な式を含んでいる場合はそうです。 この動作により、関数の評価順序はより直感的になり、出力に現れない行については評価されなくなります。 PostgreSQLでは、式がDISTINCTORDER BYGROUP BYの中で参照されていない限り、ソートと制限(limit)の後にそれらの式を実際に評価します。 (この反例として、SELECT f(x) FROM tab ORDER BY 1 では明らかにf(x)をソートの前に評価しなければなりません。) 集合を返す関数を含む出力式は、ソートの後、制限の前に実際の評価が行われ、これによりLIMITが集合を返す関数の出力を制限することになります。

注記

<productname>PostgreSQL</productname> versions before 9.6 did not provide any guarantees about the timing of evaluation of output expressions versus sorting and limiting; it depended on the form of the chosen query plan. PostgreSQLのバージョン9.6より前では、出力式がソートや制限に対して評価されるタイミングについて何の保証もしていませんでした。 それは選択された問い合わせの計画の形式に依存します。

<refsect2 id="sql-distinct" xreflabel="DISTINCT Clause">

DISTINCT

<title><literal>DISTINCT</literal> Clause</title>

If <literal>SELECT DISTINCT</literal> is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). <literal>SELECT ALL</literal> specifies the opposite: all rows are kept; that is the default. SELECT DISTINCTが指定されると、重複する行は全て結果セットから削除されます (重複するグループの中で1行が保持されます)。 SELECT ALLはこの反対で、全ての行が保持されます。 デフォルトはこちらです。

<literal>SELECT DISTINCT ON ( <replaceable class="parameter">expression</replaceable> [, ...] )</literal> keeps only the first row of each set of rows where the given expressions evaluate to equal. The <literal>DISTINCT ON</literal> expressions are interpreted using the same rules as for <literal>ORDER BY</literal> (see above). Note that the <quote>first row</quote> of each set is unpredictable unless <literal>ORDER BY</literal> is used to ensure that the desired row appears first. For example: SELECT DISTINCT ON ( expression [, ...] )は指定した式が等しいと評価した各行集合の中で、最初の行のみを保持します。 DISTINCT ON式は、ORDER BY(上述)と同じ規則で扱われます。 各集合の最初の行は、ORDER BYを使用して目的の行が確実に最初に現れるようにしない限り予測することはできないことに注意してください。 例えば、次の例は各地点の最新の気象情報を取り出します。

SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;

retrieves the most recent weather report for each location. But if we had not used <literal>ORDER BY</literal> to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location. しかしORDER BYを使用して各地点を時間によって降順にソートしなければ、各地点について得られる情報がいつのものかはわかりません。

The <literal>DISTINCT ON</literal> expression(s) must match the leftmost <literal>ORDER BY</literal> expression(s). The <literal>ORDER BY</literal> clause will normally contain additional expression(s) that determine the desired precedence of rows within each <literal>DISTINCT ON</literal> group. DISTINCT ONに指定する式はORDER BYの最も左側の式と一致しなければなりません。 ORDER BY句は、通常、各DISTINCT ONグループの中での行の優先順位を決定する追加的な式を含みます。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified with <literal>DISTINCT</literal>. 現在は、FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHAREDISTINCTと合わせて使うことはできません。

<refsect2 id="sql-union" xreflabel="UNION Clause">

UNION

<title><literal>UNION</literal> Clause</title>

The <literal>UNION</literal> clause has this general form: UNION句の一般的な構文は以下の通りです。

select_statement UNION [ ALL | DISTINCT ] select_statement

</synopsis><replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>,
    <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause.
    (<literal>ORDER BY</literal> and <literal>LIMIT</literal> can be attached to a
    subexpression if it is enclosed in parentheses.  Without
    parentheses, these clauses will be taken to apply to the result of
    the <literal>UNION</literal>, not to its right-hand input
    expression.)

select_statementには、ORDER BYLIMITFOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHARE句を持たない任意のSELECT文が入ります (ORDER BYLIMITは、括弧で囲めば副式として付与することができます。 括弧がない場合、これらの句は右側に置かれた入力式ではなく、UNIONの結果に対して適用されてしまいます)。

The <literal>UNION</literal> operator computes the set union of the rows returned by the involved <command>SELECT</command> statements. A row is in the set union of two result sets if it appears in at least one of the result sets. The two <command>SELECT</command> statements that represent the direct operands of the <literal>UNION</literal> must produce the same number of columns, and corresponding columns must be of compatible data types. UNION演算子は、2つのSELECT文が返す行の和集合を作成します。 この和集合には、2つのSELECT文の結果集合のいずれか(または両方)に存在する行が全て含まれています。 UNIONの直接のオペランドとなる2つのSELECT文が返す列数は、同じでなければなりません。また、対応する列のデータ型には互換性が存在する必要があります。

The result of <literal>UNION</literal> does not contain any duplicate rows unless the <literal>ALL</literal> option is specified. <literal>ALL</literal> prevents elimination of duplicates. (Therefore, <literal>UNION ALL</literal> is usually significantly quicker than <literal>UNION</literal>; use <literal>ALL</literal> when you can.) <literal>DISTINCT</literal> can be written to explicitly specify the default behavior of eliminating duplicate rows. ALLオプションが指定されていない限り、UNIONの結果には重複行は含まれません。 ALLを指定するとこのような重複除去が行われません (したがって、通常UNION ALLUNIONよりかなり高速です。 できればALLを使用してください)。 重複行を除去するデフォルトの動作を明示的に指定するためにDISTINCTを記述することができます。

Multiple <literal>UNION</literal> operators in the same <command>SELECT</command> statement are evaluated left to right, unless otherwise indicated by parentheses. 1つのSELECT文に複数のUNION演算子がある場合、括弧がない限り、それらは左から右に評価されます。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified either for a <literal>UNION</literal> result or for any input of a <literal>UNION</literal>. 現時点では、UNIONの結果やUNIONに対する入力に、FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHAREを指定することはできません。

<refsect2 id="sql-intersect" xreflabel="INTERSECT Clause">

INTERSECT

<title><literal>INTERSECT</literal> Clause</title>

The <literal>INTERSECT</literal> clause has this general form: INTERSECT句の一般的な構文は以下の通りです。

select_statement INTERSECT [ ALL | DISTINCT ] select_statement

</synopsis><replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>,
    <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause.

select_statementには、ORDER BYLIMITFOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHARE句を持たない、任意のSELECT文が入ります。

The <literal>INTERSECT</literal> operator computes the set intersection of the rows returned by the involved <command>SELECT</command> statements. A row is in the intersection of two result sets if it appears in both result sets. INTERSECTは、2つのSELECT文が返す行の積集合を計算します。 この積集合に含まれるのは、2つのSELECT文の結果集合の両方に存在する行です。

The result of <literal>INTERSECT</literal> does not contain any duplicate rows unless the <literal>ALL</literal> option is specified. With <literal>ALL</literal>, a row that has <replaceable>m</replaceable> duplicates in the left table and <replaceable>n</replaceable> duplicates in the right table will appear min(<replaceable>m</replaceable>,<replaceable>n</replaceable>) times in the result set. <literal>DISTINCT</literal> can be written to explicitly specify the default behavior of eliminating duplicate rows. ALLオプションを指定しない限り、INTERSECTの結果に重複行は含まれません。 ALLが指定された場合、左側テーブルにm個、右側テーブルにn個の重複がある行は、結果集合ではmin(m,n)個出現します。 重複行を除去するデフォルトの動作を明示的に指定するためにDISTINCTを記述することができます。

Multiple <literal>INTERSECT</literal> operators in the same <command>SELECT</command> statement are evaluated left to right, unless parentheses dictate otherwise. <literal>INTERSECT</literal> binds more tightly than <literal>UNION</literal>. That is, <literal>A UNION B INTERSECT C</literal> will be read as <literal>A UNION (B INTERSECT C)</literal>. 1つのSELECT文に複数のINTERSECT演算子がある場合、括弧がない限り、それらは左から右に評価されます。 INTERSECTUNIONよりも強い結び付きを持ちます。 つまり、A UNION B INTERSECT CA UNION (B INTERSECT C)と解釈されます。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified either for an <literal>INTERSECT</literal> result or for any input of an <literal>INTERSECT</literal>. 現時点では、INTERSECTの結果やINTERSECTに対する入力に、FOR NO KEY UPDATEFOR UPDATEFOR SHAREまたはFOR KEY SHAREを指定することはできません。

<refsect2 id="sql-except" xreflabel="EXCEPT Clause">

EXCEPT

<title><literal>EXCEPT</literal> Clause</title>

The <literal>EXCEPT</literal> clause has this general form: EXCEPT句の一般的な構文は以下の通りです。

select_statement EXCEPT [ ALL | DISTINCT ] select_statement

</synopsis><replaceable class="parameter">select_statement</replaceable> is
    any <command>SELECT</command> statement without an <literal>ORDER
    BY</literal>, <literal>LIMIT</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>,
    <literal>FOR SHARE</literal>, or <literal>FOR KEY SHARE</literal> clause.

select_statementには、ORDER BYLIMITFOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHARE句を持たない、任意のSELECT文が入ります。

The <literal>EXCEPT</literal> operator computes the set of rows that are in the result of the left <command>SELECT</command> statement but not in the result of the right one. EXCEPTは、左側のSELECT文の結果には存在し、右側のSELECT文の結果には存在しない行の集合を生成します。

The result of <literal>EXCEPT</literal> does not contain any duplicate rows unless the <literal>ALL</literal> option is specified. With <literal>ALL</literal>, a row that has <replaceable>m</replaceable> duplicates in the left table and <replaceable>n</replaceable> duplicates in the right table will appear max(<replaceable>m</replaceable>-<replaceable>n</replaceable>,0) times in the result set. <literal>DISTINCT</literal> can be written to explicitly specify the default behavior of eliminating duplicate rows. ALLオプションが指定されていない限り、EXCEPTの結果には重複行は含まれません。 ALLがある場合、左側テーブルにm個、右側テーブルにn個の重複がある行は、結果集合ではmax(m-n,0)個出現します。 重複行を除去するデフォルトの動作を明示的に指定するためにDISTINCTを記述することができます。

Multiple <literal>EXCEPT</literal> operators in the same <command>SELECT</command> statement are evaluated left to right, unless parentheses dictate otherwise. <literal>EXCEPT</literal> binds at the same level as <literal>UNION</literal>. 1つのSELECT文に複数のEXCEPT演算子がある場合、括弧がない限り、それらは左から右に評価されます。 EXCEPTの結び付きの強さはUNIONと同じです。

Currently, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> cannot be specified either for an <literal>EXCEPT</literal> result or for any input of an <literal>EXCEPT</literal>. 現時点では、EXCEPTの結果やEXCEPTに対する入力に、FOR NO KEY UPDATEFOR UPDATEFOR SHAREまたはFOR KEY SHAREを指定することはできません。

<refsect2 id="sql-orderby" xreflabel="ORDER BY Clause">

ORDER BY

<title><literal>ORDER BY</literal> Clause</title>

The optional <literal>ORDER BY</literal> clause has this general form: ORDER BY句の一般的な構文は以下の通りです(この句は省略可能です)。

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

The <literal>ORDER BY</literal> clause causes the result rows to be sorted according to the specified expression(s). If two rows are equal according to the leftmost expression, they are compared according to the next expression and so on. If they are equal according to all specified expressions, they are returned in an implementation-dependent order. ORDER BY句を使うと、結果行を指定した式(複数可)に従ってソートすることができます。 最も左側の式を使って比較した結果、2つの行が等しいと判断された場合は、1つ右側の式を使って比較します。その結果も等しければ、さらに次の式に進みます。 指定した全ての式で等しいと判断された場合は、実装に依存した順番で返されます。

Each <replaceable class="parameter">expression</replaceable> can be the name or ordinal number of an output column (<command>SELECT</command> list item), or it can be an arbitrary expression formed from input-column values. expressionには、出力列(SELECTリスト項目)の名前または序数、あるいは入力列値から形成される任意の式を取ることができます。

The ordinal number refers to the ordinal (left-to-right) position of the output column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it is always possible to assign a name to an output column using the <literal>AS</literal> clause. 序数は、出力列の位置(左から右に割り当てられます)を示します。 これを使うと、一意な名前を持たない列の順序を定義することができます。 AS句を使用すれば出力列に名前を割り当てることができるので、これはどうしても必要な機能というわけではありません。

It is also possible to use arbitrary expressions in the <literal>ORDER BY</literal> clause, including columns that do not appear in the <command>SELECT</command> output list. Thus the following statement is valid: また、ORDER BY句には、SELECT出力リストに出現しない列を含む、任意の式を使用できます。 したがって、以下の文は有効です。

SELECT name FROM distributors ORDER BY code;

A limitation of this feature is that an <literal>ORDER BY</literal> clause applying to the result of a <literal>UNION</literal>, <literal>INTERSECT</literal>, or <literal>EXCEPT</literal> clause can only specify an output column name or number, not an expression. ただし、UNIONINTERSECTEXCEPTの結果にORDER BYを適用する場合は、式は使用できず、出力列の名前か序数のみを指定できるという制限があります。

If an <literal>ORDER BY</literal> expression is a simple name that matches both an output column name and an input column name, <literal>ORDER BY</literal> will interpret it as the output column name. This is the opposite of the choice that <literal>GROUP BY</literal> will make in the same situation. This inconsistency is made to be compatible with the SQL standard. ORDER BYの式として出力列名と入力列名の両方に一致する単なる名前が与えられた場合、ORDER BYはそれを出力列名として扱います。 これは、同じ状況におけるGROUP BYの選択とは反対です。 この不整合は、標準SQLとの互換性を保持するために発生しています。

Optionally one can add the key word <literal>ASC</literal> (ascending) or <literal>DESC</literal> (descending) after any expression in the <literal>ORDER BY</literal> clause. If not specified, <literal>ASC</literal> is assumed by default. Alternatively, a specific ordering operator name can be specified in the <literal>USING</literal> clause. An ordering operator must be a less-than or greater-than member of some B-tree operator family. <literal>ASC</literal> is usually equivalent to <literal>USING &lt;</literal> and <literal>DESC</literal> is usually equivalent to <literal>USING &gt;</literal>. (But the creator of a user-defined data type can define exactly what the default sort ordering is, and it might correspond to operators with other names.) ORDER BY中の任意の式の後に、キーワードASC(昇順)、DESC(降順)を付加することができます(省略可能)。 指定がなければ、デフォルトでASCがあるものとして扱われます。 その他、順序を指定する演算子名をUSING句に指定する方法もあります。 順序指定演算子は何らかのB-Tree演算子族の小なりまたは大なり演算子でなければなりません。 通常、ASCUSING <と、DESCUSING >と同じです (ただし、ユーザ定義データ型の作成時には、デフォルトのソート順を定義することができます。また、異なる名前の演算子と対応付けすることもできます)。

If <literal>NULLS LAST</literal> is specified, null values sort after all non-null values; if <literal>NULLS FIRST</literal> is specified, null values sort before all non-null values. If neither is specified, the default behavior is <literal>NULLS LAST</literal> when <literal>ASC</literal> is specified or implied, and <literal>NULLS FIRST</literal> when <literal>DESC</literal> is specified (thus, the default is to act as though nulls are larger than non-nulls). When <literal>USING</literal> is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator. NULLS LASTが指定されると、NULL値はすべての非NULL値の後にソートされます。 NULLS FIRSTが指定されると、NULL値はすべての非NULL値の前にソートされます。 どちらも指定されない場合のデフォルト動作は、明示的あるいは暗黙的なASCの場合はNULLS LASTDESCが指定された場合はNULLS FIRSTです。 (したがって、デフォルトでは、NULLが非NULLよりも大きい値であるかのように動作します。) USINGが指定されると、デフォルトのNULLの順序は、演算子が小なり演算子か大なり演算子によって変わります。

Note that ordering options apply only to the expression they follow; for example <literal>ORDER BY x, y DESC</literal> does not mean the same thing as <literal>ORDER BY x DESC, y DESC</literal>. 順序付けオプションは直前の演算子にのみ適用されます。 たとえば、ORDER BY x, y DESCORDER BY x DESC, y DESCと同一の意味ではありません。

Character-string data is sorted according to the collation that applies to the column being sorted. That can be overridden at need by including a <literal>COLLATE</literal> clause in the <replaceable class="parameter">expression</replaceable>, for example <literal>ORDER BY mycolumn COLLATE "en_US"</literal>. For more information see <xref linkend="sql-syntax-collate-exprs"/> and <xref linkend="collation"/>. 文字型データでは、格納する列に適用された照合順序に従ってソートされます。 これは必要に応じてexpression内にCOLLATE句を含めることで上書きできます。 例えばORDER BY mycolumn COLLATE "en_US"です。 より詳細については4.2.10および24.2を参照してください。

<refsect2 id="sql-limit" xreflabel="LIMIT Clause">

LIMIT

<title><literal>LIMIT</literal> Clause</title>

The <literal>LIMIT</literal> clause consists of two independent sub-clauses: LIMIT句は2つの独立した副句から構成されます。

LIMIT { count | ALL }
OFFSET start

The parameter <replaceable class="parameter">count</replaceable> specifies the maximum number of rows to return, while <replaceable class="parameter">start</replaceable> specifies the number of rows to skip before starting to return rows. When both are specified, <replaceable class="parameter">start</replaceable> rows are skipped before starting to count the <replaceable class="parameter">count</replaceable> rows to be returned. パラメータcountには返される行の最大数を、一方、startには行を返し始める前に飛ばす行数を指定します。 両方とも指定された場合、start行分が飛ばされ、そこから数えてcount行が返されます。

If the <replaceable class="parameter">count</replaceable> expression evaluates to NULL, it is treated as <literal>LIMIT ALL</literal>, i.e., no limit. If <replaceable class="parameter">start</replaceable> evaluates to NULL, it is treated the same as <literal>OFFSET 0</literal>. count式がNULLと評価された場合、LIMIT ALLとして、つまり制限無しとして扱われます。 startがNULLと評価された場合、OFFSET 0と同様に扱われます。

SQL:2008 introduced a different syntax to achieve the same result, which <productname>PostgreSQL</productname> also supports. It is: SQL:2008では同じ結果を実現する異なる構文が導入されました。 PostgreSQLでもサポートしています。 以下の構文です。

OFFSET start { ROW | ROWS }
FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES }

In this syntax, the <replaceable class="parameter">start</replaceable> or <replaceable class="parameter">count</replaceable> value is required by the standard to be a literal constant, a parameter, or a variable name; as a <productname>PostgreSQL</productname> extension, other expressions are allowed, but will generally need to be enclosed in parentheses to avoid ambiguity. If <replaceable class="parameter">count</replaceable> is omitted in a <literal>FETCH</literal> clause, it defaults to 1. The <literal>WITH TIES</literal> option is used to return any additional rows that tie for the last place in the result set according to the <literal>ORDER BY</literal> clause; <literal>ORDER BY</literal> is mandatory in this case, and <literal>SKIP LOCKED</literal> is not allowed. <literal>ROW</literal> and <literal>ROWS</literal> as well as <literal>FIRST</literal> and <literal>NEXT</literal> are noise words that don't influence the effects of these clauses. According to the standard, the <literal>OFFSET</literal> clause must come before the <literal>FETCH</literal> clause if both are present; but <productname>PostgreSQL</productname> is laxer and allows either order. この構文において、startまたはcountの値は標準SQLでは、リテラル定数、パラメータもしくは変数名を要求します。 PostgreSQLの拡張では他の表現が許容されていますが、曖昧さを防ぐために通常は括弧で囲まれる必要があるでしょう。 countFETCH句で省略した場合、そのデフォルトは1です。 WITH TIESオプションは、結果の集合でORDER BY句に従って最後の場所で同点になる追加の行を返すのに使われます。この場合ORDER BYは必須で、SKIP LOCKEDは利用できません。 ROWおよびROWS、そしてFIRSTおよびNEXTは意味がない単語で、この句に影響を与えることはありません。 SQL標準ではOFFSET句は、FETCH句と同時に使用する場合、これより前に存在しなければなりません。 しかしPostgreSQLは厳密ではなく、どちらが先でも許されます。

When using <literal>LIMIT</literal>, it is a good idea to use an <literal>ORDER BY</literal> clause that constrains the result rows into a unique order. Otherwise you will get an unpredictable subset of the query's rows &mdash; you might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You don't know what ordering unless you specify <literal>ORDER BY</literal>. LIMITを使う時は、結果行を一意な順番に強制するORDER BY句を使うとよいでしょう。 そうしないと、問い合わせ結果のどの部分が返されるのかがわかりません。 10〜20行目までを出力するとしても、どの順番で並べた時の10〜20行目なのでしょうか。 ORDER BYを指定しない限り、行が返される順番は不明です。

The query planner takes <literal>LIMIT</literal> into account when generating a query plan, so you are very likely to get different plans (yielding different row orders) depending on what you use for <literal>LIMIT</literal> and <literal>OFFSET</literal>. Thus, using different <literal>LIMIT</literal>/<literal>OFFSET</literal> values to select different subsets of a query result <emphasis>will give inconsistent results</emphasis> unless you enforce a predictable result ordering with <literal>ORDER BY</literal>. This is not a bug; it is an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless <literal>ORDER BY</literal> is used to constrain the order. 問い合わせプランナは問い合わせ計画を作成する時にLIMITを考慮するので、LIMITOFFSETの指定によって異なった計画を得ることになるでしょう。計画が異なれば、異なる順番で行が返ります。 したがって、LIMIT/OFFSET値の変更によって異なる結果行を選択しようとすると、ORDER BYで順序を並べ替えない限り、矛盾した結果を返すことになります。 これはバグではありません。 「SQLは、ORDER BYで順序を制御されない限り、問い合わせ結果が返す順序を約束しない」という事実の当然の帰結なのです。

It is even possible for repeated executions of the same <literal>LIMIT</literal> query to return different subsets of the rows of a table, if there is not an <literal>ORDER BY</literal> to enforce selection of a deterministic subset. Again, this is not a bug; determinism of the results is simply not guaranteed in such a case. 厳密的に部分集合の選択を強制するORDER BYがなければ、同じLIMIT問い合わせを繰り返し実行してもテーブル行から異なる部分集合が取り出される可能性すらあります。 繰り返しますが、これは不具合ではありません。 こうした場合に確定した結果は単に保証されていないのです。

<refsect2 id="sql-for-update-share" xreflabel="The Locking Clause">

ロック処理句

<title>The Locking Clause</title>

<literal>FOR UPDATE</literal>, <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> are <firstterm>locking clauses</firstterm>; they affect how <literal>SELECT</literal> locks rows as they are obtained from the table. FOR UPDATEFOR NO KEY UPDATEFOR SHAREおよびFOR KEY SHAREロック処理句です。 これらはテーブルから行を入手する時にどのようにSELECTがその行をロックするかに影響します。

The locking clause has the general form ロック処理句の一般的な構文は以下の通りです。

FOR lock_strength [ OF table_name [, ...] ] [ NOWAIT | SKIP LOCKED ]

where <replaceable>lock_strength</replaceable> can be one of ここでlock_strengthは以下のいずれかを取ることができます。

UPDATE
NO KEY UPDATE
SHARE
KEY SHARE

For more information on each row-level lock mode, refer to <xref linkend="locking-rows"/>. それぞれの行レベルロックモードについての詳しい説明は13.3.2を参照してください。

To prevent the operation from waiting for other transactions to commit, use either the <literal>NOWAIT</literal> or <literal>SKIP LOCKED</literal> option. With <literal>NOWAIT</literal>, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. With <literal>SKIP LOCKED</literal>, any selected rows that cannot be immediately locked are skipped. Skipping locked rows provides an inconsistent view of the data, so this is not suitable for general purpose work, but can be used to avoid lock contention with multiple consumers accessing a queue-like table. Note that <literal>NOWAIT</literal> and <literal>SKIP LOCKED</literal> apply only to the row-level lock(s) &mdash; the required <literal>ROW SHARE</literal> table-level lock is still taken in the ordinary way (see <xref linkend="mvcc"/>). You can use <link linkend="sql-lock"><command>LOCK</command></link> with the <literal>NOWAIT</literal> option first, if you need to acquire the table-level lock without waiting. 他のトランザクションのコミットを待機することなく操作を進めるには、NOWAITあるいはSKIP LOCKEDオプションを使用してください。 NOWAITでは、選択行のロックを即座に獲得できない時、文は待機せずに、エラーを報告します。 SKIP LOCKEDでは、即座にロックできない行はすべてスキップされます。 行のロックをスキップすると、一貫性のないデータが見えることになるので、一般的な目的の作業のためには適しませんが、複数の消費者がキューのようなテーブルにアクセスするときのロック競合の回避などに利用できます。 NOWAITおよびSKIP LOCKEDは行レベルロックにのみに適用される点に注意してください。 つまり、必要なROW SHAREテーブルレベルロックは通常通りの方法( 第13章を参照)で獲得されます。 もし、テーブルレベルのロックを待機せずに獲得しなければならないのであれば、最初にLOCKNOWAITオプションを使用してください。

If specific tables are named in a locking clause, then only rows coming from those tables are locked; any other tables used in the <command>SELECT</command> are simply read as usual. A locking clause without a table list affects all tables used in the statement. If a locking clause is applied to a view or sub-query, it affects all tables used in the view or sub-query. However, these clauses do not apply to <literal>WITH</literal> queries referenced by the primary query. If you want row locking to occur within a <literal>WITH</literal> query, specify a locking clause within the <literal>WITH</literal> query. ロック処理句内に特定のテーブルが指定されている場合は、そのテーブルの行のみがロックされます。 SELECT内の他のテーブルは通常通りに読み込まれます。 テーブルリストを持たないロック処理句は、その文で使用されるすべてのテーブルに影響を与えます。 ロック処理句がビューまたは副問い合わせで使用された場合、そのビューや副問い合わせで使用されるすべてのテーブルに影響を与えます。 しかしこれらの句は主問い合わせで参照されるWITH問い合わせには適用されません。 WITH問い合わせ内での行ロックを行いたい場合は、WITH問い合わせ内でロック処理句を指定してください。

Multiple locking clauses can be written if it is necessary to specify different locking behavior for different tables. If the same table is mentioned (or implicitly affected) by more than one locking clause, then it is processed as if it was only specified by the strongest one. Similarly, a table is processed as <literal>NOWAIT</literal> if that is specified in any of the clauses affecting it. Otherwise, it is processed as <literal>SKIP LOCKED</literal> if that is specified in any of the clauses affecting it. 異なるロック方式を異なるテーブルに指定する必要があれば、複数のロック処理句を記述することができます。 複数のロック処理句で同一のテーブルを記述した(または暗黙的に影響が与えられた)場合、最も強いものだけが指定されたかのように処理されます。 同様に、あるテーブルに影響を与える句のいずれかでNOWAITが指定された場合、そのテーブルはNOWAITとして処理されます。 それ以外の場合、あるテーブルに影響を与える句のいずれかでSKIP LOCKEDが指定されていれば、そのテーブルはSKIP LOCKEDとして処理されます。

The locking clauses cannot be used in contexts where returned rows cannot be clearly identified with individual table rows; for example they cannot be used with aggregation. ロック処理句は、返される行がテーブルのどの行に対応するのかが明確に識別できない場合には使用することができません。 例えば、集約には使用できません。

When a locking clause appears at the top level of a <command>SELECT</command> query, the rows that are locked are exactly those that are returned by the query; in the case of a join query, the rows locked are those that contribute to returned join rows. In addition, rows that satisfied the query conditions as of the query snapshot will be locked, although they will not be returned if they were updated after the snapshot and no longer satisfy the query conditions. If a <literal>LIMIT</literal> is used, locking stops once enough rows have been returned to satisfy the limit (but note that rows skipped over by <literal>OFFSET</literal> will get locked). Similarly, if a locking clause is used in a cursor's query, only rows actually fetched or stepped past by the cursor will be locked. ロック処理句がSELECT問い合わせの最上位レベルに存在する場合、ロック対象行は問い合わせが返す行に正確に一致します。 結合問い合わせ内の場合、ロック対象行は返される結合行に関連する行となります。 さらに、スナップショットを更新した後に問い合わせ条件を満たさなくなった場合は返されなくなりますが、問い合わせのスナップショット時点で問い合わせ条件を満たす行もロックされます。 LIMITが使用された場合、制限を満たす行が返されるとロック処理は止まります。 (しかし、OFFSETにより飛ばされた行はロックされることに注意してください。) 同様に、ロック処理句がカーソル問い合わせで使用された場合、カーソルにより実際に取り込んだ行または通り過ぎた行のみがロックされます。

When a locking clause appears in a sub-<command>SELECT</command>, the rows locked are those returned to the outer query by the sub-query. This might involve fewer rows than inspection of the sub-query alone would suggest, since conditions from the outer query might be used to optimize execution of the sub-query. For example, ロック処理句が副SELECTに存在する場合、ロック対象行は副問い合わせの外側の問い合わせに返される行となります。 外側の問い合わせからの条件が副問い合わせ実行の最適化に使用される可能性がありますので、これには副問い合わせ自体の検査が提示する行より少なくなるかもしれません。 例えば、

SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;

will lock only rows having <literal>col1 = 5</literal>, even though that condition is not textually within the sub-query. は、副問い合わせ内では文字として条件が記載されていなくても、col1 = 5を持つ行のみがロックされます。

Previous releases failed to preserve a lock which is upgraded by a later savepoint. For example, this code: 以前のリリースでは、セーブポイント以降に更新されるロックの保持は失敗しました。 例えば以下のコードです。

BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
SAVEPOINT s;
UPDATE mytable SET ... WHERE key = 1;
ROLLBACK TO s;

would fail to preserve the <literal>FOR UPDATE</literal> lock after the <command>ROLLBACK TO</command>. This has been fixed in release 9.3. ROLLBACK TO後のFOR UPDATEロックの保持に失敗します。 これはリリース9.3で修正されました。

注意

It is possible for a <command>SELECT</command> command running at the <literal>READ COMMITTED</literal> transaction isolation level and using <literal>ORDER BY</literal> and a locking clause to return rows out of order. This is because <literal>ORDER BY</literal> is applied first. The command sorts the result, but might then block trying to obtain a lock on one or more of the rows. Once the <literal>SELECT</literal> unblocks, some of the ordering column values might have been modified, leading to those rows appearing to be out of order (though they are in order in terms of the original column values). This can be worked around at need by placing the <literal>FOR UPDATE/SHARE</literal> clause in a sub-query, for example ORDER BY句とロック処理句を使用した、READ COMMITTEDトランザクション分離レベルで実行するSELECTコマンドでは、順序通りにならない行を返す可能性があります。 ORDER BYが最初に適用されるためです。 このコマンドは結果をソートしますが、その後、1行または複数の行のロック獲得がブロックされる可能性があります。 このSELECTのブロックが解除された時点で、順序付け対象の列値の一部が変更されているかもしれません。 これによりこうした行が(元の列値という観点では順序通りではありますが、)順序通りに現れません。 必要に応じて、これは以下のように副問い合わせ内にFOR UPDATE/SHARE句を記述することで、回避することができます。

SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;

Note that this will result in locking all rows of <structname>mytable</structname>, whereas <literal>FOR UPDATE</literal> at the top level would lock only the actually returned rows. This can make for a significant performance difference, particularly if the <literal>ORDER BY</literal> is combined with <literal>LIMIT</literal> or other restrictions. So this technique is recommended only if concurrent updates of the ordering columns are expected and a strictly sorted result is required. 最上位レベルにおけるFOR UPDATEは実際に返される行のみをロックするのに対して、これは結果としてmytableのすべての行をロックすることに注意してください。 これは、特にORDER BYLIMITやその他の制限と組み合わせている場合、性能上大きな違いを生み出す可能性があります。 このため、この技法は、順序付け対象の列に対する同時実行の更新が想定され、かつ、厳密にソートされた結果が要求される場合にのみ推奨されます。

At the <literal>REPEATABLE READ</literal> or <literal>SERIALIZABLE</literal> transaction isolation level this would cause a serialization failure (with an <literal>SQLSTATE</literal> of <literal>'40001'</literal>), so there is no possibility of receiving rows out of order under these isolation levels. REPEATABLE READまたはSERIALIZABLEトランザクション分離レベルでは、('40001'というSQLSTATEを持つ)シリアライゼーション失敗が発生します。 このためこれらの分離レベルでは順序通りでない行を受け取る可能性はありません。

TABLEコマンド

<title><literal>TABLE</literal> Command</title>

The command コマンド

TABLE name

is equivalent to は以下と同じです。

SELECT * FROM name

It can be used as a top-level command or as a space-saving syntax variant in parts of complex queries. Only the <literal>WITH</literal>, <literal>UNION</literal>, <literal>INTERSECT</literal>, <literal>EXCEPT</literal>, <literal>ORDER BY</literal>, <literal>LIMIT</literal>, <literal>OFFSET</literal>, <literal>FETCH</literal> and <literal>FOR</literal> locking clauses can be used with <command>TABLE</command>; the <literal>WHERE</literal> clause and any form of aggregation cannot be used. これは、最上位のコマンドとして、あるいは複雑な問い合わせの一部として、入力を省略する構文の一種としても使用することができます。 WITHUNIONINTERSECTEXCEPTORDER BYLIMITOFFSETFETCHFORのロック句だけをTABLEと一緒に使うことができます。 WHERE句およびいかなる形式の集約も使うことはできません。

<title>Examples</title>

To join the table <literal>films</literal> with the table <literal>distributors</literal>: filmsテーブルをdistributorsテーブルと結合します。

SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d JOIN films f USING (did);

       title       | did |     name     | date_prod  |   kind
-------------------+-----+--------------+------------+----------
 The Third Man     | 101 | British Lion | 1949-12-23 | Drama
 The African Queen | 101 | British Lion | 1951-08-11 | Romantic
 ...

To sum the column <literal>len</literal> of all films and group the results by <literal>kind</literal>: 全ての映画のlen列を合計しkind列によって結果をグループ化します。

SELECT kind, sum(len) AS total FROM films GROUP BY kind;

   kind   | total
----------+-------
 Action   | 07:34
 Comedy   | 02:58
 Drama    | 14:28
 Musical  | 06:42
 Romantic | 04:38

To sum the column <literal>len</literal> of all films, group the results by <literal>kind</literal> and show those group totals that are less than 5 hours: 全ての映画のlen列を合計しkind列によって結果をグループ化し、合計が5時間より少ないグループの合計を表示します。

SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) < interval '5 hours';

   kind   | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38

The following two examples are identical ways of sorting the individual results according to the contents of the second column (<literal>name</literal>): 次に、結果を2番目の列(name)の内容に基づいてソートする方法を2つ例示します。

SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;

 did |       name
-----+------------------
 109 | 20th Century Fox
 110 | Bavaria Atelier
 101 | British Lion
 107 | Columbia
 102 | Jean Luc Godard
 113 | Luso films
 104 | Mosfilm
 103 | Paramount
 106 | Toho
 105 | United Artists
 111 | Walt Disney
 112 | Warner Bros.
 108 | Westward

The next example shows how to obtain the union of the tables <literal>distributors</literal> and <literal>actors</literal>, restricting the results to those that begin with the letter W in each table. Only distinct rows are wanted, so the key word <literal>ALL</literal> is omitted. 次の例は、distributorsテーブルとactorsテーブルの和集合を取得する方法を示しています。さらに、両方のテーブルで結果をWという文字で始まる行のみに限定しています。 重複しない行のみが必要なので、ALLキーワードは省略されています。

distributors:               actors:
 did |     name              id |     name
-----+--------------        ----+----------------
 108 | Westward               1 | Woody Allen
 111 | Walt Disney            2 | Warren Beatty
 112 | Warner Bros.           3 | Walter Matthau
 ...                         ...

SELECT distributors.name
    FROM distributors
    WHERE distributors.name LIKE 'W%'
UNION
SELECT actors.name
    FROM actors
    WHERE actors.name LIKE 'W%';

      name
----------------
 Walt Disney
 Walter Matthau
 Warner Bros.
 Warren Beatty
 Westward
 Woody Allen

This example shows how to use a function in the <literal>FROM</literal> clause, both with and without a column definition list: 次に、FROM句内での関数の使用方法について、列定義リストがある場合とない場合の両方の例を示します。

CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
    SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;

SELECT * FROM distributors(111);
 did |    name
-----+-------------
 111 | Walt Disney

CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
    SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;

SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
 f1  |     f2
-----+-------------
 111 | Walt Disney

Here is an example of a function with an ordinality column added: 以下は序数列が追加された関数の例です。

SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY;
 unnest | ordinality
--------+----------
 a      |        1
 b      |        2
 c      |        3
 d      |        4
 e      |        5
 f      |        6
(6 rows)

This example shows how to use a simple <literal>WITH</literal> clause: 以下の例では簡単なWITH句の使用方法を示します。

WITH t AS (
    SELECT random() as x FROM generate_series(1, 3)
  )
SELECT * FROM t
UNION ALL
SELECT * FROM t

         x
--------------------
  0.534150459803641
  0.520092216785997
 0.0735620250925422
  0.534150459803641
  0.520092216785997
 0.0735620250925422

Notice that the <literal>WITH</literal> query was evaluated only once, so that we got two sets of the same three random values. WITH問い合わせが一度だけ評価されることに注意してください。 このため3つのランダムな値の同じ集合2組を得ることになります。

This example uses <literal>WITH RECURSIVE</literal> to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates: 以下の例ではWITH RECURSIVEを使用して、直接の部下しか表示しないテーブルから、従業員Maryの(直接または間接的な)部下とその間接度を見つけ出します。

WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
    SELECT 1, employee_name, manager_name
    FROM employee
    WHERE manager_name = 'Mary'
  UNION ALL
    SELECT er.distance + 1, e.employee_name, e.manager_name
    FROM employee_recursive er, employee e
    WHERE er.employee_name = e.manager_name
  )
SELECT distance, employee_name FROM employee_recursive;

Notice the typical form of recursive queries: an initial condition, followed by <literal>UNION</literal>, followed by the recursive part of the query. Be sure that the recursive part of the query will eventually return no tuples, or else the query will loop indefinitely. (See <xref linkend="queries-with"/> for more examples.) 初期条件、続いてUNION、さらに問い合わせの再帰部分という再帰問い合わせの典型的な構文に注意してください。 問い合わせの再帰部分は最終的にはタプルを返さないことを確実にしてください。 さもないと問い合わせは無限にループします。 (より多くの例については7.8を参照してください。)

This example uses <literal>LATERAL</literal> to apply a set-returning function <function>get_product_names()</function> for each row of the <structname>manufacturers</structname> table: 以下の例では、manufacturersテーブルの各行に対して集合を返すget_product_names()関数を適用するためにLATERALを使用します。

SELECT m.name AS mname, pname
FROM manufacturers m, LATERAL get_product_names(m.id) pname;

Manufacturers not currently having any products would not appear in the result, since it is an inner join. If we wished to include the names of such manufacturers in the result, we could do: これは内部結合ですので、現時点で製品をまったく持たないメーカーは結果に現れません。 こうしたメーカーの名前も結果に含めたければ以下のようにします。

SELECT m.name AS mname, pname
FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;

互換性

<title>Compatibility</title>

Of course, the <command>SELECT</command> statement is compatible with the SQL standard. But there are some extensions and some missing features. 当然ながら、SELECT文は標準SQLと互換性があります。 しかし、拡張機能や実現されていない機能もいくつかあります。

FROM句の省略

<title>Omitted <literal>FROM</literal> Clauses</title>

<productname>PostgreSQL</productname> allows one to omit the <literal>FROM</literal> clause. It has a straightforward use to compute the results of simple expressions: PostgreSQLでは、FROM句を省略することができます。 これによって、以下のように単純な式を計算させることができます。

SELECT 2+2;

 ?column?
----------
        4

Some other <acronym>SQL</acronym> databases cannot do this except by introducing a dummy one-row table from which to do the <command>SELECT</command>. 他のSQLデータベースでは、このようなSELECTを行うためにはダミーの1行テーブルを使わなければならないものもあります。

空のSELECTリスト

<title>Empty <literal>SELECT</literal> Lists</title>

The list of output expressions after <literal>SELECT</literal> can be empty, producing a zero-column result table. This is not valid syntax according to the SQL standard. <productname>PostgreSQL</productname> allows it to be consistent with allowing zero-column tables. However, an empty list is not allowed when <literal>DISTINCT</literal> is used. SELECTの後の出力式のリストは空でも良く、このとき列数がゼロの結果テーブルが生成されます。 これは標準SQLでは有効な構文ではありませんが、PostgreSQLは列数がゼロのテーブルを許すので、それと整合性を保つために許しています。 しかし、DISTINCTを使う時は、空のリストを使うことはできません。

ASキーワードの省略

<title>Omitting the <literal>AS</literal> Key Word</title>

In the SQL standard, the optional key word <literal>AS</literal> can be omitted before an output column name whenever the new column name is a valid column name (that is, not the same as any reserved keyword). <productname>PostgreSQL</productname> is slightly more restrictive: <literal>AS</literal> is required if the new column name matches any keyword at all, reserved or not. Recommended practice is to use <literal>AS</literal> or double-quote output column names, to prevent any possible conflict against future keyword additions. 標準SQLでは、キーワードAS(省略可能)は、新しい列名が有効な列名(つまり予約済みのどのキーワードとも異なるもの)である場合は常に、出力列名の前から省くことができます。 PostgreSQLには多少より強い制限があります。 新しい列名が予約済みか否かに関わらず何らかのキーワードに一致する場合はASが必要です。 推奨する実践方法は、今後のキーワードの追加と競合する可能性に備え、ASを使用する、または出力列名を二重引用符で括ることです。

In <literal>FROM</literal> items, both the standard and <productname>PostgreSQL</productname> allow <literal>AS</literal> to be omitted before an alias that is an unreserved keyword. But this is impractical for output column names, because of syntactic ambiguities. FROM項目において標準およびPostgreSQLでは、未予約のキーワードである別名の前のASを省略することができます。 しかし、構文があいまいになるため、出力名では実践的ではありません。

FROMでの副SELECTの別名の省略

<title>Omitting Sub-<command>SELECT</command> Aliases in <literal>FROM</literal></title>

According to the SQL standard, a sub-<command>SELECT</command> in the <literal>FROM</literal> list must have an alias. In <productname>PostgreSQL</productname>, this alias may be omitted. 標準SQLでは、FROMリスト内の副SELECTには別名が必要です。 PostgreSQLでは、この別名を省略できます。

ONLYと継承関係

<title><literal>ONLY</literal> and Inheritance</title>

The SQL standard requires parentheses around the table name when writing <literal>ONLY</literal>, for example <literal>SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE ...</literal>. <productname>PostgreSQL</productname> considers these parentheses to be optional. 標準SQLでは、SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE ...のように、ONLYを記述する時にテーブル名の前後を括弧でくくることを要求します。 PostgreSQLではこの括弧を省略可能であるとみなしています。

<productname>PostgreSQL</productname> allows a trailing <literal>*</literal> to be written to explicitly specify the non-<literal>ONLY</literal> behavior of including child tables. The standard does not allow this. PostgreSQLでは最後に*を付けることで 明示的に子テーブルを含めるというONLYではない動作を指定することができます。 標準ではこれを許していません。

(These points apply equally to all SQL commands supporting the <literal>ONLY</literal> option.) (これらの点はONLYオプションをサポートするすべてのSQLコマンドで同様に適用されます。)

TABLESAMPLE句の制限

<title><literal>TABLESAMPLE</literal> Clause Restrictions</title>

The <literal>TABLESAMPLE</literal> clause is currently accepted only on regular tables and materialized views. According to the SQL standard it should be possible to apply it to any <literal>FROM</literal> item. 現在のところ、TABLESAMPLE句は通常のテーブルとマテリアライズドビューでのみ受け付けられます。 SQL標準では、FROM句の任意の要素について適用可能であるべきとされています。

FROM内の関数呼び出し

<title>Function Calls in <literal>FROM</literal></title>

<productname>PostgreSQL</productname> allows a function call to be written directly as a member of the <literal>FROM</literal> list. In the SQL standard it would be necessary to wrap such a function call in a sub-<command>SELECT</command>; that is, the syntax <literal>FROM <replaceable>func</replaceable>(...) <replaceable>alias</replaceable></literal> is approximately equivalent to <literal>FROM LATERAL (SELECT <replaceable>func</replaceable>(...)) <replaceable>alias</replaceable></literal>. Note that <literal>LATERAL</literal> is considered to be implicit; this is because the standard requires <literal>LATERAL</literal> semantics for an <literal>UNNEST()</literal> item in <literal>FROM</literal>. <productname>PostgreSQL</productname> treats <literal>UNNEST()</literal> the same as other set-returning functions. PostgreSQLでは、FROMリストのメンバとして直接関数呼び出しを記述することができます。 標準SQLではこうした関数呼び出しを副SELECT内に囲む必要があります。 つまりFROM func(...) aliasはおおよそFROM LATERAL (SELECT func(...)) aliasと同じです。 暗黙的にLATERALであるとみなされることに注意してください。 標準ではFROM内のUNNEST()項目にはLATERAL構文を必要とするためです。 PostgreSQLではUNNEST()を他の集合を返す関数と同じものとして扱います。

GROUP BYORDER BYにおける利用可能な名前空間

<title>Namespace Available to <literal>GROUP BY</literal> and <literal>ORDER BY</literal></title>

In the SQL-92 standard, an <literal>ORDER BY</literal> clause can only use output column names or numbers, while a <literal>GROUP BY</literal> clause can only use expressions based on input column names. <productname>PostgreSQL</productname> extends each of these clauses to allow the other choice as well (but it uses the standard's interpretation if there is ambiguity). <productname>PostgreSQL</productname> also allows both clauses to specify arbitrary expressions. Note that names appearing in an expression will always be taken as input-column names, not as output-column names. 標準SQL-92では、ORDER BY句で使用できるのは、出力列名か序数のみであり、GROUP BY句で使用できるのは、入力列名からなる式のみです。 PostgreSQLは、これらの句で両方が指定できるように拡張されています (ただし、不明瞭さがある場合は標準の解釈が使用されます)。 さらに、PostgreSQLではどちらの句にも任意の式を指定できます。 式で使われる名前は、常に出力列名ではなく入力列の名前とみなされることに注意してください。

SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL-92. In most cases, however, <productname>PostgreSQL</productname> will interpret an <literal>ORDER BY</literal> or <literal>GROUP BY</literal> expression the same way SQL:1999 does. SQL:1999以降では、SQL-92と完全には上位互換でない、多少異なる定義が採用されています。 しかし、ほとんどの場合、PostgreSQLはSQL:1999と同じ方法でORDER BYGROUP BYを解釈します。

関数従属性

<title>Functional Dependencies</title>

<productname>PostgreSQL</productname> recognizes functional dependency (allowing columns to be omitted from <literal>GROUP BY</literal>) only when a table's primary key is included in the <literal>GROUP BY</literal> list. The SQL standard specifies additional conditions that should be recognized. テーブルの主キーがGROUP BYリストに含まれる場合に限り、PostgreSQLは(GROUP BYで列を省くことができる)関数従属性を認識します。 標準SQLでは、認識しなければならない追加の条件を規定しています。

LIMITおよびOFFSET

<title><literal>LIMIT</literal> and <literal>OFFSET</literal></title>

The clauses <literal>LIMIT</literal> and <literal>OFFSET</literal> are <productname>PostgreSQL</productname>-specific syntax, also used by <productname>MySQL</productname>. The SQL:2008 standard has introduced the clauses <literal>OFFSET ... FETCH {FIRST|NEXT} ...</literal> for the same functionality, as shown above in <xref linkend="sql-limit"/>. This syntax is also used by <productname>IBM DB2</productname>. (Applications written for <productname>Oracle</productname> frequently use a workaround involving the automatically generated <literal>rownum</literal> column, which is not available in PostgreSQL, to implement the effects of these clauses.) LIMITおよびOFFSET句はPostgreSQL独自の構文ですが、MySQLでも使用されています。 LIMIT句で説明したように、標準SQL:2008にて同じ機能のOFFSET ... FETCH {FIRST|NEXT} ...が導入されました。 この構文はIBM DB2でも使用されています。 (Oracle用に開発されたアプリケーションでは、これらの句の機能を実装するために自動生成されるrownum列を含めるという回避策を使用することが多いですが、PostgreSQLでは利用できません。)

FOR NO KEY UPDATEFOR UPDATEFOR SHAREFOR KEY SHARE

<title><literal>FOR NO KEY UPDATE</literal>, <literal>FOR UPDATE</literal>, <literal>FOR SHARE</literal>, <literal>FOR KEY SHARE</literal></title>

Although <literal>FOR UPDATE</literal> appears in the SQL standard, the standard allows it only as an option of <command>DECLARE CURSOR</command>. <productname>PostgreSQL</productname> allows it in any <command>SELECT</command> query as well as in sub-<command>SELECT</command>s, but this is an extension. The <literal>FOR NO KEY UPDATE</literal>, <literal>FOR SHARE</literal> and <literal>FOR KEY SHARE</literal> variants, as well as the <literal>NOWAIT</literal> and <literal>SKIP LOCKED</literal> options, do not appear in the standard. FOR UPDATEは標準SQLに存在しますが、標準では、DECLARE CURSORのオプションとしてしか許されていません。 PostgreSQLでは、副SELECTなど任意のSELECTで許されます。 これは拡張です。 FOR NO KEY UPDATEFOR SHAREFOR KEY SHAREの亜種、およびNOWAITSKIP LOCKEDオプションは標準にはありません。

WITH内のデータ変更文

<title>Data-Modifying Statements in <literal>WITH</literal></title>

<productname>PostgreSQL</productname> allows <command>INSERT</command>, <command>UPDATE</command>, and <command>DELETE</command> to be used as <literal>WITH</literal> queries. This is not found in the SQL standard. PostgreSQLではWITH問い合わせとしてINSERTUPDATEおよびDELETEを使用することができます。 これは標準SQLにはありません。

非標準句

<title>Nonstandard Clauses</title>

<literal>DISTINCT ON ( ... )</literal> is an extension of the SQL standard. DISTINCT ON ( ... )は標準SQLの拡張です。

<literal>ROWS FROM( ... )</literal> is an extension of the SQL standard. ROWS FROM( ... )は標準SQLの拡張です。

The <literal>MATERIALIZED</literal> and <literal>NOT MATERIALIZED</literal> options of <literal>WITH</literal> are extensions of the SQL standard. WITHMATERIALIZEDNOT MATERIALIZEDオプションはSQL標準の拡張です。