Sophie

Sophie

distrib > Mandriva > 2008.1 > x86_64 > media > main-testing > by-pkgid > bab02a23fa9f3df8d66a9a3231b50245 > files > 812

postgresql8.3-docs-8.3.6-2mdv2008.1.x86_64.rpm

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>SELECT</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 8.3.6 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="SQL Commands"
HREF="sql-commands.html"><LINK
REL="PREVIOUS"
TITLE="SAVEPOINT"
HREF="sql-savepoint.html"><LINK
REL="NEXT"
TITLE="SELECT INTO"
HREF="sql-selectinto.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2009-02-03T04:34:16"></HEAD
><BODY
CLASS="REFENTRY"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
>PostgreSQL 8.3.6 Documentation</TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="sql-savepoint.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="sql-savepoint.html"
>Fast Backward</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="top"
><A
HREF="sql-selectinto.html"
>Fast Forward</A
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="top"
><A
HREF="sql-selectinto.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="SQL-SELECT"
></A
>SELECT</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN59451"
></A
><H2
>Name</H2
>SELECT&nbsp;--&nbsp;retrieve rows from a table or view</DIV
><A
NAME="AEN59454"
></A
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN59456"
></A
><H2
>Synopsis</H2
><PRE
CLASS="SYNOPSIS"
>SELECT [ ALL | DISTINCT [ ON ( <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [, ...] ) ] ]
    * | <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [ AS <TT
CLASS="REPLACEABLE"
><I
>output_name</I
></TT
> ] [, ...]
    [ FROM <TT
CLASS="REPLACEABLE"
><I
>from_item</I
></TT
> [, ...] ]
    [ WHERE <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
> ]
    [ GROUP BY <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [, ...] ]
    [ HAVING <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
> [, ...] ]
    [ { UNION | INTERSECT | EXCEPT } [ ALL ] <TT
CLASS="REPLACEABLE"
><I
>select</I
></TT
> ]
    [ ORDER BY <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [ ASC | DESC | USING <TT
CLASS="REPLACEABLE"
><I
>operator</I
></TT
> ] [ NULLS { FIRST | LAST } ] [, ...] ]
    [ LIMIT { <TT
CLASS="REPLACEABLE"
><I
>count</I
></TT
> | ALL } ]
    [ OFFSET <TT
CLASS="REPLACEABLE"
><I
>start</I
></TT
> ]
    [ FOR { UPDATE | SHARE } [ OF <TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
> [, ...] ] [ NOWAIT ] [...] ]

where <TT
CLASS="REPLACEABLE"
><I
>from_item</I
></TT
> can be one of:

    [ ONLY ] <TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
> [ * ] [ [ AS ] <TT
CLASS="REPLACEABLE"
><I
>alias</I
></TT
> [ ( <TT
CLASS="REPLACEABLE"
><I
>column_alias</I
></TT
> [, ...] ) ] ]
    ( <TT
CLASS="REPLACEABLE"
><I
>select</I
></TT
> ) [ AS ] <TT
CLASS="REPLACEABLE"
><I
>alias</I
></TT
> [ ( <TT
CLASS="REPLACEABLE"
><I
>column_alias</I
></TT
> [, ...] ) ]
    <TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
> ( [ <TT
CLASS="REPLACEABLE"
><I
>argument</I
></TT
> [, ...] ] ) [ AS ] <TT
CLASS="REPLACEABLE"
><I
>alias</I
></TT
> [ ( <TT
CLASS="REPLACEABLE"
><I
>column_alias</I
></TT
> [, ...] | <TT
CLASS="REPLACEABLE"
><I
>column_definition</I
></TT
> [, ...] ) ]
    <TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
> ( [ <TT
CLASS="REPLACEABLE"
><I
>argument</I
></TT
> [, ...] ] ) AS ( <TT
CLASS="REPLACEABLE"
><I
>column_definition</I
></TT
> [, ...] )
    <TT
CLASS="REPLACEABLE"
><I
>from_item</I
></TT
> [ NATURAL ] <TT
CLASS="REPLACEABLE"
><I
>join_type</I
></TT
> <TT
CLASS="REPLACEABLE"
><I
>from_item</I
></TT
> [ ON <TT
CLASS="REPLACEABLE"
><I
>join_condition</I
></TT
> | USING ( <TT
CLASS="REPLACEABLE"
><I
>join_column</I
></TT
> [, ...] ) ]</PRE
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN59491"
></A
><H2
>Description</H2
><P
>   <TT
CLASS="COMMAND"
>SELECT</TT
> retrieves rows from zero or more tables.
   The general processing of <TT
CLASS="COMMAND"
>SELECT</TT
> is as follows:

   <P
></P
></P><OL
TYPE="1"
><LI
><P
>      All elements in the <TT
CLASS="LITERAL"
>FROM</TT
> list are computed.
      (Each element in the <TT
CLASS="LITERAL"
>FROM</TT
> list is a real or
      virtual table.)  If more than one element is specified in the
      <TT
CLASS="LITERAL"
>FROM</TT
> list, they are cross-joined together.
      (See <A
HREF="sql-select.html#SQL-FROM"
><I
><I
>FROM</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      If the <TT
CLASS="LITERAL"
>WHERE</TT
> clause is specified, all rows
      that do not satisfy the condition are eliminated from the
      output.  (See <A
HREF="sql-select.html#SQL-WHERE"
><I
><I
>WHERE</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      If the <TT
CLASS="LITERAL"
>GROUP BY</TT
> clause is specified, the
      output is divided into groups of rows that match on one or more
      values.  If the <TT
CLASS="LITERAL"
>HAVING</TT
> clause is present, it
      eliminates groups that do not satisfy the given condition.  (See
      <A
HREF="sql-select.html#SQL-GROUPBY"
><I
><I
>GROUP BY</I
> Clause</I
></A
> and
      <A
HREF="sql-select.html#SQL-HAVING"
><I
><I
>HAVING</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      The actual output rows are computed using the
      <TT
CLASS="COMMAND"
>SELECT</TT
> output expressions for each selected
      row.  (See
      <A
HREF="sql-select.html#SQL-SELECT-LIST"
><I
><I
>SELECT</I
> List</I
></A
>
      below.)
     </P
></LI
><LI
><P
>      Using the operators <TT
CLASS="LITERAL"
>UNION</TT
>,
      <TT
CLASS="LITERAL"
>INTERSECT</TT
>, and <TT
CLASS="LITERAL"
>EXCEPT</TT
>, the
      output of more than one <TT
CLASS="COMMAND"
>SELECT</TT
> statement can
      be combined to form a single result set.  The
      <TT
CLASS="LITERAL"
>UNION</TT
> operator returns all rows that are in
      one or both of the result sets.  The
      <TT
CLASS="LITERAL"
>INTERSECT</TT
> operator returns all rows that are
      strictly in both result sets.  The <TT
CLASS="LITERAL"
>EXCEPT</TT
>
      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 <TT
CLASS="LITERAL"
>ALL</TT
> is specified. (See
      <A
HREF="sql-select.html#SQL-UNION"
><I
><I
>UNION</I
> Clause</I
></A
>, <A
HREF="sql-select.html#SQL-INTERSECT"
><I
><I
>INTERSECT</I
> Clause</I
></A
>, and
      <A
HREF="sql-select.html#SQL-EXCEPT"
><I
><I
>EXCEPT</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      If the <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause is specified, the
      returned rows are sorted in the specified order.  If
      <TT
CLASS="LITERAL"
>ORDER BY</TT
> is not given, the rows are returned
      in whatever order the system finds fastest to produce.  (See
      <A
HREF="sql-select.html#SQL-ORDERBY"
><I
><I
>ORDER BY</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      <TT
CLASS="LITERAL"
>DISTINCT</TT
> eliminates duplicate rows from the
      result.  <TT
CLASS="LITERAL"
>DISTINCT ON</TT
> eliminates rows that
      match on all the specified expressions.  <TT
CLASS="LITERAL"
>ALL</TT
>
      (the default) will return all candidate rows, including
      duplicates.  (See <A
HREF="sql-select.html#SQL-DISTINCT"
><I
><I
>DISTINCT</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      If the <TT
CLASS="LITERAL"
>LIMIT</TT
> or <TT
CLASS="LITERAL"
>OFFSET</TT
>
      clause is specified, the <TT
CLASS="COMMAND"
>SELECT</TT
> statement
      only returns a subset of the result rows. (See <A
HREF="sql-select.html#SQL-LIMIT"
><I
><I
>LIMIT</I
> Clause</I
></A
> below.)
     </P
></LI
><LI
><P
>      If <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> or <TT
CLASS="LITERAL"
>FOR SHARE</TT
>
      is specified, the
      <TT
CLASS="COMMAND"
>SELECT</TT
> statement locks the selected rows
      against concurrent updates.  (See <A
HREF="sql-select.html#SQL-FOR-UPDATE-SHARE"
><I
><I
>FOR UPDATE</I
>/<I
>FOR SHARE</I
> Clause</I
></A
> below.)
     </P
></LI
></OL
><P>
  </P
><P
>   You must have <TT
CLASS="LITERAL"
>SELECT</TT
> privilege on a table to
   read its values.  The use of <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> or
   <TT
CLASS="LITERAL"
>FOR SHARE</TT
> requires
   <TT
CLASS="LITERAL"
>UPDATE</TT
> privilege as well.
  </P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN59558"
></A
><H2
>Parameters</H2
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-FROM"
></A
><H3
><TT
CLASS="LITERAL"
>FROM</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>FROM</TT
> clause specifies one or more source
    tables for the <TT
CLASS="COMMAND"
>SELECT</TT
>.  If multiple sources are
    specified, the result is the Cartesian product (cross join) of all
    the sources.  But usually qualification conditions
    are added to restrict the returned rows to a small subset of the
    Cartesian product.
   </P
><P
>    The <TT
CLASS="LITERAL"
>FROM</TT
> clause can contain the following
    elements:

    <P
></P
></P><DIV
CLASS="VARIABLELIST"
><DL
><DT
><TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
></DT
><DD
><P
>        The name (optionally schema-qualified) of an existing table or
        view.  If <TT
CLASS="LITERAL"
>ONLY</TT
> is specified, only that table is
        scanned.  If <TT
CLASS="LITERAL"
>ONLY</TT
> is not specified, the table and
        all its descendant tables (if any) are scanned.  <TT
CLASS="LITERAL"
>*</TT
>
        can be appended to the table name to indicate that descendant
        tables are to be scanned, but in the current version, this is
        the default behavior.  (In releases before 7.1,
        <TT
CLASS="LITERAL"
>ONLY</TT
> was the default behavior.)  The default
        behavior can be modified by changing the <A
HREF="runtime-config-compatible.html#GUC-SQL-INHERITANCE"
>sql_inheritance</A
> configuration option.
       </P
></DD
><DT
><TT
CLASS="REPLACEABLE"
><I
>alias</I
></TT
></DT
><DD
><P
>        A substitute name for the <TT
CLASS="LITERAL"
>FROM</TT
> 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
        <TT
CLASS="LITERAL"
>FROM foo AS f</TT
>, the remainder of the
        <TT
CLASS="COMMAND"
>SELECT</TT
> must refer to this <TT
CLASS="LITERAL"
>FROM</TT
>
        item as <TT
CLASS="LITERAL"
>f</TT
> not <TT
CLASS="LITERAL"
>foo</TT
>.  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.
       </P
></DD
><DT
><TT
CLASS="REPLACEABLE"
><I
>select</I
></TT
></DT
><DD
><P
>        A sub-<TT
CLASS="COMMAND"
>SELECT</TT
> can appear in the
        <TT
CLASS="LITERAL"
>FROM</TT
> clause.  This acts as though its
        output were created as a temporary table for the duration of
        this single <TT
CLASS="COMMAND"
>SELECT</TT
> command.  Note that the
        sub-<TT
CLASS="COMMAND"
>SELECT</TT
> must be surrounded by
        parentheses, and an alias <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>must</I
></SPAN
> be
        provided for it.  A
        <A
HREF="sql-values.html"
><I
>VALUES</I
></A
> command
        can also be used here.
       </P
></DD
><DT
><TT
CLASS="REPLACEABLE"
><I
>function_name</I
></TT
></DT
><DD
><P
>        Function calls can appear in the <TT
CLASS="LITERAL"
>FROM</TT
>
        clause.  (This is especially useful for functions that return
        result sets, but any function can be used.)  This acts as
        though its output were created as a temporary table for the
        duration of this single <TT
CLASS="COMMAND"
>SELECT</TT
> command. An
        alias can also be used. 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. If
        the function has been defined as returning the <TT
CLASS="TYPE"
>record</TT
>
        data type, then an alias or the key word <TT
CLASS="LITERAL"
>AS</TT
> must
        be present, followed by a column definition list in the form
        <TT
CLASS="LITERAL"
>( <TT
CLASS="REPLACEABLE"
><I
>column_name</I
></TT
> <TT
CLASS="REPLACEABLE"
><I
>data_type</I
></TT
> [<SPAN
CLASS="OPTIONAL"
>, ... </SPAN
>]
        )</TT
>.  The column definition list must match the actual
        number and types of columns returned by the function.
       </P
></DD
><DT
><TT
CLASS="REPLACEABLE"
><I
>join_type</I
></TT
></DT
><DD
><P
>        One of
        <P
></P
></P><UL
><LI
><P
><TT
CLASS="LITERAL"
>[ INNER ] JOIN</TT
></P
></LI
><LI
><P
><TT
CLASS="LITERAL"
>LEFT [ OUTER ] JOIN</TT
></P
></LI
><LI
><P
><TT
CLASS="LITERAL"
>RIGHT [ OUTER ] JOIN</TT
></P
></LI
><LI
><P
><TT
CLASS="LITERAL"
>FULL [ OUTER ] JOIN</TT
></P
></LI
><LI
><P
><TT
CLASS="LITERAL"
>CROSS JOIN</TT
></P
></LI
></UL
><P>

        For the <TT
CLASS="LITERAL"
>INNER</TT
> and <TT
CLASS="LITERAL"
>OUTER</TT
> join types, a
        join condition must be specified, namely exactly one of
        <TT
CLASS="LITERAL"
>NATURAL</TT
>, <TT
CLASS="LITERAL"
>ON <TT
CLASS="REPLACEABLE"
><I
>join_condition</I
></TT
></TT
>, or
        <TT
CLASS="LITERAL"
>USING (<TT
CLASS="REPLACEABLE"
><I
>join_column</I
></TT
> [, ...])</TT
>.
        See below for the meaning.  For <TT
CLASS="LITERAL"
>CROSS JOIN</TT
>,
        none of these clauses can appear.
       </P
><P
>        A <TT
CLASS="LITERAL"
>JOIN</TT
> clause combines two
        <TT
CLASS="LITERAL"
>FROM</TT
> items.  Use parentheses if necessary to
        determine the order of nesting.  In the absence of parentheses,
        <TT
CLASS="LITERAL"
>JOIN</TT
>s nest left-to-right.  In any case
        <TT
CLASS="LITERAL"
>JOIN</TT
> binds more tightly than the commas
        separating <TT
CLASS="LITERAL"
>FROM</TT
> items.
       </P
><P
>        <TT
CLASS="LITERAL"
>CROSS JOIN</TT
> and <TT
CLASS="LITERAL"
>INNER JOIN</TT
>
        produce a simple Cartesian product, the same result as you get from
        listing the two items at the top level of <TT
CLASS="LITERAL"
>FROM</TT
>,
        but restricted by the join condition (if any).
        <TT
CLASS="LITERAL"
>CROSS JOIN</TT
> is equivalent to <TT
CLASS="LITERAL"
>INNER JOIN ON
        (TRUE)</TT
>, that is, no rows are removed by qualification.
        These join types are just a notational convenience, since they
        do nothing you couldn't do with plain <TT
CLASS="LITERAL"
>FROM</TT
> and
        <TT
CLASS="LITERAL"
>WHERE</TT
>.
       </P
><P
>        <TT
CLASS="LITERAL"
>LEFT OUTER JOIN</TT
> 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 <TT
CLASS="LITERAL"
>JOIN</TT
>
        clause's own condition is considered while deciding which rows
        have matches.  Outer conditions are applied afterwards.
       </P
><P
>        Conversely, <TT
CLASS="LITERAL"
>RIGHT OUTER JOIN</TT
> 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 <TT
CLASS="LITERAL"
>LEFT
        OUTER JOIN</TT
> by switching the left and right inputs.
       </P
><P
>        <TT
CLASS="LITERAL"
>FULL OUTER JOIN</TT
> 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).
       </P
></DD
><DT
><TT
CLASS="LITERAL"
>ON <TT
CLASS="REPLACEABLE"
><I
>join_condition</I
></TT
></TT
></DT
><DD
><P
>        <TT
CLASS="REPLACEABLE"
><I
>join_condition</I
></TT
> is
        an expression resulting in a value of type
        <TT
CLASS="TYPE"
>boolean</TT
> (similar to a <TT
CLASS="LITERAL"
>WHERE</TT
>
        clause) that specifies which rows in a join are considered to
        match.
       </P
></DD
><DT
><TT
CLASS="LITERAL"
>USING ( <TT
CLASS="REPLACEABLE"
><I
>join_column</I
></TT
> [, ...] )</TT
></DT
><DD
><P
>        A clause of the form <TT
CLASS="LITERAL"
>USING ( a, b, ... )</TT
> is
        shorthand for <TT
CLASS="LITERAL"
>ON left_table.a = right_table.a AND
        left_table.b = right_table.b ...</TT
>.  Also,
        <TT
CLASS="LITERAL"
>USING</TT
> implies that only one of each pair of
        equivalent columns will be included in the join output, not
        both.
       </P
></DD
><DT
><TT
CLASS="LITERAL"
>NATURAL</TT
></DT
><DD
><P
>        <TT
CLASS="LITERAL"
>NATURAL</TT
> is shorthand for a
        <TT
CLASS="LITERAL"
>USING</TT
> list that mentions all columns in the two
        tables that have the same names.
       </P
></DD
></DL
></DIV
><P>
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-WHERE"
></A
><H3
><TT
CLASS="LITERAL"
>WHERE</TT
> Clause</H3
><P
>    The optional <TT
CLASS="LITERAL"
>WHERE</TT
> clause has the general form
</P><PRE
CLASS="SYNOPSIS"
>WHERE <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
></PRE
><P>
    where <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
> is
    any expression that evaluates to a result of type
    <TT
CLASS="TYPE"
>boolean</TT
>.  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.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-GROUPBY"
></A
><H3
><TT
CLASS="LITERAL"
>GROUP BY</TT
> Clause</H3
><P
>    The optional <TT
CLASS="LITERAL"
>GROUP BY</TT
> clause has the general form
</P><PRE
CLASS="SYNOPSIS"
>GROUP BY <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [, ...]</PRE
><P>
   </P
><P
>    <TT
CLASS="LITERAL"
>GROUP BY</TT
> will condense into a single row all
    selected rows that share the same values for the grouped
    expressions.  <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> can be an input column
    name, or the name or ordinal number of an output column
    (<TT
CLASS="COMMAND"
>SELECT</TT
> list item), or an arbitrary
    expression formed from input-column values.  In case of ambiguity,
    a <TT
CLASS="LITERAL"
>GROUP BY</TT
> name will be interpreted as an
    input-column name rather than an output column name.
   </P
><P
>    Aggregate functions, if any are used, are computed across all rows
    making up each group, producing a separate value for each group
    (whereas without <TT
CLASS="LITERAL"
>GROUP BY</TT
>, an aggregate
    produces a single value computed across all the selected rows).
    When <TT
CLASS="LITERAL"
>GROUP BY</TT
> is present, it is not valid for
    the <TT
CLASS="COMMAND"
>SELECT</TT
> list expressions to refer to
    ungrouped columns except within aggregate functions, since there
    would be more than one possible value to return for an ungrouped
    column.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-HAVING"
></A
><H3
><TT
CLASS="LITERAL"
>HAVING</TT
> Clause</H3
><P
>    The optional <TT
CLASS="LITERAL"
>HAVING</TT
> clause has the general form
</P><PRE
CLASS="SYNOPSIS"
>HAVING <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
></PRE
><P>
    where <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
> is
    the same as specified for the <TT
CLASS="LITERAL"
>WHERE</TT
> clause.
   </P
><P
>    <TT
CLASS="LITERAL"
>HAVING</TT
> eliminates group rows that do not
    satisfy the condition.  <TT
CLASS="LITERAL"
>HAVING</TT
> is different
    from <TT
CLASS="LITERAL"
>WHERE</TT
>: <TT
CLASS="LITERAL"
>WHERE</TT
> filters
    individual rows before the application of <TT
CLASS="LITERAL"
>GROUP
    BY</TT
>, while <TT
CLASS="LITERAL"
>HAVING</TT
> filters group rows
    created by <TT
CLASS="LITERAL"
>GROUP BY</TT
>.  Each column referenced in
    <TT
CLASS="REPLACEABLE"
><I
>condition</I
></TT
> must
    unambiguously reference a grouping column, unless the reference
    appears within an aggregate function.
   </P
><P
>    The presence of <TT
CLASS="LITERAL"
>HAVING</TT
> turns a query into a grouped
    query even if there is no <TT
CLASS="LITERAL"
>GROUP BY</TT
> clause.  This is the
    same as what happens when the query contains aggregate functions but
    no <TT
CLASS="LITERAL"
>GROUP BY</TT
> clause.  All the selected rows are considered to
    form a single group, and the <TT
CLASS="COMMAND"
>SELECT</TT
> list and
    <TT
CLASS="LITERAL"
>HAVING</TT
> clause can only reference table columns from
    within aggregate functions.  Such a query will emit a single row if the
    <TT
CLASS="LITERAL"
>HAVING</TT
> condition is true, zero rows if it is not true.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-SELECT-LIST"
></A
><H3
><TT
CLASS="COMMAND"
>SELECT</TT
> List</H3
><P
>    The <TT
CLASS="COMMAND"
>SELECT</TT
> list (between the key words
    <TT
CLASS="LITERAL"
>SELECT</TT
> and <TT
CLASS="LITERAL"
>FROM</TT
>) specifies expressions
    that form the output rows of the <TT
CLASS="COMMAND"
>SELECT</TT
>
    statement.  The expressions can (and usually do) refer to columns
    computed in the <TT
CLASS="LITERAL"
>FROM</TT
> clause.  Using the clause
    <TT
CLASS="LITERAL"
>AS <TT
CLASS="REPLACEABLE"
><I
>output_name</I
></TT
></TT
>, another
    name can be specified for an output column.  This name is
    primarily used to label the column for display.  It can also be
    used to refer to the column's value in <TT
CLASS="LITERAL"
>ORDER BY</TT
> and
    <TT
CLASS="LITERAL"
>GROUP BY</TT
> clauses, but not in the <TT
CLASS="LITERAL"
>WHERE</TT
> or
    <TT
CLASS="LITERAL"
>HAVING</TT
> clauses; there you must write out the
    expression instead.
   </P
><P
>    Instead of an expression, <TT
CLASS="LITERAL"
>*</TT
> can be written in
    the output list as a shorthand for all the columns of the selected
    rows.  Also, one can write <TT
CLASS="LITERAL"
><TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
>.*</TT
> as a
    shorthand for the columns coming from just that table.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-UNION"
></A
><H3
><TT
CLASS="LITERAL"
>UNION</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>UNION</TT
> clause has this general form:
</P><PRE
CLASS="SYNOPSIS"
><TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> UNION [ ALL ] <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
></PRE
><P>
    <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> is
    any <TT
CLASS="COMMAND"
>SELECT</TT
> statement without an <TT
CLASS="LITERAL"
>ORDER
    BY</TT
>, <TT
CLASS="LITERAL"
>LIMIT</TT
>, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
>, or
    <TT
CLASS="LITERAL"
>FOR SHARE</TT
> clause.
    (<TT
CLASS="LITERAL"
>ORDER BY</TT
> and <TT
CLASS="LITERAL"
>LIMIT</TT
> 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 <TT
CLASS="LITERAL"
>UNION</TT
>, not to its right-hand input
    expression.)
   </P
><P
>    The <TT
CLASS="LITERAL"
>UNION</TT
> operator computes the set union of
    the rows returned by the involved <TT
CLASS="COMMAND"
>SELECT</TT
>
    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
    <TT
CLASS="COMMAND"
>SELECT</TT
> statements that represent the direct
    operands of the <TT
CLASS="LITERAL"
>UNION</TT
> must produce the same
    number of columns, and corresponding columns must be of compatible
    data types.
   </P
><P
>    The result of <TT
CLASS="LITERAL"
>UNION</TT
> does not contain any duplicate
    rows unless the <TT
CLASS="LITERAL"
>ALL</TT
> option is specified.
    <TT
CLASS="LITERAL"
>ALL</TT
> prevents elimination of duplicates.  (Therefore,
    <TT
CLASS="LITERAL"
>UNION ALL</TT
> is usually significantly quicker than
    <TT
CLASS="LITERAL"
>UNION</TT
>; use <TT
CLASS="LITERAL"
>ALL</TT
> when you can.)
   </P
><P
>    Multiple <TT
CLASS="LITERAL"
>UNION</TT
> operators in the same
    <TT
CLASS="COMMAND"
>SELECT</TT
> statement are evaluated left to right,
    unless otherwise indicated by parentheses.
   </P
><P
>    Currently, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and <TT
CLASS="LITERAL"
>FOR SHARE</TT
> cannot be
    specified either for a <TT
CLASS="LITERAL"
>UNION</TT
> result or for any input of a
    <TT
CLASS="LITERAL"
>UNION</TT
>.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-INTERSECT"
></A
><H3
><TT
CLASS="LITERAL"
>INTERSECT</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>INTERSECT</TT
> clause has this general form:
</P><PRE
CLASS="SYNOPSIS"
><TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> INTERSECT [ ALL ] <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
></PRE
><P>
    <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> is
    any <TT
CLASS="COMMAND"
>SELECT</TT
> statement without an <TT
CLASS="LITERAL"
>ORDER
    BY</TT
>, <TT
CLASS="LITERAL"
>LIMIT</TT
>, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
>, or
    <TT
CLASS="LITERAL"
>FOR SHARE</TT
> clause.
   </P
><P
>    The <TT
CLASS="LITERAL"
>INTERSECT</TT
> operator computes the set
    intersection of the rows returned by the involved
    <TT
CLASS="COMMAND"
>SELECT</TT
> statements.  A row is in the
    intersection of two result sets if it appears in both result sets.
   </P
><P
>    The result of <TT
CLASS="LITERAL"
>INTERSECT</TT
> does not contain any
    duplicate rows unless the <TT
CLASS="LITERAL"
>ALL</TT
> option is specified.
    With <TT
CLASS="LITERAL"
>ALL</TT
>, a row that has <TT
CLASS="REPLACEABLE"
><I
>m</I
></TT
> duplicates in the
    left table and <TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
> duplicates in the right table will appear
    min(<TT
CLASS="REPLACEABLE"
><I
>m</I
></TT
>,<TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
>) times in the result set.
   </P
><P
>    Multiple <TT
CLASS="LITERAL"
>INTERSECT</TT
> operators in the same
    <TT
CLASS="COMMAND"
>SELECT</TT
> statement are evaluated left to right,
    unless parentheses dictate otherwise.
    <TT
CLASS="LITERAL"
>INTERSECT</TT
> binds more tightly than
    <TT
CLASS="LITERAL"
>UNION</TT
>.  That is, <TT
CLASS="LITERAL"
>A UNION B INTERSECT
    C</TT
> will be read as <TT
CLASS="LITERAL"
>A UNION (B INTERSECT
    C)</TT
>.
   </P
><P
>    Currently, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and <TT
CLASS="LITERAL"
>FOR SHARE</TT
> cannot be
    specified either for an <TT
CLASS="LITERAL"
>INTERSECT</TT
> result or for any input of
    an <TT
CLASS="LITERAL"
>INTERSECT</TT
>.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-EXCEPT"
></A
><H3
><TT
CLASS="LITERAL"
>EXCEPT</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>EXCEPT</TT
> clause has this general form:
</P><PRE
CLASS="SYNOPSIS"
><TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> EXCEPT [ ALL ] <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
></PRE
><P>
    <TT
CLASS="REPLACEABLE"
><I
>select_statement</I
></TT
> is
    any <TT
CLASS="COMMAND"
>SELECT</TT
> statement without an <TT
CLASS="LITERAL"
>ORDER
    BY</TT
>, <TT
CLASS="LITERAL"
>LIMIT</TT
>, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
>, or
    <TT
CLASS="LITERAL"
>FOR SHARE</TT
> clause.
   </P
><P
>    The <TT
CLASS="LITERAL"
>EXCEPT</TT
> operator computes the set of rows
    that are in the result of the left <TT
CLASS="COMMAND"
>SELECT</TT
>
    statement but not in the result of the right one.
   </P
><P
>    The result of <TT
CLASS="LITERAL"
>EXCEPT</TT
> does not contain any
    duplicate rows unless the <TT
CLASS="LITERAL"
>ALL</TT
> option is specified.
    With <TT
CLASS="LITERAL"
>ALL</TT
>, a row that has <TT
CLASS="REPLACEABLE"
><I
>m</I
></TT
> duplicates in the
    left table and <TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
> duplicates in the right table will appear
    max(<TT
CLASS="REPLACEABLE"
><I
>m</I
></TT
>-<TT
CLASS="REPLACEABLE"
><I
>n</I
></TT
>,0) times in the result set.
   </P
><P
>    Multiple <TT
CLASS="LITERAL"
>EXCEPT</TT
> operators in the same
    <TT
CLASS="COMMAND"
>SELECT</TT
> statement are evaluated left to right,
    unless parentheses dictate otherwise.  <TT
CLASS="LITERAL"
>EXCEPT</TT
> binds at
    the same level as <TT
CLASS="LITERAL"
>UNION</TT
>.
   </P
><P
>    Currently, <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and <TT
CLASS="LITERAL"
>FOR SHARE</TT
> cannot be
    specified either for an <TT
CLASS="LITERAL"
>EXCEPT</TT
> result or for any input of
    an <TT
CLASS="LITERAL"
>EXCEPT</TT
>.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-ORDERBY"
></A
><H3
><TT
CLASS="LITERAL"
>ORDER BY</TT
> Clause</H3
><P
>    The optional <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause has this general form:
</P><PRE
CLASS="SYNOPSIS"
>ORDER BY <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [ ASC | DESC | USING <TT
CLASS="REPLACEABLE"
><I
>operator</I
></TT
> ] [ NULLS { FIRST | LAST } ] [, ...]</PRE
><P>
    The <TT
CLASS="LITERAL"
>ORDER BY</TT
> 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.
   </P
><P
>    Each <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> can be the
    name or ordinal number of an output column
    (<TT
CLASS="COMMAND"
>SELECT</TT
> list item), or it can be an arbitrary
    expression formed from input-column values.
   </P
><P
>    The ordinal number refers to the ordinal (left-to-right) position
    of the result 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 a result column using the
    <TT
CLASS="LITERAL"
>AS</TT
> clause.
   </P
><P
>    It is also possible to use arbitrary expressions in the
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause, including columns that do not
    appear in the <TT
CLASS="COMMAND"
>SELECT</TT
> result list.  Thus the
    following statement is valid:
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT name FROM distributors ORDER BY code;</PRE
><P>
    A limitation of this feature is that an <TT
CLASS="LITERAL"
>ORDER BY</TT
>
    clause applying to the result of a <TT
CLASS="LITERAL"
>UNION</TT
>,
    <TT
CLASS="LITERAL"
>INTERSECT</TT
>, or <TT
CLASS="LITERAL"
>EXCEPT</TT
> clause can only
    specify an output column name or number, not an expression.
   </P
><P
>    If an <TT
CLASS="LITERAL"
>ORDER BY</TT
> expression is a simple name that
    matches both a result column name and an input column name,
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> will interpret it as the result column name.
    This is the opposite of the choice that <TT
CLASS="LITERAL"
>GROUP BY</TT
> will
    make in the same situation.  This inconsistency is made to be
    compatible with the SQL standard.
   </P
><P
>    Optionally one can add the key word <TT
CLASS="LITERAL"
>ASC</TT
> (ascending) or
    <TT
CLASS="LITERAL"
>DESC</TT
> (descending) after any expression in the
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause.  If not specified, <TT
CLASS="LITERAL"
>ASC</TT
> is
    assumed by default.  Alternatively, a specific ordering operator
    name can be specified in the <TT
CLASS="LITERAL"
>USING</TT
> clause.
    An ordering operator must be a less-than or greater-than
    member of some B-tree operator family.
    <TT
CLASS="LITERAL"
>ASC</TT
> is usually equivalent to <TT
CLASS="LITERAL"
>USING &lt;</TT
> and
    <TT
CLASS="LITERAL"
>DESC</TT
> is usually equivalent to <TT
CLASS="LITERAL"
>USING &gt;</TT
>.
    (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.)
   </P
><P
>    If <TT
CLASS="LITERAL"
>NULLS LAST</TT
> is specified, null values sort after all
    non-null values; if <TT
CLASS="LITERAL"
>NULLS FIRST</TT
> is specified, null values
    sort before all non-null values.  If neither is specified, the default
    behavior is <TT
CLASS="LITERAL"
>NULLS LAST</TT
> when <TT
CLASS="LITERAL"
>ASC</TT
> is specified
    or implied, and <TT
CLASS="LITERAL"
>NULLS FIRST</TT
> when <TT
CLASS="LITERAL"
>DESC</TT
> is specified
    (thus, the default is to act as though nulls are larger than non-nulls).
    When <TT
CLASS="LITERAL"
>USING</TT
> is specified, the default nulls ordering depends
    on whether the operator is a less-than or greater-than operator.
   </P
><P
>    Note that ordering options apply only to the expression they follow;
    for example <TT
CLASS="LITERAL"
>ORDER BY x, y DESC</TT
> does not mean
    the same thing as <TT
CLASS="LITERAL"
>ORDER BY x DESC, y DESC</TT
>.
   </P
><P
>    Character-string data is sorted according to the locale-specific
    collation order that was established when the database cluster
    was initialized.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-DISTINCT"
></A
><H3
><TT
CLASS="LITERAL"
>DISTINCT</TT
> Clause</H3
><P
>    If <TT
CLASS="LITERAL"
>DISTINCT</TT
> is specified, all duplicate rows are
    removed from the result set (one row is kept from each group of
    duplicates).  <TT
CLASS="LITERAL"
>ALL</TT
> specifies the opposite: all rows are
    kept; that is the default.
   </P
><P
>    <TT
CLASS="LITERAL"
>DISTINCT ON ( <TT
CLASS="REPLACEABLE"
><I
>expression</I
></TT
> [, ...] )</TT
>
    keeps only the first row of each set of rows where the given
    expressions evaluate to equal.  The <TT
CLASS="LITERAL"
>DISTINCT ON</TT
>
    expressions are interpreted using the same rules as for
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> (see above).  Note that the <SPAN
CLASS="QUOTE"
>"first
    row"</SPAN
> of each set is unpredictable unless <TT
CLASS="LITERAL"
>ORDER
    BY</TT
> is used to ensure that the desired row appears first.  For
    example:
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT DISTINCT ON (location) location, time, report
    FROM weather_reports
    ORDER BY location, time DESC;</PRE
><P>
    retrieves the most recent weather report for each location.  But
    if we had not used <TT
CLASS="LITERAL"
>ORDER BY</TT
> to force descending order
    of time values for each location, we'd have gotten a report from
    an unpredictable time for each location.
   </P
><P
>    The <TT
CLASS="LITERAL"
>DISTINCT ON</TT
> expression(s) must match the leftmost
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> expression(s).  The <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause
    will normally contain additional expression(s) that determine the
    desired precedence of rows within each <TT
CLASS="LITERAL"
>DISTINCT ON</TT
> group.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-LIMIT"
></A
><H3
><TT
CLASS="LITERAL"
>LIMIT</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>LIMIT</TT
> clause consists of two independent
    sub-clauses:
</P><PRE
CLASS="SYNOPSIS"
>LIMIT { <TT
CLASS="REPLACEABLE"
><I
>count</I
></TT
> | ALL }
OFFSET <TT
CLASS="REPLACEABLE"
><I
>start</I
></TT
></PRE
><P>
    <TT
CLASS="REPLACEABLE"
><I
>count</I
></TT
> specifies the
    maximum number of rows to return, while <TT
CLASS="REPLACEABLE"
><I
>start</I
></TT
> specifies the number of rows
    to skip before starting to return rows.  When both are specified,
    <TT
CLASS="REPLACEABLE"
><I
>start</I
></TT
> rows are skipped
    before starting to count the <TT
CLASS="REPLACEABLE"
><I
>count</I
></TT
> rows to be returned.
   </P
><P
>    When using <TT
CLASS="LITERAL"
>LIMIT</TT
>, it is a good idea to use an
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> 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 <TT
CLASS="LITERAL"
>ORDER BY</TT
>.
   </P
><P
>    The query planner takes <TT
CLASS="LITERAL"
>LIMIT</TT
> 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 <TT
CLASS="LITERAL"
>LIMIT</TT
> and <TT
CLASS="LITERAL"
>OFFSET</TT
>.  Thus, using
    different <TT
CLASS="LITERAL"
>LIMIT</TT
>/<TT
CLASS="LITERAL"
>OFFSET</TT
> values to select
    different subsets of a query result <SPAN
CLASS="emphasis"
><I
CLASS="EMPHASIS"
>will give
    inconsistent results</I
></SPAN
> unless you enforce a predictable
    result ordering with <TT
CLASS="LITERAL"
>ORDER BY</TT
>.  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
    <TT
CLASS="LITERAL"
>ORDER BY</TT
> is used to constrain the order.
   </P
><P
>    It is even possible for repeated executions of the same <TT
CLASS="LITERAL"
>LIMIT</TT
>
    query to return different subsets of the rows of a table, if there
    is not an <TT
CLASS="LITERAL"
>ORDER BY</TT
> 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.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="SQL-FOR-UPDATE-SHARE"
></A
><H3
><TT
CLASS="LITERAL"
>FOR UPDATE</TT
>/<TT
CLASS="LITERAL"
>FOR SHARE</TT
> Clause</H3
><P
>    The <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> clause has this form:
</P><PRE
CLASS="SYNOPSIS"
>FOR UPDATE [ OF <TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
> [, ...] ] [ NOWAIT ]</PRE
><P>
   </P
><P
>    The closely related <TT
CLASS="LITERAL"
>FOR SHARE</TT
> clause has this form:
</P><PRE
CLASS="SYNOPSIS"
>FOR SHARE [ OF <TT
CLASS="REPLACEABLE"
><I
>table_name</I
></TT
> [, ...] ] [ NOWAIT ]</PRE
><P>
   </P
><P
>    <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> causes the rows retrieved by the
    <TT
CLASS="COMMAND"
>SELECT</TT
> statement to be locked as though for
    update.  This prevents them from being modified or deleted by
    other transactions until the current transaction ends.  That is,
    other transactions that attempt <TT
CLASS="COMMAND"
>UPDATE</TT
>,
    <TT
CLASS="COMMAND"
>DELETE</TT
>, or <TT
CLASS="COMMAND"
>SELECT FOR UPDATE</TT
>
    of these rows will be blocked until the current transaction ends.
    Also, if an <TT
CLASS="COMMAND"
>UPDATE</TT
>, <TT
CLASS="COMMAND"
>DELETE</TT
>,
    or <TT
CLASS="COMMAND"
>SELECT FOR UPDATE</TT
> from another transaction
    has already locked a selected row or rows, <TT
CLASS="COMMAND"
>SELECT FOR
    UPDATE</TT
> will wait for the other transaction to complete,
    and will then lock and return the updated row (or no row, if the
    row was deleted).  For further discussion see <A
HREF="mvcc.html"
>Chapter 13</A
>.
   </P
><P
>    To prevent the operation from waiting for other transactions to commit,
    use the <TT
CLASS="LITERAL"
>NOWAIT</TT
> option.  <TT
CLASS="COMMAND"
>SELECT FOR UPDATE
    NOWAIT</TT
> reports an error, rather than waiting, if a selected row
    cannot be locked immediately.  Note that <TT
CLASS="LITERAL"
>NOWAIT</TT
> applies only
    to the row-level lock(s) &mdash; the required <TT
CLASS="LITERAL"
>ROW SHARE</TT
>
    table-level lock is still taken in the ordinary way (see
    <A
HREF="mvcc.html"
>Chapter 13</A
>).  You can use the <TT
CLASS="LITERAL"
>NOWAIT</TT
> option of
    <A
HREF="sql-lock.html"
><I
>LOCK</I
></A
>
    if you need to acquire the table-level lock without waiting.
   </P
><P
>    <TT
CLASS="LITERAL"
>FOR SHARE</TT
> behaves similarly, except that it
    acquires a shared rather than exclusive lock on each retrieved
    row.  A shared lock blocks other transactions from performing
    <TT
CLASS="COMMAND"
>UPDATE</TT
>, <TT
CLASS="COMMAND"
>DELETE</TT
>, or <TT
CLASS="COMMAND"
>SELECT
    FOR UPDATE</TT
> on these rows, but it does not prevent them
    from performing <TT
CLASS="COMMAND"
>SELECT FOR SHARE</TT
>.
   </P
><P
>    If specific tables are named in <TT
CLASS="LITERAL"
>FOR UPDATE</TT
>
    or <TT
CLASS="LITERAL"
>FOR SHARE</TT
>,
    then only rows coming from those tables are locked; any other
    tables used in the <TT
CLASS="COMMAND"
>SELECT</TT
> are simply read as
    usual.  A <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> or <TT
CLASS="LITERAL"
>FOR SHARE</TT
>
    clause without a table list affects all tables used in the command.
    If <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> or <TT
CLASS="LITERAL"
>FOR SHARE</TT
> is
    applied to a view or sub-query, it affects all tables used in
    the view or sub-query.
   </P
><P
>    Multiple <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and <TT
CLASS="LITERAL"
>FOR SHARE</TT
>
    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 both <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and
    <TT
CLASS="LITERAL"
>FOR SHARE</TT
> clauses, then it is processed as
    <TT
CLASS="LITERAL"
>FOR UPDATE</TT
>.  Similarly, a table is processed
    as <TT
CLASS="LITERAL"
>NOWAIT</TT
> if that is specified in any of the clauses
    affecting it.
   </P
><P
>    <TT
CLASS="LITERAL"
>FOR UPDATE</TT
> and <TT
CLASS="LITERAL"
>FOR SHARE</TT
> cannot be
    used in contexts where returned rows cannot be clearly identified with
    individual table rows; for example they cannot be used with aggregation.
   </P
><DIV
CLASS="CAUTION"
><P
></P
><TABLE
CLASS="CAUTION"
BORDER="1"
WIDTH="100%"
><TR
><TD
ALIGN="CENTER"
><B
>Caution</B
></TD
></TR
><TR
><TD
ALIGN="LEFT"
><P
>    Avoid locking a row and then modifying it within a later savepoint or
    <SPAN
CLASS="APPLICATION"
>PL/pgSQL</SPAN
> exception block.  A subsequent
    rollback would cause the lock to be lost.  For example:
</P><PRE
CLASS="PROGRAMLISTING"
>BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
SAVEPOINT s;
UPDATE mytable SET ... WHERE key = 1;
ROLLBACK TO s;</PRE
><P>
    After the <TT
CLASS="COMMAND"
>ROLLBACK</TT
>, the row is effectively unlocked, rather
    than returned to its pre-savepoint state of being locked but not modified.
    This hazard occurs if a row locked in the current transaction is updated
    or deleted, or if a shared lock is upgraded to exclusive: in all these
    cases, the former lock state is forgotten.  If the transaction is then
    rolled back to a state between the original locking command and the
    subsequent change, the row will appear not to be locked at all.  This is
    an implementation deficiency which will be addressed in a future release
    of <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
>.
   </P
></TD
></TR
></TABLE
></DIV
><DIV
CLASS="CAUTION"
><P
></P
><TABLE
CLASS="CAUTION"
BORDER="1"
WIDTH="100%"
><TR
><TD
ALIGN="CENTER"
><B
>Caution</B
></TD
></TR
><TR
><TD
ALIGN="LEFT"
><P
>    It is possible for a <TT
CLASS="COMMAND"
>SELECT</TT
> command using both
    <TT
CLASS="LITERAL"
>LIMIT</TT
> and  <TT
CLASS="LITERAL"
>FOR UPDATE/SHARE</TT
>
    clauses to return fewer rows than specified by <TT
CLASS="LITERAL"
>LIMIT</TT
>.
    This is because <TT
CLASS="LITERAL"
>LIMIT</TT
> is applied first.  The command
    selects the specified number of rows,
    but might then block trying to obtain lock on one or more of them.
    Once the <TT
CLASS="LITERAL"
>SELECT</TT
> unblocks, the row might have been deleted
    or updated so that it does not meet the query <TT
CLASS="LITERAL"
>WHERE</TT
> condition
    anymore, in which case it will not be returned.
   </P
></TD
></TR
></TABLE
></DIV
><DIV
CLASS="CAUTION"
><P
></P
><TABLE
CLASS="CAUTION"
BORDER="1"
WIDTH="100%"
><TR
><TD
ALIGN="CENTER"
><B
>Caution</B
></TD
></TR
><TR
><TD
ALIGN="LEFT"
><P
>    Similarly, it is possible for a <TT
CLASS="COMMAND"
>SELECT</TT
> command
    using <TT
CLASS="LITERAL"
>ORDER BY</TT
> and <TT
CLASS="LITERAL"
>FOR
    UPDATE/SHARE</TT
> to return rows out of order.  This is
    because <TT
CLASS="LITERAL"
>ORDER BY</TT
> is applied first.  The command
    orders the result, but might then block trying to obtain a lock
    on one or more of the rows.  Once the <TT
CLASS="LITERAL"
>SELECT</TT
>
    unblocks, one of the ordered columns might have been modified
    and be returned out of order.  A workaround is to perform
    <TT
CLASS="COMMAND"
>SELECT ... FOR UPDATE/SHARE</TT
> and then <TT
CLASS="COMMAND"
>SELECT
    ... ORDER BY</TT
>.
   </P
></TD
></TR
></TABLE
></DIV
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN60043"
></A
><H2
>Examples</H2
><P
>   To join the table <TT
CLASS="LITERAL"
>films</TT
> with the table
   <TT
CLASS="LITERAL"
>distributors</TT
>:

</P><PRE
CLASS="PROGRAMLISTING"
>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
 ...</PRE
><P>
  </P
><P
>   To sum the column <TT
CLASS="LITERAL"
>len</TT
> of all films and group
   the results by <TT
CLASS="LITERAL"
>kind</TT
>:

</P><PRE
CLASS="PROGRAMLISTING"
>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</PRE
><P>
  </P
><P
>   To sum the column <TT
CLASS="LITERAL"
>len</TT
> of all films, group
   the results by <TT
CLASS="LITERAL"
>kind</TT
> and show those group totals
   that are less than 5 hours:

</P><PRE
CLASS="PROGRAMLISTING"
>SELECT kind, sum(len) AS total
    FROM films
    GROUP BY kind
    HAVING sum(len) &lt; interval '5 hours';

   kind   | total
----------+-------
 Comedy   | 02:58
 Romantic | 04:38</PRE
><P>
  </P
><P
>   The following two examples are identical ways of sorting the individual
   results according to the contents of the second column
   (<TT
CLASS="LITERAL"
>name</TT
>):

</P><PRE
CLASS="PROGRAMLISTING"
>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</PRE
><P>
  </P
><P
>   The next example shows how to obtain the union of the tables
   <TT
CLASS="LITERAL"
>distributors</TT
> and
   <TT
CLASS="LITERAL"
>actors</TT
>, restricting the results to those that begin
   with the letter W in each table.  Only distinct rows are wanted, so the
   key word <TT
CLASS="LITERAL"
>ALL</TT
> is omitted.

</P><PRE
CLASS="PROGRAMLISTING"
>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</PRE
><P>
  </P
><P
>   This example shows how to use a function in the <TT
CLASS="LITERAL"
>FROM</TT
>
   clause, both with and without a column definition list:

</P><PRE
CLASS="PROGRAMLISTING"
>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</PRE
><P>
  </P
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN60068"
></A
><H2
>Compatibility</H2
><P
>   Of course, the <TT
CLASS="COMMAND"
>SELECT</TT
> statement is compatible
   with the SQL standard.  But there are some extensions and some
   missing features.
  </P
><DIV
CLASS="REFSECT2"
><A
NAME="AEN60072"
></A
><H3
>Omitted <TT
CLASS="LITERAL"
>FROM</TT
> Clauses</H3
><P
>    <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> allows one to omit the
    <TT
CLASS="LITERAL"
>FROM</TT
> clause.  It has a straightforward use to
    compute the results of simple expressions:
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT 2+2;

 ?column?
----------
        4</PRE
><P>
    Some other <ACRONYM
CLASS="ACRONYM"
>SQL</ACRONYM
> databases cannot do this except
    by introducing a dummy one-row table from which to do the
    <TT
CLASS="COMMAND"
>SELECT</TT
>.
   </P
><P
>    Note that if a <TT
CLASS="LITERAL"
>FROM</TT
> clause is not specified,
    the query cannot reference any database tables. For example, the
    following query is invalid:
</P><PRE
CLASS="PROGRAMLISTING"
>SELECT distributors.* WHERE distributors.name = 'Westward';</PRE
><P>
    <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> releases prior to
    8.1 would accept queries of this form, and add an implicit entry
    to the query's <TT
CLASS="LITERAL"
>FROM</TT
> clause for each table
    referenced by the query. This is no longer the default behavior,
    because it does not comply with the SQL standard, and is
    considered by many to be error-prone. For compatibility with
    applications that rely on this behavior the <A
HREF="runtime-config-compatible.html#GUC-ADD-MISSING-FROM"
>add_missing_from</A
> configuration variable can be
    enabled.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="AEN60087"
></A
><H3
>The <TT
CLASS="LITERAL"
>AS</TT
> Key Word</H3
><P
>    In the SQL standard, the optional key word <TT
CLASS="LITERAL"
>AS</TT
> is just
    noise and can be omitted without affecting the meaning.  The
    <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> parser requires this key
    word when renaming output columns because the type extensibility
    features lead to parsing ambiguities without it.
    <TT
CLASS="LITERAL"
>AS</TT
> is optional in <TT
CLASS="LITERAL"
>FROM</TT
>
    items, however.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="AEN60095"
></A
><H3
>Namespace Available to <TT
CLASS="LITERAL"
>GROUP BY</TT
> and <TT
CLASS="LITERAL"
>ORDER BY</TT
></H3
><P
>    In the SQL-92 standard, an <TT
CLASS="LITERAL"
>ORDER BY</TT
> clause can
    only use result column names or numbers, while a <TT
CLASS="LITERAL"
>GROUP
    BY</TT
> clause can only use expressions based on input column
    names.  <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> extends each of
    these clauses to allow the other choice as well (but it uses the
    standard's interpretation if there is ambiguity).
    <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
> 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
    result-column names.
   </P
><P
>    SQL:1999 and later use a slightly different definition which is not
    entirely upward compatible with SQL-92.  
    In most cases, however, <SPAN
CLASS="PRODUCTNAME"
>PostgreSQL</SPAN
>
    will interpret an <TT
CLASS="LITERAL"
>ORDER BY</TT
> or <TT
CLASS="LITERAL"
>GROUP
    BY</TT
> expression the same way SQL:1999 does.
   </P
></DIV
><DIV
CLASS="REFSECT2"
><A
NAME="AEN60108"
></A
><H3
>Nonstandard Clauses</H3
><P
>    The clauses <TT
CLASS="LITERAL"
>DISTINCT ON</TT
>,
    <TT
CLASS="LITERAL"
>LIMIT</TT
>, and <TT
CLASS="LITERAL"
>OFFSET</TT
> are not
    defined in the SQL standard.
   </P
></DIV
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="sql-savepoint.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="sql-selectinto.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>SAVEPOINT</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="sql-commands.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>SELECT INTO</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>