SELECT(7)
π SELECT(7) β PostgreSQL 13.23 Documentation
okay bestie, this is the SELECT page from the PostgreSQL 13.23 docs, and itβs genuinely iconic. like, this is the main-character command of SQL. weβre talking retrieve rows from a table or view, with a whole pipeline of clauses doing their little jobs in order. no cap, itβs a lot, but weβre gonna get through it together. π«Ά
β¨ NAME β¨
SELECT, TABLE, WITH β retrieve rows from a table or view
π SYNOPSIS π
[ WITH [ RECURSIVE ] with_query [, ...] ]
SELECT [ ALL | DISTINCT [ ON ( expression [, ...] ) ] ]
[ { * | expression [ [ AS ] output_name ] } [, ...] ]
[ FROM from_item [, ...] ]
[ WHERE condition ]
[ GROUP BY 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 [, ...] ) }
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 )
TABLE [ ONLY ] table_name [ * ]
πΈ DESCRIPTION πΈ
SELECT retrieves rows from zero or more tables. the general processing of SELECT is, like, a whole little assembly line. hereβs the order:
- all queries in the
WITHlist are computed. they effectively serve as temporary tables that can be referenced in theFROMlist. aWITHquery that is referenced more than once inFROMis computed only once, unless specified otherwise withNOT MATERIALIZED. (see WITH Clause below.) - all elements in the
FROMlist are computed. each element in theFROMlist is a real or virtual table. if more than one element is specified in theFROMlist, they are cross-joined together. (see FROM Clause below.) - if the
WHEREclause is specified, all rows that do not satisfy the condition are eliminated from the output. (see WHERE Clause below.) - if the
GROUP BYclause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed. if theHAVINGclause is present, it eliminates groups that do not satisfy the given condition. (see GROUP BY Clause and HAVING Clause below.) although query output columns are nominally computed in the next step, they can also be referenced (by name or ordinal number) in theGROUP BYclause. - the actual output rows are computed using the
SELECToutput expressions for each selected row or row group. (see SELECT List below.) SELECT DISTINCTeliminates duplicate rows from the result.SELECT DISTINCT ONeliminates rows that match on all the specified expressions.SELECT ALL(the default) will return all candidate rows, including duplicates. (see DISTINCT Clause below.)- using the operators
UNION,INTERSECT, andEXCEPT, the output of more than oneSELECTstatement can be combined to form a single result set. theUNIONoperator returns all rows that are in one or both of the result sets. theINTERSECToperator returns all rows that are strictly in both result sets. theEXCEPToperator returns the rows that are in the first result set but not in the second. in all three cases, duplicate rows are eliminated unlessALLis specified. the noise wordDISTINCTcan be added to explicitly specify eliminating duplicate rows. notice thatDISTINCTis the default behavior here, even thoughALLis the default forSELECTitself. (see UNION Clause, INTERSECT Clause, and EXCEPT Clause below.) - if the
ORDER BYclause is specified, the returned rows are sorted in the specified order. ifORDER BYis not given, the rows are returned in whatever order the system finds fastest to produce. (see ORDER BY Clause below.) - if the
LIMIT(orFETCH FIRST) orOFFSETclause is specified, theSELECTstatement only returns a subset of the result rows. (see LIMIT Clause below.) - if
FOR UPDATE,FOR NO KEY UPDATE,FOR SHAREorFOR KEY SHAREis specified, theSELECTstatement locks the selected rows against concurrent updates. (see The Locking Clause below.)
you must have SELECT privilege on each column used in a SELECT command. the use of FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE or FOR KEY SHARE requires UPDATE privilege as well (for at least one column of each table so selected). π
π PARAMETERS π
π¦ WITH Clause
the WITH clause allows you to specify one or more subqueries that can be referenced by name in the primary query. the subqueries effectively act as temporary tables or views for the duration of the primary query. each subquery can be a SELECT, TABLE, VALUES, INSERT, UPDATE or DELETE statement. when writing a data-modifying statement (INSERT, UPDATE or DELETE) in WITH, it is usual to include a RETURNING clause. it is the output of RETURNING, not the underlying table that the statement modifies, that forms the temporary table that is read by the primary query. if RETURNING is omitted, the statement is still executed, but it produces no output so it cannot be referenced as a table by the primary query.
a name (without schema qualification) must be specified for each WITH query. optionally, a list of column names can be specified; if this is omitted, the column names are inferred from the subquery.
if RECURSIVE is specified, it allows a SELECT subquery to reference itself by name. such a subquery must have the form
non_recursive_term UNION [ ALL | DISTINCT ] recursive_term
where 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 query in a data-modifying statement. see Section 7.8 for an example.
another effect of RECURSIVE is that WITH queries need not be ordered: a query can reference another one that is later in the list. (however, circular references, or mutual recursion, are not implemented.) without RECURSIVE, WITH queries can only reference sibling WITH queries that are earlier in the WITH list.
when there are multiple queries in the WITH clause, RECURSIVE should be written only once, immediately after WITH. it applies to all queries in the WITH clause, though it has no effect on queries that do not use recursion or forward references.
the primary query and the WITH queries are all (notionally) executed at the same time. this implies that the effects of a data-modifying statement in WITH cannot be seen from other parts of the query, other than by reading its RETURNING output. if two such data-modifying statements attempt to modify the same row, the results are unspecified. π
a key property of WITH queries is that they are normally evaluated only once per execution of the primary query, even if the primary query refers to them more than once. in particular, data-modifying statements are guaranteed to be executed once and only once, regardless of whether the primary query reads all or any of their output.
however, a WITH query can be marked NOT MATERIALIZED to remove this guarantee. in that case, the WITH query can be folded into the primary query much as though it were a simple sub-SELECT in the primary queryβs FROM clause. this results in duplicate computations if the primary query refers to that WITH query more than once; but if each such use requires only a few rows of the WITH queryβs total output, NOT MATERIALIZED can provide a net savings by allowing the queries to be optimized jointly. NOT MATERIALIZED is ignored if it is attached to a WITH query that is recursive or is not side-effect-free (i.e., is not a plain SELECT containing no volatile functions).
by default, a side-effect-free WITH query is folded into the primary query if it is used exactly once in the primary queryβs FROM clause. this allows joint optimization of the two query levels in situations where that should be semantically invisible. however, such folding can be prevented by marking the WITH query as MATERIALIZED. that might be useful, for example, if the WITH query is being used as an optimization fence to prevent the planner from choosing a bad plan. PostgreSQL versions before v12 never did such folding, so queries written for older versions might rely on WITH to act as an optimization fence. π
see Section 7.8 for additional information.
π FROM Clause
the FROM clause specifies one or more source tables for the SELECT. if multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. but usually qualification conditions are added (via WHERE) to restrict the returned rows to a small subset of the Cartesian product.
the FROM clause can contain the following elements:
table_nameβ the name (optionally schema-qualified) of an existing table or view. ifONLYis specified before the table name, only that table is scanned. ifONLYis not specified, the table and all its descendant tables (if any) are scanned. optionally,*can be specified after the table name to explicitly indicate that descendant tables are included. π
π« alias π«
Okay so an alias is literally just a cute lil substitute name for the FROM item it's attached to. Bestie uses an alias for brevity, or to kill the ambiguity in self-joins (you know, when the same table gets scanned multiple times and everyone's like "wait, which one"). The moment you give an alias, it completely hides the real name of the table or function β no cap. Like, given FROM foo AS f, the rest of that SELECT has to refer to this FROM item as f, not foo. It's giving "you don't know her anymore." If you do write an alias, you can also drop a column alias list to hand out substitute names for one or more columns of the table. π
π² TABLESAMPLE sampling_method ( argument [, ...] ) [ REPEATABLE ( seed ) ] π²
A TABLESAMPLE clause after a table_name says: use this sampling_method to grab a subset of that table's rows. Iconic. And this sampling happens before any other filters get applied, like WHERE clauses and friends β so it's first in line, main character energy.
The standard PostgreSQL distribution ships with two sampling methods, BERNOULLI and SYSTEM, and you can install other sampling methods into the database via extensions. π¦
BERNOULLI and SYSTEM both accept a single argument β that's the fraction of the table to sample, expressed as a percentage between 0 and 100. This argument can be any real-valued expression. (Other sampling methods might accept more or different arguments, iykyk.) Both of these return a randomly-chosen sample of the table containing approximately the specified percentage of the table's rows. Here's the tea on the difference:
BERNOULLIscans the whole table and selects or ignores individual rows independently, with the specified probability.SYSTEMdoes block-level sampling β each block has the specified chance of being selected, and all rows in each selected block are returned.
SYSTEM is significantly faster than BERNOULLI when you're working with small sampling percentages, but it may return a less-random sample of the table as a result of clustering effects. Trade-offs, bestie. π
The optional REPEATABLE clause specifies a seed number or expression to use for generating random numbers within the sampling method. The seed value can be any non-null floating-point value. Two queries that specify the same seed and argument values will select the same sample of the table, if the table hasn't been changed meanwhile. Different seed values will usually produce different samples. If REPEATABLE isn't given, a new random sample is selected for each query, based upon a system-generated seed. β¨
Heads up: some add-on sampling methods do not accept REPEATABLE, and will always produce new samples on each use. So don't come for them when the seed does nothing, okay? π
πΈ select πΈ
A sub-SELECT can appear in the FROM clause, and it acts as though its output were created as a temporary table for the duration of this single SELECT command. Two rules though, fr fr: the sub-SELECT must be surrounded by parentheses, and an alias must be provided for it. A VALUES(7) command can also be used here. π
π«Ά with_query_name π«Ά
You reference a WITH query by writing its name, just as though the query's name were a table name. (In fact, the WITH query hides any real table of the same name for the purposes of the primary query. If you need it, you can still refer to a real table of the same name by schema-qualifying the table's name.) An alias can be provided in the same way as for a table. Easy slay. β
π§ function_name π§
Function calls can appear in the FROM clause! (This is especially useful for functions that return result sets, but honestly any function can be used.) It acts as though the function's output were created as a temporary table for the duration of this single SELECT command. If the function's result type is composite β including the case of a function with multiple OUT parameters β each attribute becomes a separate column in the implicit table. π
When the optional WITH ORDINALITY clause is added to the function call, an additional column of type bigint will be appended to the function's result column(s). This column numbers the rows of the function's result set, starting from 1. By default, this column is named ordinality. Cute, right? π
An alias can be provided in the same way as for a table. If an alias is written, a column alias list can also be written, providing substitute names for one or more attributes of the function's composite return type β including the ordinality column if present.
Multiple function calls can be combined into a single FROM-clause item by surrounding them with ROWS FROM( ... ). The output of such an item is the concatenation of the first row from each function, then the second row from each function, etc. If some of the functions produce fewer rows than others, null values are substituted for the missing data, so that the total number of rows returned is always the same as for the function that produced the most rows. Nobody gets left on read. π
If the function has been defined as returning the record data type, then an alias or the key word AS must be present, followed by a column definition list in the form ( column_name data_type [, ... ]). That column definition list must match the actual number and types of columns returned by the function.
When using the ROWS FROM( ... ) syntax, if one of the functions requires a column definition list, it's preferred to put the column definition list after the function call inside ROWS FROM( ... ). A column definition list can be placed after the ROWS FROM( ... ) construct only if there's just a single function and no WITH ORDINALITY clause.
To use ORDINALITY together with a column definition list, you must use the ROWS FROM( ... ) syntax and put the column definition list inside ROWS FROM( ... ). That's the rule, periodt. π
π₯ join_type π₯
It's one of these:
[ INNER ] JOINLEFT [ OUTER ] JOINRIGHT [ OUTER ] JOINFULL [ OUTER ] JOIN
For the INNER and OUTER join types, a join condition must be specified β namely exactly one of ON join_condition, USING (join_column [, ...]), or NATURAL. See below for what those mean. π
A JOIN clause combines two FROM items, which for convenience we'll call "tables", though in reality they can be any type of FROM item. Use parentheses if necessary to determine the order of nesting. In the absence of parentheses, JOINs nest left-to-right. In any case, JOIN binds more tightly than the commas separating FROM-list items. And honestly? All the JOIN options are just a notational convenience β they do nothing you couldn't do with plain FROM and WHERE. It's giving "the outfit is cute but the outfit is optional." π
LEFT OUTER JOIN 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. That left-hand row gets extended to the full width of the joined table by inserting null values for the right-hand columns. Note that only the JOIN clause's own condition is considered while deciding which rows have matches β outer conditions are applied afterwards.
RIGHT OUTER JOIN is the flip side: it 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 LEFT OUTER JOIN by switching the left and right tables. Lowkey the same thing in a different font. π
FULL OUTER JOIN 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). Everybody eats. π
β ON join_condition β
join_condition is an expression resulting in a value of type boolean (similar to a WHERE clause) that specifies which rows in a join are considered to match. Simple as that, bestie.
π USING ( join_column [, ...] ) π
A clause of the form USING ( a, b, ... ) is shorthand for ON left_table.a = right_table.a AND left_table.b = right_table.b .... Also, USING implies that only one of each pair of equivalent columns will be included in the join output β not both. Dedupe queen. β¨
π¦ NATURAL π¦
NATURAL is shorthand for a USING list that mentions all columns in the two tables that have matching names. If there are no common column names, NATURAL is equivalent to ON TRUE. So it's either β¨match made in heavenβ¨ or a complete free-for-all. π
π CROSS JOIN π
CROSS JOIN is equivalent to INNER JOIN ON (TRUE) β that is, no rows are removed by qualification. They produce a simple Cartesian product, the same result as you get from listing the two tables at the top level of FROM, but restricted by the join condition (if any). No cap, it's just everyone Γ everyone. π
πΈ LATERAL πΈ
The LATERAL key word can precede a sub-SELECT FROM item. This allows the sub-SELECT to refer to columns of FROM items that appear before it in the FROM list. (Without LATERAL, each sub-SELECT is evaluated independently and so can't cross-reference any other FROM item.) It's giving "I can see you but you can't see me" β except the other way around. π
LATERAL can also precede a function-call FROM item, but in this case it's a noise word, because the function expression can refer to earlier FROM items in any case. So technically you can write it, and technically it does nothing. An icon doing nothing on purpose. π
A LATERAL item can appear at the top level in the FROM list, or within a JOIN tree. In the latter case it can also refer to any items that are on the left-hand side of a JOIN that it's on the right-hand side of.
When a FROM item contains LATERAL cross-references, evaluation proceeds like this: for each row of the FROM item providing the cross-referenced column(s), or set of rows of multiple FROM items providing the columns, the LATERAL item is evaluated using that row or row set's values of the columns. The resulting row(s) are joined as usual with the rows they were computed from. This is repeated for each row or set of rows from the column source table(s). π
The column source table(s) must be INNER or LEFT joined to the LATERAL item, else there would not be a well-defined set of rows from which to compute each set of rows for the LATERAL item. So even though a construct like X RIGHT JOIN LATERAL Y is syntactically valid, it is not actually allowed for Y to reference X.
Fr fr, that one's a trap. It parses and then the vibe check fails. π
π WHERE Clause π
The optional WHERE clause has the general form
WHERE condition
where condition is any expression that evaluates to a result of type boolean. 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. Basically: if you don't pass the vibe check, you're not coming to the party. πͺβ¨
π GROUP BY Clause π
The optional GROUP BY clause has the general form
GROUP BY grouping_element [, ...]
Like, GROUP BY is gonna squish together every selected row that shares the same values for the grouped expressions into one single row. Iconic condensation behavior. An expression inside a grouping_element can be an input column name, or the name or ordinal number of an output column (a SELECT list item), or literally any arbitrary expression you build out of input-column values. But watch out β if there's ambiguity, a GROUP BY name gets read as an input-column name, not an output column name. No cap, that's just the rule. π«Ά
And if any of GROUPING SETS, ROLLUP or CUBE show up as grouping elements, then the GROUP BY clause as a whole defines some number of independent grouping sets. The effect is equivalent to constructing a UNION ALL between subqueries with the individual grouping sets as their GROUP BY clauses. For the full deets on how grouping sets get handled, see Section 7.2.4. Section 7.2.4 is the group chat you wanna scroll back through.
Aggregate functions β if any are used β are computed across all rows making up each group, producing a separate value for each group. (And if there are aggregate functions but no GROUP BY clause, the query is treated as having a single group comprising all the selected rows. One big group, one big vibe. β¨) The set of rows fed to each aggregate function can be further filtered by attaching a FILTER clause to the aggregate function call; see Section 4.2.7 for more. When a FILTER clause is present, only those rows matching it are included in the input to that aggregate function. Filtered, focused, flawless.
When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, or when the ungrouped column is functionally dependent on the grouped columns β because otherwise there'd be more than one possible value to return for an ungrouped column, and the query is just gonna be like "which one bestie??". π A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column. That's the loophole, iykyk.
Keep in mind that all aggregate functions are evaluated before evaluating any "scalar" expressions in the HAVING clause or SELECT list. Which means, for example, a CASE expression cannot be used to skip evaluation of an aggregate function; see Section 4.2.14. You cannot dodge the aggregate, bestie. It runs regardless.
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified with GROUP BY. Not allowed. Periodt.
π HAVING Clause π
The optional HAVING clause has the general form
HAVING condition
where condition is the same as specified for the WHERE clause. Same flavor, different job.
HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns. Unambiguous or bust π
The presence of HAVING turns a query into a grouped query even if there is no GROUP BY clause. This is the same as what happens when the query contains aggregate functions but no GROUP BY clause. All the selected rows are considered to form a single group, and the SELECT list and HAVING clause can only reference table columns from within aggregate functions. Such a query will emit a single row if the HAVING condition is true, zero rows if it is not true. One row or no rows, there is no in-between. π
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified with HAVING. Same energy as before: nope.
π¦ WINDOW Clause π¦
The optional WINDOW clause has the general form
WINDOW window_name AS ( window_definition ) [, ...]
where window_name is a name that can be referenced from OVER clauses or subsequent window definitions, and 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 it must refer to an earlier entry in the WINDOW list; the new window copies its partitioning clause from that entry, as well as its ordering clause if any. In this case the new window cannot specify its own PARTITION BY clause, and it can specify ORDER BY only if the copied window does not have one. The new window always uses its own frame clause; the copied window must not specify a frame clause. Sharing is caring, but the frame is yours and yours alone π
The elements of the PARTITION BY list are interpreted in much the same fashion as elements of a GROUP BY clause, except that they are always simple expressions and never the name or number of an output column. Another difference is that these expressions can contain aggregate function calls, which are not allowed in a regular GROUP BY clause. They're allowed here because windowing occurs after grouping and aggregation. Order of operations said so, so it slays.
Similarly, the elements of the ORDER BY list are interpreted in much the same fashion as elements of a statement-level ORDER BY clause, except that the expressions are always taken as simple expressions and never the name or number of an output column.
The optional frame_clause defines the window frame for window functions that depend on the frame (not all do β some are just vibing without one). The window frame is a set of related rows for each row of the query (called the current row). The frame_clause can be one of
{ 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 one of
UNBOUNDED PRECEDING
offset PRECEDING
CURRENT ROW
offset FOLLOWING
UNBOUNDED FOLLOWING
and frame_exclusion can be one of
EXCLUDE CURRENT ROW
EXCLUDE GROUP
EXCLUDE TIES
EXCLUDE NO OTHERS
If frame_end is omitted it defaults to CURRENT ROW. Restrictions are that frame_start cannot be UNBOUNDED FOLLOWING, frame_end cannot be UNBOUNDED PRECEDING, and the frame_end choice cannot appear earlier in the above list of frame_start and frame_end options than the frame_start choice does β for example RANGE BETWEEN CURRENT ROW AND offset PRECEDING is not allowed. Bestie, the frame cannot end before it starts. Physics said no.
The default framing option is RANGE UNBOUNDED PRECEDING, which is the same as RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW; it sets the frame to be all rows from the partition start up through the current row's last peer (a row that the window's ORDER BY clause considers equivalent to the current row; all rows are peers if there is no ORDER BY). In general, UNBOUNDED PRECEDING means that the frame starts with the first row of the partition, and similarly UNBOUNDED FOLLOWING means that the frame ends with the last row of the partition, regardless of RANGE, ROWS or GROUPS mode. In ROWS mode, CURRENT ROW means that the frame starts or ends with the current row; but in RANGE or GROUPS mode it means that the frame starts or ends with the current row's first or last peer in the ORDER BY ordering. Peer pressure, but make it SQL.
The offset PRECEDING and offset FOLLOWING options vary in meaning depending on the frame mode. In ROWS mode, the offset is an integer indicating that the frame starts or ends that many rows before or after the current row. In GROUPS mode, the offset is an integer indicating that the frame starts or ends that many peer groups before or after the current row's peer group, where a peer group is a group of rows that are equivalent according to the window's ORDER BY clause. In RANGE mode, use of an offset option requires that there be exactly one ORDER BY column in the window definition. Then the frame contains those rows whose ordering column value is no more than offset less than (for PRECEDING) or more than (for FOLLOWING) the current row's ordering column value. In these cases the data type of the offset expression depends on the data type of the ordering column. For numeric ordering columns it is typically of the same type as the ordering column, but for datetime ordering columns it is an interval. In all these cases, the value of the offset must be non-null and non-negative. Also, while the offset does not have to be a simple constant, it cannot contain variables, aggregate functions, or window functions. No variables, no aggregates, no window functions in your offset. It's giving strict.
The frame_exclusion option allows rows around the current row to be excluded from the frame, even if they would be included according to the frame start and frame end options. EXCLUDE CURRENT ROW excludes the current row from the frame. EXCLUDE GROUP excludes the current row and its ordering peers from the frame. EXCLUDE TIES excludes any peers of the current row from the frame, but not the current row itself. EXCLUDE NO OTHERS simply specifies explicitly the default behavior of not excluding the current row or its peers. Main character row stays in the frame unless you say otherwise π
β οΈ Beware that theROWSmode can produce unpredictable results if theORDER BYordering does not order the rows uniquely. TheRANGEandGROUPSmodes are designed to ensure that rows that are peers in theORDER BYordering are treated alike: all rows of a given peer group will be in the frame or excluded from it. Unpredictable = not the vibe. Be careful withROWSmode, fr fr.
The purpose of a WINDOW clause is to specify the behavior of window functions appearing in the query's SELECT list or ORDER BY clause. These functions can reference the WINDOW clause entries by name in their OVER clauses. A WINDOW clause entry does not have to be referenced anywhere, however; if it is not used in the query it is simply ignored. It is possible to use window functions without any WINDOW clause at all, since a window function call can specify its window definition directly in its OVER clause. However, the WINDOW clause saves typing when the same window definition is needed for more than one window function. DRY but for windows. Obsessed.
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified with WINDOW. Yes, same four, yes, still not allowed.
Window functions are described in detail in Section 3.5, Section 4.2.8, and Section 7.2.5. Go read those, bestie, they ate.
πΈ SELECT List πΈ
The SELECT list (between the key words SELECT and FROM) specifies expressions that form the output rows of the SELECT statement. The expressions can (and usually do) refer to columns computed in the FROM clause. That's the whole point, honestly π
Just like in a real table, every output column of a SELECT has a name. In a simple SELECT that name is lowkey just there to label the column for display, but when the SELECT is a sub-query of a bigger query, the bigger query sees that name as the column name of the virtual table the sub-query produces. To pick the name for an output column, write AS output_name after the column's expression. (You can drop the AS, but only if the name you want doesn't match any PostgreSQL keyword β see Appendix C. And like, for protection against future keyword additions, it's recommended you always either write AS or double-quote the output name. Trust.) If you don't specify a column name, PostgreSQL picks one for you automatically. If the column's expression is a simple column reference, the chosen name is the same as that column's name. In more complex cases a function or type name may be used, or the system may fall back on a generated name like ?column?. Bestie, ?column? is real and it will show up in your results, don't be alarmed π
An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses β but not in WHERE or HAVING clauses. Over there you have to write out the expression instead. No shortcuts, sorry π«Ά
Instead of an expression, * can be written in the output list as a shorthand for all the columns of the selected rows. Also, you can write table_name.* as a shorthand for the columns coming from just that one table. In these cases it is not possible to specify new names with AS β the output column names will be the same as the table columns' names. Periodt.
According to the SQL standard, the expressions in the output list should be computed before applying DISTINCT, ORDER BY, or LIMIT. This is obviously necessary when using DISTINCT, since otherwise it's not clear what values are being made distinct. However, in many cases it's convenient if output expressions are computed after ORDER BY and LIMIT β particularly if the output list contains any volatile or expensive functions. With that behavior, the order of function evaluations is more intuitive and there won't be evaluations corresponding to rows that never appear in the output. PostgreSQL will effectively evaluate output expressions after sorting and limiting, so long as those expressions are not referenced in DISTINCT, ORDER BY or GROUP BY. (As a counterexample, SELECT f(x) FROM tab ORDER BY 1 clearly must evaluate f(x) before sorting.) Output expressions that contain set-returning functions are effectively evaluated after sorting and before limiting, so that LIMIT will act to cut off the output from a set-returning function.
Note π PostgreSQL versions before 9.6 did not provide any guarantees about the timing of evaluation of output expressions versus sorting and limiting; it depended on the form of the chosen query plan. Ancient history, but now you know πΈ
β¨ DISTINCT Clause β¨
If SELECT DISTINCT is specified, all duplicate rows are removed from the result set (one row is kept from each group of duplicates). SELECT ALL specifies the opposite: all rows are kept β and that's the default, iykyk.
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 are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. For example:
SELECT DISTINCT ON (location) location, time, report
FROM weather_reports
ORDER BY location, time DESC;
retrieves the most recent weather report for each location. But if we had not used ORDER BY to force descending order of time values for each location, we'd have gotten a report from an unpredictable time for each location. Like, chaos π
The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s). The ORDER BY clause will normally contain additional expression(s) that determine the desired precedence of rows within each DISTINCT ON group.
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified with DISTINCT.
π UNION Clause π
The UNION clause has this general form:
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 it is enclosed in parentheses. Without parentheses, these clauses will be taken to apply to the result of the UNION, not to its right-hand input expression.) Parentheses are your bestie here, fr fr.
The UNION operator computes the set union of the rows returned by the involved SELECT 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 SELECT statements that represent the direct operands of the UNION must produce the same number of columns, and corresponding columns must be of compatible data types.
The result of UNION does not contain any duplicate rows unless the ALL option is specified. ALL prevents elimination of duplicates. (Therefore, UNION ALL is usually significantly quicker than UNION; use ALL when you can β free speed, bestie π₯) DISTINCT can be written to explicitly specify the default behavior of eliminating duplicate rows.
Multiple UNION operators in the same SELECT statement are evaluated left to right, unless otherwise indicated by parentheses.
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified either for a UNION result or for any input of a UNION.
π¦ INTERSECT Clause π¦
The INTERSECT clause has this general form:
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.
The INTERSECT operator computes the set intersection of the rows returned by the involved SELECT statements. A row is in the intersection of two result sets if it appears in both result sets. It's giving "only the ones who showed up to both parties" π
The result of INTERSECT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear min(m,n) times in the result set. DISTINCT can be written to explicitly specify the default behavior of eliminating duplicate rows.
Multiple INTERSECT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. INTERSECT binds more tightly than UNION. That is, A UNION B INTERSECT C will be read as A UNION (B INTERSECT C). Math class, but make it SQL β¨
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified either for an INTERSECT result or for any input of an INTERSECT.
π EXCEPT Clause π
The EXCEPT clause has this general form:
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.
The EXCEPT operator computes the set of rows that are in the result of the left SELECT statement but not in the result of the right one. Left side minus right side, the subtraction arc π
The result of EXCEPT does not contain any duplicate rows unless the ALL option is specified. With ALL, a row that has m duplicates in the left table and n duplicates in the right table will appear max(m-n,0) times in the result set. DISTINCT can be written to explicitly specify the default behavior of eliminating duplicate rows.
Multiple EXCEPT operators in the same SELECT statement are evaluated left to right, unless parentheses dictate otherwise. EXCEPT binds at the same level as UNION.
Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified either for an EXCEPT result or for any input of an EXCEPT.
π ORDER BY Clause π
The optional ORDER BY clause has this general form:
ORDER BY expression [ ASC | DESC | USING operator ] [ NULLS { FIRST | LAST } ] [, ...]
The ORDER BY 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. So if you want a guaranteed order, actually specify enough columns, bestie π
Each expression can be the name or ordinal number of an output column (SELECT list item), or it can be an arbitrary expression formed from input-column values.
The ordinal number refers to the ordinal (left-to-right) position of the output column. This feature makes it possible to define an ordering on the basis of a column that does not have a unique name. This is never absolutely necessary because it's always possible to assign a name to an output column using the AS clause.
It's also possible to use arbitrary expressions in the ORDER BY clause, including columns that do not appear in the SELECT output list. Thus the following statement is valid:
SELECT name FROM distributors ORDER BY code;
A limitation of this feature is that an ORDER BY clause applying to the result of a UNION, INTERSECT, or EXCEPT clause can only specify an output column name or number, not an expression. Noted π
If an ORDER BY expression is a simple name that matches both an output column name and an input column name, ORDER BY will interpret it as the output column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard. Yeah, it's weird, but that's the standard's fault, not ours π
Optionally one can add the key word ASC (ascending) or DESC (descending) after any expression in the ORDER BY clause. If not specified, ASC is assumed by default. Alternatively, a specific ordering operator name can be specified in the USING clause. An ordering operator must be a less-than or greater-than member of some B-tree operator family. ASC is usually equivalent to USING < and DESC is usually equivalent to USING >. (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.) Custom types doing custom things, iconic honestly π§
If NULLS LAST is specified, null values sort after all non-null values; if NULLS FIRST is specified, null values sort before all non-null values. If neither is specified, the default behavior is NULLS LAST when ASC is specified or implied, and NULLS FIRST when DESC is specified (thus, the default is to act as though nulls are larger than non-nulls). When USING is specified, the default nulls ordering depends on whether the operator is a less-than or greater-than operator.
Note that ordering options apply only to the expression they follow; for example ORDER BY x, y DESC does not mean the same thing as ORDER BY x DESC, y DESC. Read the commas carefully, bestie β it's a trap π
oh and btw β character-string data sorts according to whatever collation applies to the column you're sorting, and you can override that at need by dropping a COLLATE clause into the expression, like ORDER BY mycolumn COLLATE "en_US". π
For more info, go peek at Section 4.2.10 and Section 23.2.
β¨ LIMIT Clause β¨
okay so the LIMIT clause is literally two independent sub-clauses, bestie:
LIMIT { count | ALL }
OFFSET start
The parameter count is the max number of rows you want back, and start is how many rows to skip before you even start returning rows. When you give both, the start rows get skipped, and then we start counting the count rows to return. π
If the count expression evaluates to NULL, it's treated as LIMIT ALL β i.e., no limit at all, go off. And if start evaluates to NULL, it's treated the same as OFFSET 0. π
SQL:2008 introduced a whole different syntax for the same result, and PostgreSQL supports that too. It's this:
OFFSET start { ROW | ROWS }
FETCH { FIRST | NEXT } [ count ] { ROW | ROWS } { ONLY | WITH TIES }
In this syntax, the standard requires the start or count value to be a literal constant, a parameter, or a variable name. As a PostgreSQL extension, other expressions are allowed β but they'll generally need to be wrapped in parentheses to avoid ambiguity. π«Ά If count is omitted in a FETCH clause, it defaults to 1. The WITH TIES option returns any extra rows that tie for last place in the result set according to the ORDER BY clause β ORDER BY is mandatory in that case, and SKIP LOCKED is not allowed. π« ROW and ROWS, plus FIRST and NEXT, are just noise words that don't influence the effects of these clauses. And per the standard, OFFSET must come before FETCH if both are present β but PostgreSQL is laxer and lets you use either order. slay for flexibility π
When you're using LIMIT, it's a good idea to use an ORDER BY clause that constrains the result rows into a unique order. Otherwise you'll get an unpredictable subset of the query's rows β like, you might be asking for the tenth through twentieth rows, but tenth through twentieth in what ordering? You literally don't know what ordering unless you specify ORDER BY. π
The query planner takes LIMIT into account when generating a query plan, so you're very likely to get different plans (yielding different row orders) depending on what you use for LIMIT and OFFSET. So using different LIMIT/OFFSET values to select different subsets of a query result will give inconsistent results unless you enforce a predictable result ordering with ORDER BY. This is not a bug β it's an inherent consequence of the fact that SQL does not promise to deliver the results of a query in any particular order unless ORDER BY is used to constrain the order. π€·ββοΈ
It's even possible for repeated executions of the same LIMIT query to return different subsets of the rows of a table, if there's no ORDER BY to enforce selection of a deterministic subset. Again β not a bug. Determinism of the results is just simply not guaranteed in that case. periodt. π
π The Locking Clause π
FOR UPDATE, FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE are the locking clauses β they affect how SELECT locks rows as they're 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
For more info on each row-level lock mode, refer to Section 13.3.2. π¦
To stop the operation from waiting for other transactions to commit, use either the NOWAIT or SKIP LOCKED option. With NOWAIT, the statement reports an error rather than waiting if a selected row can't be locked immediately. With SKIP LOCKED, any selected rows that can't be immediately locked are just skipped. β οΈ Skipping locked rows gives you an inconsistent view of the data, so it's not suitable for general purpose work β but it can be used to avoid lock contention with multiple consumers accessing a queue-like table. Note that NOWAIT and SKIP LOCKED apply only to the row-level lock(s) β the required ROW SHARE table-level lock is still taken in the ordinary way (see Chapter 13). And if you need to acquire that table-level lock without waiting, you can use LOCK(7) with the NOWAIT option first. π‘
If specific tables are named in a locking clause, then only rows coming from those tables get locked; any other tables used in the SELECT are simply read as usual. A locking clause without a table list affects all tables used in the statement. If a locking clause is applied to a view or sub-query, it affects all tables used in the view or sub-query. However, these clauses do not apply to WITH queries referenced by the primary query β if you want row locking to happen inside a WITH query, specify a locking clause within the WITH query itself. π
Multiple locking clauses can be written if you need different locking behavior for different tables. If the same table is mentioned (or implicitly affected) by more than one locking clause, then it's processed as if it was only specified by the strongest one. Similarly, a table is processed as NOWAIT if that's specified in any of the clauses affecting it β otherwise, it's processed as SKIP LOCKED if that's specified in any of the clauses affecting it. π
The locking clauses cannot be used in contexts where returned rows can't be clearly identified with individual table rows β for example, they can't be used with aggregation. π ββοΈ
When a locking clause appears at the top level of a SELECT query, the rows that are locked are exactly those that are returned by the query; in the case of a join query, the rows locked are those that contribute to returned join rows. Plus, rows that satisfied the query conditions as of the query snapshot will be locked β although they won't be returned if they were updated after the snapshot and no longer satisfy the query conditions. If a LIMIT is used, locking stops once enough rows have been returned to satisfy the limit (but bestie, note that rows skipped over by OFFSET will get locked π). Similarly, if a locking clause is used in a cursor's query, only rows actually fetched or stepped past by the cursor will be locked.
When a locking clause appears in a sub-SELECT, the rows locked are those returned to the outer query by the sub-query. This might involve fewer rows than inspection of the sub-query alone would suggest, since conditions from the outer query might be used to optimize execution of the sub-query. For example,
SELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss WHERE col1 = 5;
will lock only rows having col1 = 5, even though that condition is not textually within the sub-query. β¨
Previous releases failed to preserve a lock which is upgraded by a later savepoint. For example, this code:
BEGIN;
SELECT * FROM mytable WHERE key = 1 FOR UPDATE;
SAVEPOINT s;
UPDATE mytable SET ... WHERE key = 1;
ROLLBACK TO s;
would fail to preserve the FOR UPDATE lock after the ROLLBACK TO. This has been fixed in release 9.3. π
β οΈ Caution β οΈ It is possible for aSELECTcommand running at theREAD COMMITTEDtransaction isolation level and usingORDER BYand a locking clause to return rows out of order. This is becauseORDER BYis applied first. The command sorts the result, but might then block trying to obtain a lock on one or more of the rows. Once theSELECTunblocks, some of the ordering column values might have been modified, leading to those rows appearing to be out of order (though they are in order in terms of the original column values). π΅βπ« This can be worked around at need by placing theFOR UPDATE/SHAREclause in a sub-query, for exampleSELECT * FROM (SELECT * FROM mytable FOR UPDATE) ss ORDER BY column1;Note that this will result in locking all rows ofmytable, whereasFOR UPDATEat the top level would lock only the actually returned rows. This can make for a significant performance difference, particularly if theORDER BYis combined withLIMITor other restrictions. So this technique is recommended only if concurrent updates of the ordering columns are expected and a strictly sorted result is required. π«Ά At theREPEATABLE READorSERIALIZABLEtransaction isolation level this would cause a serialization failure (with a SQLSTATE of'40001'), so there's no possibility of receiving rows out of order under these isolation levels. π
π TABLE Command π
The command
TABLE name
is equivalent to
SELECT * FROM name
It can be used as a top-level command or as a space-saving syntax variant in parts of complex queries. Only the WITH, UNION, INTERSECT, EXCEPT, ORDER BY, LIMIT, OFFSET, FETCH and FOR locking clauses can be used with TABLE β the WHERE clause and any form of aggregation cannot be used. π«β¨
πΈ EXAMPLES πΈ
okay bestie, example time! π first up: joining the table films with the table distributors β iconic behavior:
SELECT f.title, f.did, d.name, f.date_prod, f.kind
FROM distributors d JOIN films f USING (did);
and the result is giving:
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
...
next, summing the column len of all films and grouping the results by kind:
SELECT kind, sum(len) AS total FROM films GROUP BY kind;
slay, look at that:
kind | total
----------+-------
Action | 07:34
Comedy | 02:58
Drama | 14:28
Musical | 06:42
Romantic | 04:38
now we sum the column len of all films, group the results by kind, and only show those group totals that are less than 5 hours:
SELECT kind, sum(len) AS total
FROM films
GROUP BY kind
HAVING sum(len) < interval '5 hours';
and you get:
kind | total
----------+-------
Comedy | 02:58
Romantic | 04:38
the following two examples are literally identical ways of sorting the individual results according to the contents of the second column (name):
SELECT * FROM distributors ORDER BY name;
SELECT * FROM distributors ORDER BY 2;
both give:
did | name
-----+------------------
109 | 20th Century Fox
110 | Bavaria Atelier
101 | British Lion
107 | Columbia
102 | Jean Luc Godard
113 | Luso films
104 | Mosfilm
103 | Paramount
106 | Toho
105 | United Artists
111 | Walt Disney
112 | Warner Bros.
108 | Westward
the next example shows how to obtain the union of the tables distributors and actors, restricting the results to those that begin with the letter W in each table. only distinct rows are wanted, so the key word ALL is omitted.
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%';
the result:
name
----------------
Walt Disney
Walter Matthau
Warner Bros.
Warren Beatty
Westward
Woody Allen
this example shows how to use a function in the FROM clause, both with and without a column definition list:
CREATE FUNCTION distributors(int) RETURNS SETOF distributors AS $$
SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;
SELECT * FROM distributors(111);
did | name
-----+-------------
111 | Walt Disney
CREATE FUNCTION distributors_2(int) RETURNS SETOF record AS $$
SELECT * FROM distributors WHERE did = $1;
$$ LANGUAGE SQL;
SELECT * FROM distributors_2(111) AS (f1 int, f2 text);
f1 | f2
-----+-------------
111 | Walt Disney
hereβs an example of a function with an ordinality column added:
SELECT * FROM unnest(ARRAY['a','b','c','d','e','f']) WITH ORDINALITY;
unnest | ordinality
--------+----------
a | 1
b | 2
c | 3
d | 4
e | 5
f | 6
(6 rows)
this example shows how to use a simple WITH clause:
WITH t AS (
SELECT random() as x FROM generate_series(1, 3)
)
SELECT * FROM t
UNION ALL
SELECT * FROM t;
x
--------------------
0.534150459803641
0.520092216785997
0.0735620250925422
0.534150459803641
0.520092216785997
0.0735620250925422
notice that the WITH query was evaluated only once, so we got two sets of the same three random values. no cap, thatβs the whole point π
this example uses WITH RECURSIVE to find all subordinates (direct or indirect) of the employee Mary, and their level of indirectness, from a table that shows only direct subordinates:
WITH RECURSIVE employee_recursive(distance, employee_name, manager_name) AS (
SELECT 1, employee_name, manager_name
FROM employee
WHERE manager_name = 'Mary'
UNION ALL
SELECT er.distance + 1, e.employee_name, e.manager_name
FROM employee_recursive er, employee e
WHERE er.employee_name = e.manager_name
)
SELECT distance, employee_name FROM employee_recursive;
notice the typical form of recursive queries: an initial condition, followed by UNION, followed by the recursive part of the query. be sure that the recursive part of the query will eventually return no tuples, or else the query will loop indefinitely. (See Section 7.8 for more examples.)
β οΈ bestie please hear me: that recursive part has to eventually return no tuples, or the query loops forever. not cute. π
this example uses LATERAL to apply a set-returning function get_product_names() for each row of the manufacturers table:
SELECT m.name AS mname, pname
FROM manufacturers m, LATERAL get_product_names(m.id) pname;
manufacturers not currently having any products would not appear in the result, since it is an inner join. if we wished to include the names of such manufacturers in the result, we could do:
SELECT m.name AS mname, pname
FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true;
π COMPATIBILITY π
Okay so real talk: the SELECT statement is, of course, compatible with the SQL standard. But bestie, there are some extensions and some missing features. Letβs get into it π
.
Omitted FROM Clauses π«Ά
PostgreSQL lets you omit the FROM clause. It has a straightforward use: compute the results of simple expressions:
SELECT 2+2;
?column?
----------
4
Some other SQL databases cannot do this except by introducing a dummy one-row table from which to do the SELECT.
Note that if a FROM clause is not specified, the query cannot reference any database tables. For example, the following query is invalid:
SELECT distributors.* WHERE distributors.name = 'Westward';
PostgreSQL releases prior to 8.1 would accept queries of this form, and add an implicit entry to the queryβs FROM clause for each table referenced by the query. This is no longer allowed β periodt.
Empty SELECT Lists π
The list of output expressions after SELECT can be empty, producing a zero-column result table. This is not valid syntax according to the SQL standard. PostgreSQL allows it to be consistent with allowing zero-column tables. However, an empty list is not allowed when DISTINCT is used. Slay, but with rules β¨.
Omitting the AS Key Word β¨
In the SQL standard, the optional key word AS can be omitted before an output column name whenever the new column name is a valid column name β that is, not the same as any reserved keyword. 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 use AS or double-quote output column names, to prevent any possible conflict against future keyword additions.
In FROM items, both the standard and PostgreSQL allow AS to be omitted before an alias that is an unreserved keyword. But this is impractical for output column names, because of 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 ....
PostgreSQL considers these parentheses to be optional.
PostgreSQL allows a trailing * to be written 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. According to the SQL standard, it should be possible to apply it to any FROM item. Noted, bestie π«Ά.
Function Calls in FROM π§
PostgreSQL allows a function call to be written directly as a member of the FROM list. In the SQL standard it would be necessary to wrap such a function call in a sub-SELECT; that is, the syntax FROM func(...) alias is approximately equivalent to FROM LATERAL (SELECT func(...)) alias. Note that LATERAL is considered to be implicit; this is because the standard requires LATERAL semantics for an UNNEST() item in FROM. PostgreSQL treats UNNEST() the same as other set-returning functions.
Namespace Available to GROUP BY and ORDER BY π
In the SQL-92 standard, an ORDER BY clause can only use output column names or numbers, while a GROUP BY clause can only use expressions based on input column names. PostgreSQL extends each of these clauses to allow the other choice as well β but it uses the standardβs interpretation if there is ambiguity. PostgreSQL also allows both clauses to specify arbitrary expressions. Note that names appearing in an expression will always be taken as input-column names, not as output-column names.
SQL:1999 and later use a slightly different definition which is not entirely upward compatible with SQL-92. In most cases, however, PostgreSQL will interpret an ORDER BY or GROUP BY expression the same way SQL:1999 does.
Functional Dependencies π₯
PostgreSQL recognizes functional dependency β allowing columns to be omitted from GROUP BY β only when a tableβs primary key is included in the GROUP BY list. The SQL standard specifies additional conditions that should be recognized. Cute, but limited π
.
LIMIT and OFFSET π
The clauses LIMIT and OFFSET are PostgreSQL-specific syntax, also used by MySQL. The SQL:2008 standard has introduced the clauses OFFSET ... FETCH {FIRST|NEXT} ... for the same functionality, as shown above in LIMIT Clause. This syntax is also used by IBM DB2. (Applications written for Oracle frequently use a workaround involving the automatically generated rownum column β which is not available in PostgreSQL β to implement the effects of these clauses.)
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. PostgreSQL allows it in any SELECT query as well as in sub-SELECTs, but this is an extension. The FOR NO KEY UPDATE, FOR SHARE and FOR KEY SHARE variants, as well as the NOWAIT and SKIP LOCKED options, do not appear in the standard.
Data-Modifying Statements in WITH π¦
PostgreSQL allows INSERT, UPDATE, and DELETE to be used as WITH queries. This is not found in the SQL standard. Iconic behavior, honestly π.
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.
Thatβs the tea, bestie: this iconic SELECT(7) page comes from PostgreSQL 13.23, dated 2025 β go forth and query π
πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: postgresql13 13.23-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql13 13.23-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql13 13.23-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql13 13.23-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms