SELECT

Name

SELECT  --  Retrieve rows from a table or view. テーブルもしくはビューから行を取り出す。

Synopsis

SELECT [ALL|DISTINCT [ON column] ]
    expression [ AS
   name ] [, ...]
    [ INTO [TEMP] [TABLE] new_table ]
    [ FROM table
   [alias ] [, ...] ]
    [ WHERE condition ]
    [ GROUP BY column [, ...] ]
    [ HAVING condition [, ...] ]
    [ { UNION [ALL] | INTERSECT | EXCEPT } select ]
    [ ORDER BY column [ ASC | DESC ] [, ...] ]
    [ FOR UPDATE [OF class_name...]]
    [ LIMIT count [OFFSET|, count]]
  

入力

expression

The name of a table's column or an expression.

テーブルのカラム名または式。

name

Specifies another name for a column or an expression using the AS clause. name cannot be used in the WHERE condition. It can, however, be referenced in associated ORDER BY or GROUP BY clauses.

カラムまたは式の別名を AS 句を使用して指定します。 name は WHERE 条 件の中では使用できません。しかし、関連する ORDER BY または GROUP BY 句では参照できます。

TEMP

The table is created unique to this session, and is automatically dropped on session exit.

このセッションで一意となるテーブルが作成され、セッション終了 時に自動的に削除されます。

new_table

If the INTO TABLE clause is specified, the result of the query will be stored in another table with the indicated name. The target table (new_table) will be created automatically and should not exist before this command. Refer to SELECT INTO for more information.

INTO TABLE 句が指定された場合、問い合わせの結果は指定された名 前の別のテーブルに保存されます。対象となる( new_table )テー ブルは、自動的に作成され、また、このコマンド実行前には存在して はいけません。より詳しくは SELECT INTO を参 照して下さい。

Note: The CREATE TABLE AS statement will also create a new table from a select query.

CREATE TABLE AS 文もまた、select 文から新 しいテーブルを作成します。

table

The name of an existing table referenced by the FROM clause.

FROM 句で参照される、既存テーブルの名前。

alias

An alternate name for the preceding table. It is used for brevity or to eliminate ambiguity for joins within a single table.

直前の table の 別名。簡潔にするため、もしくは、1 つのテーブル内での結合の際 のあいまいな部分を除去するために使用されます。

condition

A boolean expression giving a result of true or false. See the WHERE clause.

その結果として true または false を返すブール式。WHERE 句を参 照して下さい。

column

The name of a table's column.

テーブルのカラム名。

select

A select statement with all features except the ORDER BY clause.

ORDER BY 以外の全ての機能を持つ select 文。

出力

The complete set of rows resulting from the query specification.

問い合わせで指定された結果の行の完全な集合。

count

The count of rows returned by the query.

問い合わせによって返される行数。

説明

SELECT will return rows from one or more tables. Candidates for selection are rows which satisfy the WHERE condition; if WHERE is omitted, all rows are candidates.

SELECT は 1 つ以上のテーブルから行を返します。選 択の候補は、WHERE 条件を満たす行です。WHERE が省略された場合は全ての 行がその候補となります。

DISTINCT will eliminate all duplicate rows from the selection. DISTINCT ON column will eliminate all duplicates in the specified column; this is equivalent to using GROUP BY column. ALL will return all candidate rows, including duplicates.

DISTINCT は選択したものから重複する行を全て除き ます。 DISTINCT ON column は指定カラム内の全ての重複を除きます。これは GROUP BY column の使用と同じことです。ALL は全ての候補となる行を、 重複したものも含めて返します。

The GROUP BY clause allows a user to divide a table conceptually into groups. (See GROUP BY clause).

GROUP BY 句により、1 つのテーブルを概念的なグループに分割すること ができます。( GROUP BY 句を参照して下さい。)

The HAVING clause specifies a grouped table derived by the elimination of groups from the result of the previously specified clause. (See HAVING clause).

HAVING 句は、事前に指定された句によりグループ化されたテーブルの中 から取り除くべきグループを指定します。( HAVING 句を参照して下さい。)

The ORDER BY clause allows a user to specify that he/she wishes the rows sorted according to the ASCending or DESCending mode operator. (See ORDER BY clause)

ORDER BY 句により、ユーザが望むように行を順方向(ASC)、または逆 方向(DESC)モード演算子にしたがって行をソートできます。( 後述の ORDER BY 句を参照して下さい。)

The UNION clause allows the result to be the collection of rows returned by the queries involved. (See UNION clause).

UNION 句により実行した問い合わせから返される行をまとめたものを結果 とすることができます。(後述の UNION 句を参照して下さい。)

The INTERSECT give you the rows that are common to both queries. (See INTERSECT clause).

INTERSECT は 2 つの問い合わせの共通部分となる行を返します。( 後述の INTERSECT 句を参照して下さい。)

The EXCEPT give you the rows in the upper query not in the lower query. (See EXCEPT clause).

EXCEPT は、上側の問い合わせにあり、下側の問い合わせにない行を返 します。( 後述の EXCEPT 句を参照して下さい。)

The FOR UPDATE clause allows the SELECT statement to perform exclusive locking of selected rows. (See EXCEPT clause).

FOR UPDATE 句により、この SELECT 文で選ばれた行を排他的ロックで きます。(後述の EXCEPT 句を参照して下さい。) (訳注: See EXCEPT clause は間違いと思われます。)

The LIMIT...OFFSET clause allows control over which rows are returned by the query.

LIMIT...OFFSET 句により、問い合わせで返される行を抑制することが できます。

You must have SELECT privilege to a table to read its values (See GRANT/REVOKE statements).

テーブルから値を読みとるためにそのテーブルに SELECT 権限を持って いる必要があります。

WHERE 句

The optional WHERE condition has the general form:

オプションである、WHERE 句は一般的に次の形式です。

WHERE expr ETER">ce"PARreplaceable> [ log_op ... ]
    
where cond_op can be one of: =, <, <=, >, >= or <>, a conditional operator like ALL, ANY, IN, LIKE, et cetera or a locally-defined operator, and log_op can be one of: AND, OR, NOT. The comparison returns either TRUE or FALSE and all instances will be discarded if the expression evaluates to FALSE. ここで、cond_op は、 =、 <、 <=、 >、 >= 、<>、または、ALL、ANY、 IN、LIKE などといった条件演算子、ローカルに定義された演算子の内 の 1 つを指定できます。また、 log_opは、AND、OR、 NOT の内の 1 つです。比較は TRUE か FALSE を返し、もし式が FALSE と評価されたら、全インスタンスは廃棄されます。

GROUP BY 句

GROUP BY specifies a grouped table derived by the application of this clause:

GROUP BY は、ここで指定された句ごとにテーブルをグループ化します。

GROUP BY column [, ...]
    

GROUP BY will condense into a single row all rows that share the same values for the grouped columns; aggregates return values derived from all rows that make up the group. The value returned for an ungrouped and unaggregated column is dependent on the order in which rows happen to be read from the database.

GROUP BY はグループ化されたカラムにて同一値を持つ全ての行を 1 つの 行にまとめ、グループを構成する全ての行から導かれる値を集約します。 グループ化されず、集約されずに返されたカラムの値は、その行がデータ ベースから読みとられた順番に依存します。

HAVING 句

The optional HAVING condition has the general form:

オプションである、HAVING 条件は一般的に次の形式です。

HAVING cond_expr
    
where cond_expr is the same as specified for the WHERE clause. ここで、cond_expr は WHERE 句で指定するものと同一です。

HAVING specifies a grouped table derived by the elimination of groups from the result of the previously specified clause that do not meet the cond_expr.

HAVING は、事前に指定された句によりグループ化されたテーブルの中か ら取り除くべき、つまり、 cond_expr に合わなか ったグループを指定します。

Each column referenced in cond_expr shall unambiguously reference a grouping column.

cond_expr で参照さ れる各カラムは、明瞭にグループ化されたカラムを参照します。

ORDER BY 句

ORDER BY column [ ASC | DESC ] [, ...]
    

column can be either a column name or an ordinal number.

column には、カラム 名または序数を指定できます。

The ordinal numbers refers to the ordinal (left-to-right) position of the column. This feature makes it possible to define an ordering on the basis of a column that does not have a proper name. This is never absolutely necessary because it is always possible assign a name to a calculated column using the AS clause, e.g.:

序数はカラムの位置を(左から右に数えた)順序で参照します。この機 能によって、適切な名前を持たないカラムを元に順番を定義することが できます。これは絶対に必要なものではありません。というのは、AS 句を下のように使えば、常に対象とするカラムに名前を割り当てること ができるからです。

SELECT title, date_prod + 1 AS newlen FROM films ORDER BY newlen;
    

From release 6.4 of PostgreSQL, the columns in the ORDER BY clause do not need to appear in the SELECT clause. Thus the following statement is now legal:

PostgreSQL のリリース 6.4 から、ORDER BY 句のカラムは SELECT 句 にある必要がなくなりました。従って、以下の文は、現在正当なもので す。

SELECT name FROM distributors ORDER BY code;
    

Optionally one may add the keyword DESC (descending) or ASC (ascending) after each column name in the ORDER BY clause. If not specified, ASC is assumed by default.

オプションとして、ORDER BY 句の各カラム名の後にキーワード DESC(逆方向)もしくは ASC(順方向)を付けることができます。 指定がなければ、デフォルトとして ASC がついているものとしま す。

UNION 句

table_query UNION [ ALL ]
table_query
     [ ORDER BY column [ ASC | DESC ] [, ...] ]
    
where table_query specifies any select expression without an ORDER BY clause. ここで、table_query は、ORDER BY 句を持たない任意の select 式を指定できます。

The UNION clause allows the result to be the collection of rows returned by the queries involved. (See UNION clause). The two tables that represent the direct operands of the UNION must have the same number of columns, and corresponding columns must be of compatible data types.

UNION 句によって、呼び出された問い合わせから返される行をまとめたも のを結果とすることができます。( UNION 句を参照して下さい。) UNION の直接の演算項目として指定された 2 つのテーブルは、同一のカラム数 でなければならず、また、その対応するカラムのデータ型には互換性がな ければなりません。

By default, the result of UNION does not contain any duplicate rows unless the ALL clause is specified.

デフォルトでは、ALL 句が指定されていない限り、UNION の結果には重 複行を含みません。

Multiple UNION operators in the same SELECT statement are evaluated left to right. Note that the ALL keyword is not global in nature, being applied only for the current pair of table results.

1 つの SELECT 文内の複数の UNION 演算子は、左から右に評価されます。 キーワード ALL は当然グローバルなものではなく、現在の 2 つのテーブ ルの結果に対してのみ適用されます。

INTERSECT 句

table_query INTERSECT
table_query
     [ ORDER BY column [ ASC | DESC ] [, ...] ]
    
where table_query specifies any select expression without an ORDER BY clause. ここで、table_query は、ORDER BY 句を持たない任意の select 式を指定できます。

The INTERSECT clause allows the result to be all rows that are common to the involved queries. (See INTERSECT clause). The two tables that represent the direct operands of the INTERSECT must have the same number of columns, and corresponding columns must be of compatible data types.

INTERSECT 句は、呼び出した問い合わせに共通する行全てを結果とする ことができます。INTERSECT の引数として直接指定された 2 つのテーブ ルは、同一のカラム数でなければならず、また、その対応するカラムの データ型には互換性がなければなりません。

Multiple INTERSECT operators in the same SELECT statement are evaluated left to right.

1 つの SELECT 文内の複数の INTERSECT 演算子は、左から右に評価さ れます。

EXCEPT 句

table_query EXCEPT
     table_query
     [ ORDER BY column [ ASC | DESC ] [, ...] ]
    
where table_query specifies any select expression without an ORDER BY clause. ここで、table_query は、ORDER BY 句を持たない任意の select 式を指定できます。

The EXCEPT clause allows the result to be rows from the upper query that are not in the lower query. (See EXCEPT clause). The two tables that represent the direct operands of the EXCEPT must have the same number of columns, and corresponding columns must be of compatible data types.

EXCEPT 句は、下側の問い合わせの結果に無く上側の問い合わせの結果に ある行を結果とすることができます。EXCEPT の引数として直接指定され た 2 つのテーブルは、同一のカラム数でなければならず、また、その対 応するカラムのデータ型には互換性がなければなりません。

Multiple EXCEPT operators in the same SELECT statement are evaluated left to right.

1 つの SELECT 文内の複数の EXCEPT 演算子は、左から右に評価されま す。

使用法

To join the table films with the table distributors:

テーブル films に、テーブル distributors を結合します。

SELECT f.title, f.did, d.name, f.date_prod, f.kind
    FROM distributors d, films f
    WHERE f.did = d.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
Une Femme est une Femme  |102|Jean Luc Godard |1961-03-12|Romantic
Vertigo                  |103|Paramount       |1958-11-14|Action
Becket                   |103|Paramount       |1964-02-03|Drama
48 Hrs                   |103|Paramount       |1982-10-22|Action
War and Peace            |104|Mosfilm         |1967-02-12|Drama
West Side Story          |105|United Artists  |1961-01-03|Musical
Bananas                  |105|United Artists  |1971-07-13|Comedy
Yojimbo                  |106|Toho            |1961-06-16|Drama
There's a Girl in my Soup|107|Columbia        |1970-06-11|Comedy
Taxi Driver              |107|Columbia        |1975-05-15|Action
Absence of Malice        |107|Columbia        |1981-11-15|Action
Storia di una donna      |108|Westward        |1970-08-15|Romantic
The King and I           |109|20th Century Fox|1956-08-11|Musical
Das Boot                 |110|Bavaria Atelier |1981-11-11|Drama
Bed Knobs and Broomsticks|111|Walt Disney     |          |Musical
  

To sum the column len of all films and group the results by kind:

films からカラム 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 len of all films, group the results by kind and show those group totals that are less than 5 hours:

filmsからカラム len の総和を求め、その結果を kind でグループ化します。そして、総和が 5 時 間未満となるグループを示します。

SELECT kind, SUM(len) AS total
    FROM films
    GROUP BY kind
    HAVING SUM(len) < INTERVAL '5 hour';

    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 (name):

以下の 2 つの例は、2 番目のカラム( name )の 内容にしたがって個々の結果をソートするという同一のものです。

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
  

This example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with letter W in each table. Only distinct rows are to be used, so the ALL keyword is omitted:

この例は、テーブル distributorsactors から W という文字から始まるもののみ抽出 した結果からなる union をどのように取得するのかを示したものです。

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

互換性

拡張

Postgres allows one to omit the FROM clause from a query. This feature was retained from the original PostQuel query language:

Postgres では問い合わせから FROM 句を省略することができます。この機能は、 元々の PostQuel 問い合わせ言語から残っているものです。

SELECT distributors.* WHERE name = 'Westwood';

    did|name
    ---+----------------
    108|Westward
  

SQL92

SELECT Clause

In the SQL92 standard, the optional keyword "AS" is just noise and can be omitted without affecting the meaning. The Postgres parser requires this keyword when renaming columns because the type extensibility features lead to parsing ambiguities in this context.

SQL92 標準では、オプションキーワード "AS" はノイズ でしかなく、その意味に影響を与えることなく省略できます。 Postgres のパーサはカラム名を変更する場合に はこのキーワードを必要とします。型拡張機能がこのコンテキストで曖昧な解 析を引き起こしてしまうからです。

In the SQL92 standard, the new column name specified in an "AS" clause may be referenced in GROUP BY and HAVING clauses. This is not currently allowed in Postgres.

SQL92 標準では、"AS" 句で指定した新しいカラ ム名を GROUP BY 及び、HAVING 句で参照することができます。現在 Postgres ではこれは許されません。

The DISTINCT ON phrase is not part of SQL92.

DISTINCT ON 句はSQL92 にはありません。

UNION 句

The SQL92 syntax for UNION allows an additional CORRESPONDING BY clause:

SQL92 における UNION の構文では、更に CORRESPONDING BY 句を使うことができます。

 
table_query UNION [ALL]
    [CORRESPONDING [BY (column [,...])]]
    table_query
     

The CORRESPONDING BY clause is not supported by Postgres.

CORRESPONDING BY 句は、Postgres では サポートされていません。