.\" This manpage has been automatically generated by docbook2man .\" from a DocBook document. This tool can be found at: .\" .\" Please send any bug reports, improvements, comments, patches, .\" etc. to Steve Cheng . .TH "SELECT" "" "02 July 1999" "SQL - Language Statements" "" .SH NAME SELECT \- Retrieve rows from a table or view. .SH SYNOPSIS 1998-09-24 .nf SELECT [ALL|DISTINCT [ON \fIcolumn\fR] ] \fIexpression\fR [ AS \fIname\fR ] [, ...] [ INTO [TEMP] [TABLE] \fInew_table\fR ] [ FROM \fItable\fR [\fIalias\fR ] [, ...] ] [ WHERE \fIcondition\fR ] [ GROUP BY \fIcolumn\fR [, ...] ] [ HAVING \fIcondition\fR [, ...] ] [ { UNION [ALL] | INTERSECT | EXCEPT } \fIselect\fR ] [ ORDER BY \fIcolumn\fR [ ASC | DESC ] [, ...] ] [ FOR UPDATE [OF class_name...]] [ LIMIT count [OFFSET|, count]] .fi .SS "INPUTS" .PP .TP \fB \fIexpression\fB \fR The name of a table's column or an expression. .TP \fB \fIname\fB \fR Specifies another name for a column or an expression using the AS clause. \fIname\fR cannot be used in the WHERE condition. It can, however, be referenced in associated ORDER BY or GROUP BY clauses. .TP \fB TEMP \fR The table is created unique to this session, and is automatically dropped on session exit. .TP \fB \fInew_table\fB \fR 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 (\fInew_table\fR) will be created automatically and should not exist before this command. Refer to \fBSELECT INTO\fR for more information. .sp .RS .B "Note:" The \fBCREATE TABLE AS\fR statement will also create a new table from a select query. .RE .TP \fB \fItable\fB \fR The name of an existing table referenced by the FROM clause. .TP \fB \fIalias\fB \fR An alternate name for the preceding \fItable\fR. It is used for brevity or to eliminate ambiguity for joins within a single table. .TP \fB \fIcondition\fB \fR A boolean expression giving a result of true or false. See the WHERE clause. .TP \fB \fIcolumn\fB \fR The name of a table's column. .TP \fB \fIselect\fB \fR A select statement with all features except the ORDER BY clause. .SS "OUTPUTS" .PP .TP \fB Rows \fR The complete set of rows resulting from the query specification. .TP \fB \fIcount\fB \fR The count of rows returned by the query. .SH "DESCRIPTION" .PP \fBSELECT\fR 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. .PP \fBDISTINCT\fR will eliminate all duplicate rows from the selection. \fBDISTINCT ON \fIcolumn\fB\fR will eliminate all duplicates in the specified column; this is equivalent to using \fBGROUP BY \fIcolumn\fB\fR. \fBALL\fR will return all candidate rows, including duplicates. .PP The GROUP BY clause allows a user to divide a table conceptually into groups. (See GROUP BY clause). .PP The HAVING clause specifies a grouped table derived by the elimination of groups from the result of the previously specified clause. (See HAVING clause). .PP 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) .PP The UNION clause allows the result to be the collection of rows returned by the queries involved. (See UNION clause). .PP The INTERSECT give you the rows that are common to both queries. (See INTERSECT clause). .PP The EXCEPT give you the rows in the upper query not in the lower query. (See EXCEPT clause). .PP The FOR UPDATE clause allows the SELECT statement to perform exclusive locking of selected rows. (See EXCEPT clause). .PP The LIMIT...OFFSET clause allows control over which rows are returned by the query. .PP You must have SELECT privilege to a table to read its values (See \fBGRANT\fR/\fBREVOKE\fR statements). .SS "WHERE CLAUSE" .PP The optional WHERE condition has the general form: .nf WHERE \fIexpr\fR \fIETER">c\fRe\fI"PAR\fRreplaceable> [ \fIlog_op\fR ... ] .fi where \fIcond_op\fR can be one of: =, , =, , = or , a conditional operator like ALL, ANY, IN, LIKE, et cetera or a locally-defined operator, and \fIlog_op\fR 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. .SS "GROUP BY CLAUSE" .PP GROUP BY specifies a grouped table derived by the application of this clause: .nf GROUP BY \fIcolumn\fR [, ...] .fi .PP 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. .SS "HAVING CLAUSE" .PP The optional HAVING condition has the general form: .nf HAVING \fIcond_expr\fR .fi where \fIcond_expr\fR is the same as specified for the WHERE clause. .PP HAVING specifies a grouped table derived by the elimination of groups from the result of the previously specified clause that do not meet the \fIcond_expr\fR. .PP Each column referenced in \fIcond_expr\fR shall unambiguously reference a grouping column. .SS "ORDER BY CLAUSE" .PP .nf ORDER BY \fIcolumn\fR [ ASC | DESC ] [, ...] .fi .PP \fIcolumn\fR can be either a column name or an ordinal number. .PP 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.: .nf SELECT title, date_prod + 1 AS newlen FROM films ORDER BY newlen; .fi .PP >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: .nf SELECT name FROM distributors ORDER BY code; .fi .PP 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. .SS "UNION CLAUSE" .PP .nf \fItable_query\fR UNION [ ALL ] \fItable_query\fR [ ORDER BY \fIcolumn\fR [ ASC | DESC ] [, ...] ] .fi where \fItable_query\fR specifies any select expression without an ORDER BY clause. .PP 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. .PP By default, the result of UNION does not contain any duplicate rows unless the ALL clause is specified. .PP 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. .SS "INTERSECT CLAUSE" .PP .nf \fItable_query\fR INTERSECT \fItable_query\fR [ ORDER BY \fIcolumn\fR [ ASC | DESC ] [, ...] ] .fi where \fItable_query\fR specifies any select expression without an ORDER BY clause. .PP 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. .PP Multiple INTERSECT operators in the same SELECT statement are evaluated left to right. .SS "EXCEPT CLAUSE" .PP .nf \fItable_query\fR EXCEPT \fItable_query\fR [ ORDER BY \fIcolumn\fR [ ASC | DESC ] [, ...] ] .fi where \fItable_query\fR specifies any select expression without an ORDER BY clause. .PP 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. .PP Multiple EXCEPT operators in the same SELECT statement are evaluated left to right. .SH "USAGE" .PP To join the table films with the table distributors: .nf 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 .fi .PP To sum the column len of all films and group the results by kind: .nf 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 .fi .PP To sum the column len of all films, group the results by kind and show those group totals that are less than 5 hours: .nf 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 .fi .PP The following two examples are identical ways of sorting the individual results according to the contents of the second column (name): .nf 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 .fi .PP 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: .nf -- 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 .fi .SH "COMPATIBILITY" .PP .SS "EXTENSIONS" .PP Postgres allows one to omit the \fBFROM\fR clause from a query. This feature was retained from the original PostQuel query language: .nf SELECT distributors.* WHERE name = 'Westwood'; did|name ---+---------------- 108|Westward .fi .SS "SQL92" .PP .SS "SELECT CLAUSE" .PP 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. .PP 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. .PP The DISTINCT ON phrase is not part of SQL92. .SS "UNION CLAUSE" .PP The SQL92 syntax for UNION allows an additional CORRESPONDING BY clause: .nf \fItable_query\fR UNION [ALL] [CORRESPONDING [BY (\fIcolumn\fR [,...])]] \fItable_query\fR .fi .PP The CORRESPONDING BY clause is not supported by Postgres.