SELECT

Updated at:

Synopsis

[ 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 ] [...] ]

where from_item can be one of:

    [ 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

and grouping_element can be one of:

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

and with_query is:

    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 [ * ]

Description

SELECT retrieves rows from zero or more tables. Processing follows this order:

  1. All queries in the WITH list are computed. These act as temporary tables referenceable in the FROM list. A WITH query referenced more than once in FROM is computed only once, unless specified otherwise with NOT MATERIALIZED.

  2. All elements in the FROM list are computed. If more than one element is specified, they are cross-joined together.

  3. If a WHERE clause is specified, rows that do not satisfy the condition are eliminated from the output.

  4. If a GROUP BY clause is specified, or if there are aggregate function calls, output is combined into groups of rows matching on one or more values, and aggregate function results are computed. If a HAVING clause is present, groups not satisfying the condition are eliminated. Output columns can be referenced (by name or ordinal number) in the GROUP BY clause.

  5. The actual output rows are computed using the SELECT output expressions for each selected row or row group.

  6. SELECT DISTINCT eliminates duplicate rows from the result. SELECT DISTINCT ON eliminates rows that match on all the specified expressions. SELECT ALL (the default) returns all candidate rows, including duplicates.

  7. UNION, INTERSECT, and EXCEPT combine the output of more than one SELECT statement into a single result set. UNION returns all rows in one or both result sets. INTERSECT returns rows that appear in both result sets. EXCEPT returns rows in the first result set but not the second. In all three cases, duplicate rows are eliminated unless ALL is specified. The noise word DISTINCT can be added to explicitly specify duplicate elimination. DISTINCT is the default behavior here, even though ALL is the default for SELECT itself.

  8. If an ORDER BY clause is specified, the returned rows are sorted in the specified order. Without ORDER BY, rows are returned in whatever order the system finds fastest to produce.

  9. If a LIMIT (or FETCH FIRST) or OFFSET clause is specified, SELECT returns only a subset of the result rows.

  10. If FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, or FOR KEY SHARE is specified, SELECT locks the selected rows against concurrent updates.

Note

You must have SELECT privilege on each column used in a SELECT command. Using FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE also requires UPDATE privilege on at least one column of each table selected.

Parameters

WITH clause

The WITH clause specifies one or more subqueries that can be referenced by name in the primary query. The subqueries act as temporary tables or views for the duration of the primary query. Each subquery can be a SELECT, TABLE, VALUES, INSERT, UPDATE, or DELETE statement.

When writing a data-modifying statement (INSERT, UPDATE, or DELETE) in WITH, include a RETURNING clause. The primary query reads from RETURNING output — not from the underlying table the statement modifies. If RETURNING is omitted, the statement executes but produces no output and cannot be referenced as a table by the primary query.

Each WITH query must have a name (without schema qualification). A column name list is optional; if omitted, column names are inferred from the subquery.

Recursive queries

If RECURSIVE is specified, a SELECT subquery can reference itself by name. The subquery must have the form:

non_recursive_term UNION [ ALL | DISTINCT ] recursive_term

The recursive self-reference must appear on the right-hand side of the UNION. 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 SELECT in a data-modifying statement.

RECURSIVE also allows WITH queries to reference each other out of order — a query can reference one that appears later in the list. (Circular references and mutual recursion are not supported.) Without RECURSIVE, a WITH query can only reference sibling queries that appear earlier in the WITH list.

When multiple queries appear in the WITH clause, RECURSIVE should be written once, immediately after WITH. It applies to all queries in the clause, though it has no effect on queries that do not use recursion or forward references.

SEARCH and CYCLE clauses

The optional SEARCH clause computes a search sequence column for ordering recursive query results in breadth-first or depth-first order. The supplied column name list specifies the row key for tracking visited rows. A column named search_seq_col_name is added to the result column list; order by this column in the outer query to achieve the desired ordering.

The optional CYCLE clause detects cycles in recursive queries. The supplied column name list specifies the row key for tracking visited rows. A column named cycle_mark_col_name is added to the result column list. This column is set to cycle_mark_value when a cycle is detected, and to cycle_mark_default otherwise; processing stops when a cycle is detected. cycle_mark_value and cycle_mark_default must be constants coercible to a common data type with an inequality operator. By default, TRUE and FALSE (of type boolean) are used. A column named cycle_path_col_name is also added for internal tracking of visited rows.

Both SEARCH and CYCLE are valid only for recursive WITH queries. The with_query must be a UNION (or UNION ALL) of exactly two SELECT (or equivalent) commands — nested UNION s are not supported. When both clauses are used, the SEARCH column appears before the CYCLE columns.

Execution semantics

The primary query and all WITH queries are notionally executed at the same time. Effects of a data-modifying statement in WITH are not visible to other parts of the query, except through its RETURNING output. If two data-modifying statements attempt to modify the same row, the results are unspecified.

By default, a WITH query is evaluated only once per execution of the primary query, even if referenced more than once. Data-modifying statements are guaranteed to execute exactly once.

A WITH query can be marked NOT MATERIALIZED to remove this guarantee, allowing it to be folded into the primary query as though it were a simple sub-SELECT in the FROM clause. This may cause duplicate computations if the primary query references the WITH query more than once, but can provide a net savings if each use requires only a few rows of the total output. NOT MATERIALIZED is ignored if attached to a recursive WITH query or one that is not side-effect-free (that is, not a plain SELECT containing no volatile functions).

By default, a side-effect-free WITH query used exactly once in the primary query's FROM clause is folded into the primary query to allow joint optimization. To prevent this — for example, to use the WITH query as an optimization fence — mark it as MATERIALIZED.

FROM clause

The FROM clause specifies one or more source tables for SELECT. If multiple sources are specified, the result is the Cartesian product (cross join) of all sources. Qualification conditions added via WHERE restrict the returned rows to a subset of the Cartesian product.

Element

Description

table_name

The name (optionally schema-qualified) of an existing table or view. With ONLY, only that table is scanned; without ONLY, the table and all descendant tables are scanned. Append * after the table name to explicitly include descendant tables.

alias

A substitute name for the FROM item. An alias is used for brevity or to disambiguate self-joins. Once an alias is provided, it completely hides the actual table or function name — for example, with FROM foo AS f, the rest of the query must refer to this item as f, not foo. A column alias list can also be written to rename one or more columns of the table.

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

Retrieves a subset of the table's rows using the specified sampling_method before any WHERE filters are applied. PolarDB PostgreSQL includes two sampling methods: BERNOULLI and SYSTEM. Both accept a single argument — the percentage of the table to sample (0 to 100, as a real-valued expression). BERNOULLI scans the whole table and selects rows independently with the specified probability. SYSTEM uses block-level sampling, selecting all rows in each chosen block; it is significantly faster than BERNOULLI at small percentages but may produce a less-random sample due to clustering effects. The optional REPEATABLE ( seed ) clause makes sampling reproducible: two queries with the same seed and argument values select the same sample, provided the table has not changed. Without REPEATABLE, a new random sample is selected for each query.

select

A sub-SELECT in the FROM clause acts as a temporary table for the duration of the query. The sub-SELECT must be surrounded by parentheses; an alias can be provided the same way as for a table. A VALUES command can also be used here.

with_query_name

References a WITH query by name, as though the name were a table name. The WITH query hides any real table of the same name. To reference a real table of the same name, schema-qualify it. An alias can be provided the same way as for a table.

function_name

Function calls can appear in the FROM clause, especially useful for set-returning functions. The function's output acts as a temporary table for the duration of the query. If the function's result type is composite (including functions with multiple OUT parameters), each attribute becomes a separate column. Adding WITH ORDINALITY appends a bigint column that numbers the result rows starting from 1; this column is named ordinality by default. Multiple function calls can be combined into a single FROM-clause item using ROWS FROM( ... ), which concatenates rows from each function in parallel; null values are substituted where functions produce fewer rows. If a function returns the record type, an alias or the keyword AS must be present, followed by a column definition list in the form ( column_name data_type [, ...] ). When using ROWS FROM( ... ), if a function requires a column definition list, place it after the function call inside ROWS FROM( ... ). A column definition list can be placed after the ROWS FROM( ... ) construct only if there is a single function and no WITH ORDINALITY clause. To use ORDINALITY together with a column definition list, use the ROWS FROM( ... ) syntax and place the column definition list inside ROWS FROM( ... ).

join_type

One of: [ INNER ] JOIN, LEFT [ OUTER ] JOIN, RIGHT [ OUTER ] JOIN, FULL [ OUTER ] JOIN. A join condition must be specified — exactly one of ON, USING ( join_column [, ...] ), or NATURAL. JOIN s nest left-to-right in the absence of parentheses and bind more tightly than the commas separating FROM-list items.

ON join_condition

A boolean expression specifying which rows match in a join, similar to a WHERE clause.

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

Shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Only one of each pair of equivalent columns appears in the join output. If a join_using_alias is specified, it provides a table alias for the join columns listed in USING; unlike a regular alias, it does not hide the joined table names from the rest of the query, and you cannot write a column alias list.

NATURAL

Shorthand for a USING list that mentions all columns with matching names in both tables. If no common column names exist, NATURAL is equivalent to ON TRUE.

CROSS JOIN

Equivalent to INNER JOIN ON (TRUE) — no rows are removed by qualification. Produces a Cartesian product.

LATERAL

Allows a sub-SELECT or function-call FROM item to refer to columns from FROM items that appear before it in the FROM list. Without LATERAL, each sub-SELECT is evaluated independently. A LATERAL item can appear at the top level of the FROM list or within a JOIN tree, where it can also reference items on the left-hand side of the JOIN. The column source tables must be INNER or LEFT joined to the LATERAL item; RIGHT JOIN LATERAL is syntactically valid but not functionally allowed for cross-referencing.

Join types

LEFT OUTER JOIN returns all rows in the qualified Cartesian product, plus one row for each left-hand table row with no matching right-hand row (extended with null values for right-hand columns). Only the JOIN clause's own condition is considered when determining matches; outer conditions are applied afterwards.

RIGHT OUTER JOIN returns all joined rows, plus one row for each unmatched right-hand row (extended with nulls on the left). This is a notational convenience equivalent to a LEFT OUTER JOIN with the tables switched.

FULL OUTER JOIN returns all 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).

WHERE clause

The optional WHERE clause has the general form:

    WHERE condition

condition is any expression that evaluates to a boolean result. Rows that do not satisfy the condition are eliminated from the output.

GROUP BY clause

The optional GROUP BY clause has the general form:

    GROUP BY grouping_element [, ...]

GROUP BY condenses into a single row all selected rows sharing the same values for the grouped expressions. An expression used inside a grouping_element can be an input column name, an output column name or ordinal number, or an arbitrary expression formed from input-column values. In case of ambiguity, a GROUP BY name is interpreted as an input-column name rather than an output column name.

If GROUPING SETS, ROLLUP, or CUBE appear as grouping elements, the GROUP BY clause as a whole defines multiple independent grouping sets. This is equivalent to constructing a UNION ALL between subqueries with the individual grouping sets as their GROUP BY clauses. The optional DISTINCT clause removes duplicate sets before processing; it does not transform UNION ALL into UNION DISTINCT.

Aggregate functions are computed across all rows in each group, producing a separate value per group. Without a GROUP BY clause, aggregate functions treat all selected rows as a single group. Attach a FILTER clause to an aggregate function call to further restrict which rows feed into that function.

When GROUP BY or aggregate functions are present, SELECT list expressions cannot reference ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns (that is, the grouped columns include the primary key of the table containing the ungrouped column).

All aggregate functions are evaluated before any "scalar" expressions in HAVING or the SELECT list — for example, a CASE expression cannot skip evaluation of an aggregate function.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified with GROUP BY.

HAVING clause

The optional HAVING clause has the general form:

    HAVING condition

HAVING eliminates group rows that do not satisfy the condition, using the same condition syntax as WHERE. The key difference: WHERE filters individual rows before GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless it appears within an aggregate function or is functionally dependent on the grouping columns.

HAVING turns a query into a grouped query even without a GROUP BY clause — the same behavior as when aggregate functions are present but no GROUP BY is specified. All selected rows form a single group; the SELECT list and HAVING clause can only reference table columns within aggregate functions. Such a query emits one row if the HAVING condition is true, zero rows if not.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified with HAVING.

WINDOW clause

The optional WINDOW clause has the general form:

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

window_name can be referenced from OVER clauses or subsequent window definitions. window_definition is:

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

If an existing_window_name is specified, the new window copies its partitioning clause and, if present, its ordering clause from that entry. The new window cannot specify its own PARTITION BY, and can specify ORDER BY only if the copied window does not. The new window always uses its own frame clause; the copied window must not specify a frame clause.

PARTITION BY elements are interpreted similarly to GROUP BY, except they are always simple expressions (never output column names or numbers) and can contain aggregate function calls (not allowed in regular GROUP BY), because windowing occurs after grouping and aggregation.

ORDER BY elements in a window definition are likewise interpreted as simple expressions, never output column names or numbers.

Frame clause

The optional frame_clause defines the window frame for window functions that depend on the frame. The frame clause can be:

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

where frame_start and frame_end can be:

    UNBOUNDED PRECEDING
    offset PRECEDING
    CURRENT ROW
    offset FOLLOWING
    UNBOUNDED FOLLOWING

and frame_exclusion can be:

    EXCLUDE CURRENT ROW
    EXCLUDE GROUP
    EXCLUDE TIES
    EXCLUDE NO OTHERS

If frame_end is omitted, it defaults to CURRENT ROW. Constraints: frame_start cannot be UNBOUNDED FOLLOWING; frame_end cannot be UNBOUNDED PRECEDING; frame_end cannot appear earlier in the list than frame_start.

The default framing option is RANGE UNBOUNDED PRECEDING, equivalent to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW — the frame spans from the partition start through the current row's last peer. UNBOUNDED PRECEDING means the frame starts at the first row of the partition; UNBOUNDED FOLLOWING means it ends at the last row, regardless of RANGE, ROWS, or GROUPS mode.

In ROWS mode, CURRENT ROW means the frame starts or ends with the current row; an offset specifies a number of rows before or after the current row. In RANGE or GROUPS mode, CURRENT ROW refers to the current row's first or last peer in the ORDER BY ordering; an offset specifies peer groups before or after the current row's peer group. In RANGE mode with an offset, exactly one ORDER BY column is required; the frame contains rows whose ordering column value is no more than offset less than (for PRECEDING) or more than (for FOLLOWING) the current row's value. The offset must be non-null and non-negative, and cannot contain variables, aggregate functions, or window functions.

The frame_exclusion option excludes rows around the current row even if they fall within the frame bounds. EXCLUDE CURRENT ROW excludes the current row. EXCLUDE GROUP excludes the current row and its ordering peers. EXCLUDE TIES excludes peers but not the current row itself. EXCLUDE NO OTHERS specifies the default behavior of excluding nothing.

ROWS mode can produce unpredictable results if ORDER BY does not order rows uniquely. RANGE and GROUPS modes ensure that peers in the ORDER BY ordering are treated alike — all rows in a peer group are either included in the frame or excluded from it.

The WINDOW clause defines window functions referenced in the SELECT list or ORDER BY clause. A WINDOW entry that is not referenced by any window function is ignored. Window functions can also define their window directly in their OVER clause without a WINDOW clause; the WINDOW clause is convenient when the same window definition is needed for multiple functions.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified with WINDOW.

SELECT list

The SELECT list (between SELECT and FROM) specifies expressions that form the output rows. These expressions typically refer to columns computed in the FROM clause.

Each output column has a name. In a simple SELECT, the name labels the column for display; in a sub-query, it becomes the column name of the virtual table seen by the outer query. To name an output column, write AS output_name after the column's expression. Omitting AS is allowed only if the desired name does not match any PolarDB PostgreSQL keyword — to protect against future keyword additions, always use AS or double-quote the output name. If no column name is specified, PolarDB PostgreSQL chooses one automatically: for a simple column reference, the chosen name matches the column's name; in more complex cases a function or type name may be used, or the system falls back to a generated name such as ?column?.

An output column name can be referenced in ORDER BY and GROUP BY clauses, but not in WHERE or HAVING — in those clauses, write out the expression directly.

Use * in the output list as shorthand for all columns of the selected rows. Use table_name.* to select all columns from a specific table. In these cases, you cannot assign new names with AS; output column names match the table column names.

Per the SQL standard, output list expressions are computed before applying DISTINCT, ORDER BY, or LIMIT. PolarDB PostgreSQL effectively evaluates output expressions after sorting and limiting, as long as those expressions are not referenced in DISTINCT, ORDER BY, or GROUP BY. Output expressions containing set-returning functions are evaluated after sorting and before limiting.

DISTINCT clause

SELECT DISTINCT removes all duplicate rows from the result, keeping one row from each group of duplicates. SELECT ALL (the default) keeps all rows.

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions follow the same rules as ORDER BY. Without ORDER BY, the "first row" of each set is unpredictable — use ORDER BY to ensure the desired row appears first.

For example, this query retrieves the most recent weather report for each location:

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

The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause typically contains additional expressions to determine the desired precedence within each DISTINCT ON group.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified with DISTINCT.

UNION clause

    select_statement UNION [ ALL | DISTINCT ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause. (ORDER BY and LIMIT can be attached to a subexpression if enclosed in parentheses; without parentheses, they apply to the UNION result.)

UNION computes the set union of rows returned by the involved SELECT statements. The two SELECT statements must produce the same number of columns, with corresponding columns of compatible data types.

UNION eliminates duplicate rows unless ALL is specified. UNION ALL is typically significantly faster than UNION; use ALL when possible. Write DISTINCT to explicitly specify the default behavior of eliminating duplicates.

Multiple UNION operators in the same SELECT are evaluated left to right unless parentheses indicate otherwise.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified for a UNION result or for any input of a UNION.

INTERSECT clause

select_statement INTERSECT [ ALL | DISTINCT ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause.

INTERSECT returns rows that appear in both result sets. Without ALL, duplicate rows are eliminated. With ALL, a row with m duplicates in the left table and n duplicates in the right table appears min(m, n) times. Write DISTINCT to explicitly eliminate duplicates.

Multiple INTERSECT operators are evaluated left to right unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION — A UNION B INTERSECT C is read as A UNION (B INTERSECT C).

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified for an INTERSECT result or for any input of an INTERSECT.

EXCEPT clause

select_statement EXCEPT [ ALL | DISTINCT ] select_statement

select_statement is any SELECT statement without an ORDER BY, LIMIT, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, or FOR KEY SHARE clause.

EXCEPT returns rows that are in the left result set but not in the right. Without ALL, duplicate rows are eliminated. With ALL, a row with m duplicates in the left table and n duplicates in the right table appears max(m-n, 0) times. Write DISTINCT to explicitly eliminate duplicates.

Multiple EXCEPT operators are evaluated left to right unless parentheses dictate otherwise. EXCEPT binds at the same level as UNION.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, and FOR KEY SHARE cannot be specified for an EXCEPT result or for any input of an EXCEPT.

ORDER BY clause

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

ORDER BY sorts result rows by the specified expressions. If two rows are equal on the leftmost expression, they are compared on the next, and so on. If equal on all specified expressions, they are returned in an implementation-dependent order.

Each expression can be an output column name or ordinal number, or an arbitrary expression formed from input-column values. Ordinal numbers refer to the left-to-right position of output columns — useful for ordering on a column without a unique name. Arbitrary expressions are also valid, including columns not in the SELECT output list:

SELECT name FROM distributors ORDER BY code;

When ORDER BY applies to a UNION, INTERSECT, or EXCEPT result, only output column names or numbers are valid — expressions are not.

If an ORDER BY expression is a simple name matching both an output column name and an input column name, ORDER BY interprets it as the output column name. This is the opposite of GROUP BY's behavior in the same situation, for SQL standard compatibility.

Add ASC (ascending) or DESC (descending) after any expression; ASC is assumed by default. Alternatively, specify an ordering operator using USING; the operator must be a less-than or greater-than member of some B-tree operator family. ASC is usually equivalent to USING < and DESC to USING >.

NULL ordering: NULLS LAST sorts nulls after all non-null values; NULLS FIRST sorts nulls before all non-null values. The default is NULLS LAST when ASC is specified and NULLS FIRST when DESC is specified. With USING, the default depends on whether the operator is less-than or greater-than.

Ordering options apply only to the expression they follow — ORDER BY x, y DESC is not the same as ORDER BY x DESC, y DESC.

Character-string data is sorted according to the collation that applies to the column being sorted. Override this with a COLLATE clause, for example: ORDER BY mycolumn COLLATE "en_US".

LIMIT clause

The LIMIT clause consists of two independent sub-clauses:

LIMIT { count | ALL }
OFFSET start

count specifies the maximum number of rows to return. start specifies how many rows to skip before returning rows. When both are specified, start rows are skipped before counting the count rows to return.

If count evaluates to NULL, it is treated as LIMIT ALL (no limit). If start evaluates to NULL, it is treated as OFFSET 0.

PolarDB PostgreSQL also supports the SQL:2008 syntax:

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

In this syntax, the SQL standard requires start or count to be a literal constant, a parameter, or a variable name; PolarDB PostgreSQL extends this to allow other expressions, which generally need parentheses to avoid ambiguity. If count is omitted in a FETCH clause, it defaults to 1. The WITH TIES option returns additional rows that tie for last place according to ORDER BY; ORDER BY is mandatory with WITH TIES, and SKIP LOCKED is not allowed. ROW/ROWS and FIRST/NEXT are noise words. Per the standard, OFFSET must precede FETCH if both are present; PolarDB PostgreSQL accepts either order.

Use ORDER BY with LIMIT to produce deterministic results. Without ORDER BY, the subset returned is unpredictable — repeated executions of the same LIMIT query may return different subsets, and different LIMIT/OFFSET values on the same query can produce inconsistent results. This is not a bug; SQL does not guarantee result order without ORDER BY.

Locking clause

FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE are locking clauses that control how SELECT locks rows as they are obtained from the table.

The locking clause has the general form:

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

where lock_strength can be one of:

UPDATE
NO KEY UPDATE
SHARE
KEY SHARE

With NOWAIT, the statement reports an error rather than waiting if a selected row cannot be locked immediately. With SKIP LOCKED, any selected rows that cannot be immediately locked are skipped — this is not suitable for general-purpose work (it produces an inconsistent view of the data), but is useful for avoiding lock contention with multiple consumers accessing a queue-like table. Note that NOWAIT and SKIP LOCKED apply only to row-level locks; the required ROW SHARE table-level lock is still acquired normally. Use LOCK with the NOWAIT option to acquire a table-level lock without waiting.

If specific tables are named in a locking clause, only rows from those tables are locked; other tables in the SELECT are read normally. A locking clause without a table list affects all tables in the statement. Applied to a view or sub-query, it affects all tables used within. These clauses do not apply to WITH queries referenced by the primary query — specify a locking clause within the WITH query to lock rows there.

Multiple locking clauses can be written to specify different locking behavior for different tables. If the same table is affected by more than one locking clause, it is processed as if specified by the strongest one. A table is processed as NOWAIT if that is specified in any clause affecting it; otherwise as SKIP LOCKED if that is specified.

Locking clauses cannot be used 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 SELECT query, the rows locked are exactly those returned by the query. In a join query, the rows locked are those that contribute to the returned join rows. Rows that satisfied the query conditions as of the query snapshot are also locked even if they no longer satisfy conditions after being updated. If LIMIT is used, locking stops once enough rows have been returned to satisfy the limit (rows skipped by OFFSET are still locked). In a cursor query, only rows actually fetched or stepped past by the cursor are locked.

When a locking clause appears in a sub-SELECT, the rows locked are those returned to the outer query. This may be fewer rows than the sub-query alone would suggest, since outer query conditions may optimize sub-query execution:

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

This locks only rows where col1 = 5, even though that condition is not textually within the sub-query.

Prior releases failed to preserve a lock upgraded by a later savepoint:

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

The FOR UPDATE lock would not be preserved after ROLLBACK TO. This was fixed in release 9.3.

Warning

A SELECT running at the READ COMMITTED transaction isolation level and using both ORDER BY and a locking clause may return rows out of order. ORDER BY is applied first: the command sorts the result, but may then block trying to obtain a lock on one or more rows. Once unblocked, some ordering column values may have been modified, causing those rows to appear out of order. Work around this by placing the FOR UPDATE/SHARE clause in a sub-query:

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

Note that this locks all rows of mytable, whereas FOR UPDATE at the top level locks only the actually returned rows — a significant performance difference when ORDER BY is combined with LIMIT or other restrictions. Use this technique only if concurrent updates of the ordering columns are expected and a strictly sorted result is required.

At the REPEATABLE READ or SERIALIZABLE isolation level, this situation causes a serialization failure (with SQLSTATE of '40001'), so rows out of order cannot occur under these isolation levels.

TABLE command

The command:

TABLE name

is equivalent to:

SELECT * FROM name

Use it as a top-level command or as a concise syntax variant in complex queries. Only WITH, UNION, INTERSECT, EXCEPT, ORDER BY, LIMIT, OFFSET, FETCH, and FOR locking clauses can be used with TABLE; the WHERE clause and aggregation cannot.

Examples

Join two tables

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

Aggregate with GROUP BY

    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

Filter groups with HAVING

    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

Sort by column name or ordinal

These two statements are equivalent — both sort by the name column:

    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

Combine results with UNION

Union the distributors and actors tables, returning only names starting with "W":

    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

Use a function in 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

Add an ordinality column

    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)

Use a WITH clause for shared subquery results

    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
Note

The WITH query was evaluated only once, producing two sets of the same three random values.

Traverse an employee hierarchy with WITH RECURSIVE

Find all subordinates (direct or indirect) of Mary, and their level of indirectness:

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

The typical form of a recursive query: an initial condition, followed by UNION, followed by the recursive part. Ensure the recursive part eventually returns no tuples, or the query will loop indefinitely.

Use LATERAL to call a set-returning function per row

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

Manufacturers with no products are excluded because this is an inner join. To include them:

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

Compatibility

The SELECT statement is compatible with the SQL standard, with several extensions and a few differences.

Omitted FROM clauses

PolarDB PostgreSQL allows omitting the FROM clause to compute simple expressions:

    SELECT 2+2;

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

Some other SQL databases require a dummy one-row table to do this.

Empty SELECT lists

The output expression list after SELECT can be empty, producing a zero-column result table. This is not valid per the SQL standard, but PolarDB PostgreSQL allows it for consistency with zero-column tables. An empty list is not allowed when DISTINCT is used.

Omitting the AS keyword

The SQL standard allows omitting AS before an output column name whenever the new column name is not a reserved keyword. PolarDB PostgreSQL is slightly more restrictive: AS is required if the new column name matches any keyword at all, reserved or not. Recommended practice is to always use AS or double-quote output column names to guard against future keyword additions.

In FROM items, both the standard and PolarDB PostgreSQL allow omitting AS before an unreserved-keyword alias. This is impractical for output column names due to syntactic ambiguities.

ONLY and inheritance

The SQL standard requires parentheses around the table name when writing ONLY, for example SELECT * FROM ONLY (tab1), ONLY (tab2) WHERE .... PolarDB PostgreSQL treats these parentheses as optional.

PostgreSQL allows a trailing * to explicitly specify the non-ONLY behavior of including child tables; the standard does not allow this.

(These points apply equally to all SQL commands supporting the ONLY option.)

TABLESAMPLE clause restrictions

The TABLESAMPLE clause is currently accepted only on regular tables and materialized views. The SQL standard allows it on any FROM item.

Function calls in FROM

PolarDB PostgreSQL allows function calls directly as members of the FROM list. In the SQL standard, such a call must be wrapped in a sub-SELECT; the syntax FROM func(...) is approximately equivalent to FROM LATERAL (SELECT func(...)). LATERAL is implicit in this case, because the standard requires LATERAL semantics for UNNEST() in FROM. PolarDB PostgreSQL treats UNNEST() the same as other set-returning functions.

Namespace available to GROUP BY and ORDER BY

SQL-92 restricts ORDER BY to output column names or numbers, and GROUP BY to expressions based on input column names. PolarDB PostgreSQL extends both clauses to allow the other choice as well (using the standard's interpretation when ambiguous) and allows arbitrary expressions in both. Names in expressions are always treated as input-column names, not output-column names.

SQL:1999 and later use a slightly different definition, not fully compatible with SQL-92. In most cases, PolarDB PostgreSQL interprets ORDER BY and GROUP BY expressions the same way SQL:1999 does.

Functional dependencies

PolarDB PostgreSQL recognizes functional dependencies (allowing columns to be omitted from GROUP BY) only when the table's primary key is included in the GROUP BY list. The SQL standard specifies additional conditions that should be recognized.

FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE, FOR KEY SHARE

Although FOR UPDATE appears in the SQL standard, the standard allows it only as an option of DECLARE CURSOR. PolarDB PostgreSQL allows it in any SELECT query and in sub-SELECT s. FOR NO KEY UPDATE, FOR SHARE, and FOR KEY SHARE, as well as the NOWAIT and SKIP LOCKED options, do not appear in the standard.

Data-modifying statements in WITH

PolarDB PostgreSQL allows INSERT, UPDATE, and DELETE as WITH queries. This is not in the SQL standard.

Nonstandard clauses

DISTINCT ON ( ... ) is an extension of the SQL standard.

ROWS FROM( ... ) is an extension of the SQL standard.

The MATERIALIZED and NOT MATERIALIZED options of WITH are extensions of the SQL standard.