gooderp18绿色标准版
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

995 linhas
64KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>4.2. Value Expressions</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="sql-syntax-lexical.html" title="4.1. Lexical Structure" /><link rel="next" href="sql-syntax-calling-funcs.html" title="4.3. Calling Functions" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">4.2. Value Expressions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="sql-syntax-lexical.html" title="4.1. Lexical Structure">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="sql-syntax.html" title="Chapter 4. SQL Syntax">Up</a></td><th width="60%" align="center">Chapter 4. SQL Syntax</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="sql-syntax-calling-funcs.html" title="4.3. Calling Functions">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="SQL-EXPRESSIONS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">4.2. Value Expressions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="sql-expressions.html#SQL-EXPRESSIONS-COLUMN-REFS">4.2.1. Column References</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-EXPRESSIONS-PARAMETERS-POSITIONAL">4.2.2. Positional Parameters</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-EXPRESSIONS-SUBSCRIPTS">4.2.3. Subscripts</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#FIELD-SELECTION">4.2.4. Field Selection</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-EXPRESSIONS-OPERATOR-CALLS">4.2.5. Operator Invocations</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-EXPRESSIONS-FUNCTION-CALLS">4.2.6. Function Calls</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SYNTAX-AGGREGATES">4.2.7. Aggregate Expressions</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS">4.2.8. Window Function Calls</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-SYNTAX-TYPE-CASTS">4.2.9. Type Casts</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-SYNTAX-COLLATE-EXPRS">4.2.10. Collation Expressions</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES">4.2.11. Scalar Subqueries</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-SYNTAX-ARRAY-CONSTRUCTORS">4.2.12. Array Constructors</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS">4.2.13. Row Constructors</a></span></dt><dt><span class="sect2"><a href="sql-expressions.html#SYNTAX-EXPRESS-EVAL">4.2.14. Expression Evaluation Rules</a></span></dt></dl></div><a id="id-1.5.3.6.2" class="indexterm"></a><a id="id-1.5.3.6.3" class="indexterm"></a><a id="id-1.5.3.6.4" class="indexterm"></a><p>
  3. Value expressions are used in a variety of contexts, such
  4. as in the target list of the <code class="command">SELECT</code> command, as
  5. new column values in <code class="command">INSERT</code> or
  6. <code class="command">UPDATE</code>, or in search conditions in a number of
  7. commands. The result of a value expression is sometimes called a
  8. <em class="firstterm">scalar</em>, to distinguish it from the result of
  9. a table expression (which is a table). Value expressions are
  10. therefore also called <em class="firstterm">scalar expressions</em> (or
  11. even simply <em class="firstterm">expressions</em>). The expression
  12. syntax allows the calculation of values from primitive parts using
  13. arithmetic, logical, set, and other operations.
  14. </p><p>
  15. A value expression is one of the following:
  16. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  17. A constant or literal value
  18. </p></li><li class="listitem"><p>
  19. A column reference
  20. </p></li><li class="listitem"><p>
  21. A positional parameter reference, in the body of a function definition
  22. or prepared statement
  23. </p></li><li class="listitem"><p>
  24. A subscripted expression
  25. </p></li><li class="listitem"><p>
  26. A field selection expression
  27. </p></li><li class="listitem"><p>
  28. An operator invocation
  29. </p></li><li class="listitem"><p>
  30. A function call
  31. </p></li><li class="listitem"><p>
  32. An aggregate expression
  33. </p></li><li class="listitem"><p>
  34. A window function call
  35. </p></li><li class="listitem"><p>
  36. A type cast
  37. </p></li><li class="listitem"><p>
  38. A collation expression
  39. </p></li><li class="listitem"><p>
  40. A scalar subquery
  41. </p></li><li class="listitem"><p>
  42. An array constructor
  43. </p></li><li class="listitem"><p>
  44. A row constructor
  45. </p></li><li class="listitem"><p>
  46. Another value expression in parentheses (used to group
  47. subexpressions and override
  48. precedence<a id="id-1.5.3.6.6.1.15.1.1" class="indexterm"></a>)
  49. </p></li></ul></div><p>
  50. </p><p>
  51. In addition to this list, there are a number of constructs that can
  52. be classified as an expression but do not follow any general syntax
  53. rules. These generally have the semantics of a function or
  54. operator and are explained in the appropriate location in <a class="xref" href="functions.html" title="Chapter 9. Functions and Operators">Chapter 9</a>. An example is the <code class="literal">IS NULL</code>
  55. clause.
  56. </p><p>
  57. We have already discussed constants in <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS" title="4.1.2. Constants">Section 4.1.2</a>. The following sections discuss
  58. the remaining options.
  59. </p><div class="sect2" id="SQL-EXPRESSIONS-COLUMN-REFS"><div class="titlepage"><div><div><h3 class="title">4.2.1. Column References</h3></div></div></div><a id="id-1.5.3.6.9.2" class="indexterm"></a><p>
  60. A column can be referenced in the form:
  61. </p><pre class="synopsis">
  62. <em class="replaceable"><code>correlation</code></em>.<em class="replaceable"><code>columnname</code></em>
  63. </pre><p>
  64. </p><p>
  65. <em class="replaceable"><code>correlation</code></em> is the name of a
  66. table (possibly qualified with a schema name), or an alias for a table
  67. defined by means of a <code class="literal">FROM</code> clause.
  68. The correlation name and separating dot can be omitted if the column name
  69. is unique across all the tables being used in the current query. (See also <a class="xref" href="queries.html" title="Chapter 7. Queries">Chapter 7</a>.)
  70. </p></div><div class="sect2" id="SQL-EXPRESSIONS-PARAMETERS-POSITIONAL"><div class="titlepage"><div><div><h3 class="title">4.2.2. Positional Parameters</h3></div></div></div><a id="id-1.5.3.6.10.2" class="indexterm"></a><a id="id-1.5.3.6.10.3" class="indexterm"></a><p>
  71. A positional parameter reference is used to indicate a value
  72. that is supplied externally to an SQL statement. Parameters are
  73. used in SQL function definitions and in prepared queries. Some
  74. client libraries also support specifying data values separately
  75. from the SQL command string, in which case parameters are used to
  76. refer to the out-of-line data values.
  77. The form of a parameter reference is:
  78. </p><pre class="synopsis">
  79. $<em class="replaceable"><code>number</code></em>
  80. </pre><p>
  81. </p><p>
  82. For example, consider the definition of a function,
  83. <code class="function">dept</code>, as:
  84. </p><pre class="programlisting">
  85. CREATE FUNCTION dept(text) RETURNS dept
  86. AS $$ SELECT * FROM dept WHERE name = $1 $$
  87. LANGUAGE SQL;
  88. </pre><p>
  89. Here the <code class="literal">$1</code> references the value of the first
  90. function argument whenever the function is invoked.
  91. </p></div><div class="sect2" id="SQL-EXPRESSIONS-SUBSCRIPTS"><div class="titlepage"><div><div><h3 class="title">4.2.3. Subscripts</h3></div></div></div><a id="id-1.5.3.6.11.2" class="indexterm"></a><p>
  92. If an expression yields a value of an array type, then a specific
  93. element of the array value can be extracted by writing
  94. </p><pre class="synopsis">
  95. <em class="replaceable"><code>expression</code></em>[<em class="replaceable"><code>subscript</code></em>]
  96. </pre><p>
  97. or multiple adjacent elements (an <span class="quote">“<span class="quote">array slice</span>”</span>) can be extracted
  98. by writing
  99. </p><pre class="synopsis">
  100. <em class="replaceable"><code>expression</code></em>[<em class="replaceable"><code>lower_subscript</code></em>:<em class="replaceable"><code>upper_subscript</code></em>]
  101. </pre><p>
  102. (Here, the brackets <code class="literal">[ ]</code> are meant to appear literally.)
  103. Each <em class="replaceable"><code>subscript</code></em> is itself an expression,
  104. which must yield an integer value.
  105. </p><p>
  106. In general the array <em class="replaceable"><code>expression</code></em> must be
  107. parenthesized, but the parentheses can be omitted when the expression
  108. to be subscripted is just a column reference or positional parameter.
  109. Also, multiple subscripts can be concatenated when the original array
  110. is multidimensional.
  111. For example:
  112. </p><pre class="programlisting">
  113. mytable.arraycolumn[4]
  114. mytable.two_d_column[17][34]
  115. $1[10:42]
  116. (arrayfunction(a,b))[42]
  117. </pre><p>
  118. The parentheses in the last example are required.
  119. See <a class="xref" href="arrays.html" title="8.15. Arrays">Section 8.15</a> for more about arrays.
  120. </p></div><div class="sect2" id="FIELD-SELECTION"><div class="titlepage"><div><div><h3 class="title">4.2.4. Field Selection</h3></div></div></div><a id="id-1.5.3.6.12.2" class="indexterm"></a><p>
  121. If an expression yields a value of a composite type (row type), then a
  122. specific field of the row can be extracted by writing
  123. </p><pre class="synopsis">
  124. <em class="replaceable"><code>expression</code></em>.<em class="replaceable"><code>fieldname</code></em>
  125. </pre><p>
  126. </p><p>
  127. In general the row <em class="replaceable"><code>expression</code></em> must be
  128. parenthesized, but the parentheses can be omitted when the expression
  129. to be selected from is just a table reference or positional parameter.
  130. For example:
  131. </p><pre class="programlisting">
  132. mytable.mycolumn
  133. $1.somecolumn
  134. (rowfunction(a,b)).col3
  135. </pre><p>
  136. (Thus, a qualified column reference is actually just a special case
  137. of the field selection syntax.) An important special case is
  138. extracting a field from a table column that is of a composite type:
  139. </p><pre class="programlisting">
  140. (compositecol).somefield
  141. (mytable.compositecol).somefield
  142. </pre><p>
  143. The parentheses are required here to show that
  144. <code class="structfield">compositecol</code> is a column name not a table name,
  145. or that <code class="structname">mytable</code> is a table name not a schema name
  146. in the second case.
  147. </p><p>
  148. You can ask for all fields of a composite value by
  149. writing <code class="literal">.*</code>:
  150. </p><pre class="programlisting">
  151. (compositecol).*
  152. </pre><p>
  153. This notation behaves differently depending on context;
  154. see <a class="xref" href="rowtypes.html#ROWTYPES-USAGE" title="8.16.5. Using Composite Types in Queries">Section 8.16.5</a> for details.
  155. </p></div><div class="sect2" id="SQL-EXPRESSIONS-OPERATOR-CALLS"><div class="titlepage"><div><div><h3 class="title">4.2.5. Operator Invocations</h3></div></div></div><a id="id-1.5.3.6.13.2" class="indexterm"></a><p>
  156. There are three possible syntaxes for an operator invocation:
  157. </p><table border="0" summary="Simple list" class="simplelist"><tr><td><em class="replaceable"><code>expression</code></em> <em class="replaceable"><code>operator</code></em> <em class="replaceable"><code>expression</code></em> (binary infix operator)</td></tr><tr><td><em class="replaceable"><code>operator</code></em> <em class="replaceable"><code>expression</code></em> (unary prefix operator)</td></tr><tr><td><em class="replaceable"><code>expression</code></em> <em class="replaceable"><code>operator</code></em> (unary postfix operator)</td></tr></table><p>
  158. where the <em class="replaceable"><code>operator</code></em> token follows the syntax
  159. rules of <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-OPERATORS" title="4.1.3. Operators">Section 4.1.3</a>, or is one of the
  160. key words <code class="token">AND</code>, <code class="token">OR</code>, and
  161. <code class="token">NOT</code>, or is a qualified operator name in the form:
  162. </p><pre class="synopsis">
  163. <code class="literal">OPERATOR(</code><em class="replaceable"><code>schema</code></em><code class="literal">.</code><em class="replaceable"><code>operatorname</code></em><code class="literal">)</code>
  164. </pre><p>
  165. Which particular operators exist and whether
  166. they are unary or binary depends on what operators have been
  167. defined by the system or the user. <a class="xref" href="functions.html" title="Chapter 9. Functions and Operators">Chapter 9</a>
  168. describes the built-in operators.
  169. </p></div><div class="sect2" id="SQL-EXPRESSIONS-FUNCTION-CALLS"><div class="titlepage"><div><div><h3 class="title">4.2.6. Function Calls</h3></div></div></div><a id="id-1.5.3.6.14.2" class="indexterm"></a><p>
  170. The syntax for a function call is the name of a function
  171. (possibly qualified with a schema name), followed by its argument list
  172. enclosed in parentheses:
  173. </p><pre class="synopsis">
  174. <em class="replaceable"><code>function_name</code></em> ([<span class="optional"><em class="replaceable"><code>expression</code></em> [<span class="optional">, <em class="replaceable"><code>expression</code></em> ... </span>]</span>] )
  175. </pre><p>
  176. </p><p>
  177. For example, the following computes the square root of 2:
  178. </p><pre class="programlisting">
  179. sqrt(2)
  180. </pre><p>
  181. </p><p>
  182. The list of built-in functions is in <a class="xref" href="functions.html" title="Chapter 9. Functions and Operators">Chapter 9</a>.
  183. Other functions can be added by the user.
  184. </p><p>
  185. When issuing queries in a database where some users mistrust other users,
  186. observe security precautions from <a class="xref" href="typeconv-func.html" title="10.3. Functions">Section 10.3</a> when
  187. writing function calls.
  188. </p><p>
  189. The arguments can optionally have names attached.
  190. See <a class="xref" href="sql-syntax-calling-funcs.html" title="4.3. Calling Functions">Section 4.3</a> for details.
  191. </p><div class="note"><h3 class="title">Note</h3><p>
  192. A function that takes a single argument of composite type can
  193. optionally be called using field-selection syntax, and conversely
  194. field selection can be written in functional style. That is, the
  195. notations <code class="literal">col(table)</code> and <code class="literal">table.col</code> are
  196. interchangeable. This behavior is not SQL-standard but is provided
  197. in <span class="productname">PostgreSQL</span> because it allows use of functions to
  198. emulate <span class="quote">“<span class="quote">computed fields</span>”</span>. For more information see
  199. <a class="xref" href="rowtypes.html#ROWTYPES-USAGE" title="8.16.5. Using Composite Types in Queries">Section 8.16.5</a>.
  200. </p></div></div><div class="sect2" id="SYNTAX-AGGREGATES"><div class="titlepage"><div><div><h3 class="title">4.2.7. Aggregate Expressions</h3></div></div></div><a id="id-1.5.3.6.15.2" class="indexterm"></a><a id="id-1.5.3.6.15.3" class="indexterm"></a><a id="id-1.5.3.6.15.4" class="indexterm"></a><a id="id-1.5.3.6.15.5" class="indexterm"></a><p>
  201. An <em class="firstterm">aggregate expression</em> represents the
  202. application of an aggregate function across the rows selected by a
  203. query. An aggregate function reduces multiple inputs to a single
  204. output value, such as the sum or average of the inputs. The
  205. syntax of an aggregate expression is one of the following:
  206. </p><pre class="synopsis">
  207. <em class="replaceable"><code>aggregate_name</code></em> (<em class="replaceable"><code>expression</code></em> [ , ... ] [ <em class="replaceable"><code>order_by_clause</code></em> ] ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ]
  208. <em class="replaceable"><code>aggregate_name</code></em> (ALL <em class="replaceable"><code>expression</code></em> [ , ... ] [ <em class="replaceable"><code>order_by_clause</code></em> ] ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ]
  209. <em class="replaceable"><code>aggregate_name</code></em> (DISTINCT <em class="replaceable"><code>expression</code></em> [ , ... ] [ <em class="replaceable"><code>order_by_clause</code></em> ] ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ]
  210. <em class="replaceable"><code>aggregate_name</code></em> ( * ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ]
  211. <em class="replaceable"><code>aggregate_name</code></em> ( [ <em class="replaceable"><code>expression</code></em> [ , ... ] ] ) WITHIN GROUP ( <em class="replaceable"><code>order_by_clause</code></em> ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ]
  212. </pre><p>
  213. where <em class="replaceable"><code>aggregate_name</code></em> is a previously
  214. defined aggregate (possibly qualified with a schema name) and
  215. <em class="replaceable"><code>expression</code></em> is
  216. any value expression that does not itself contain an aggregate
  217. expression or a window function call. The optional
  218. <em class="replaceable"><code>order_by_clause</code></em> and
  219. <em class="replaceable"><code>filter_clause</code></em> are described below.
  220. </p><p>
  221. The first form of aggregate expression invokes the aggregate
  222. once for each input row.
  223. The second form is the same as the first, since
  224. <code class="literal">ALL</code> is the default.
  225. The third form invokes the aggregate once for each distinct value
  226. of the expression (or distinct set of values, for multiple expressions)
  227. found in the input rows.
  228. The fourth form invokes the aggregate once for each input row; since no
  229. particular input value is specified, it is generally only useful
  230. for the <code class="function">count(*)</code> aggregate function.
  231. The last form is used with <em class="firstterm">ordered-set</em> aggregate
  232. functions, which are described below.
  233. </p><p>
  234. Most aggregate functions ignore null inputs, so that rows in which
  235. one or more of the expression(s) yield null are discarded. This
  236. can be assumed to be true, unless otherwise specified, for all
  237. built-in aggregates.
  238. </p><p>
  239. For example, <code class="literal">count(*)</code> yields the total number
  240. of input rows; <code class="literal">count(f1)</code> yields the number of
  241. input rows in which <code class="literal">f1</code> is non-null, since
  242. <code class="function">count</code> ignores nulls; and
  243. <code class="literal">count(distinct f1)</code> yields the number of
  244. distinct non-null values of <code class="literal">f1</code>.
  245. </p><p>
  246. Ordinarily, the input rows are fed to the aggregate function in an
  247. unspecified order. In many cases this does not matter; for example,
  248. <code class="function">min</code> produces the same result no matter what order it
  249. receives the inputs in. However, some aggregate functions
  250. (such as <code class="function">array_agg</code> and <code class="function">string_agg</code>) produce
  251. results that depend on the ordering of the input rows. When using
  252. such an aggregate, the optional <em class="replaceable"><code>order_by_clause</code></em> can be
  253. used to specify the desired ordering. The <em class="replaceable"><code>order_by_clause</code></em>
  254. has the same syntax as for a query-level <code class="literal">ORDER BY</code> clause, as
  255. described in <a class="xref" href="queries-order.html" title="7.5. Sorting Rows">Section 7.5</a>, except that its expressions
  256. are always just expressions and cannot be output-column names or numbers.
  257. For example:
  258. </p><pre class="programlisting">
  259. SELECT array_agg(a ORDER BY b DESC) FROM table;
  260. </pre><p>
  261. </p><p>
  262. When dealing with multiple-argument aggregate functions, note that the
  263. <code class="literal">ORDER BY</code> clause goes after all the aggregate arguments.
  264. For example, write this:
  265. </p><pre class="programlisting">
  266. SELECT string_agg(a, ',' ORDER BY a) FROM table;
  267. </pre><p>
  268. not this:
  269. </p><pre class="programlisting">
  270. SELECT string_agg(a ORDER BY a, ',') FROM table; -- incorrect
  271. </pre><p>
  272. The latter is syntactically valid, but it represents a call of a
  273. single-argument aggregate function with two <code class="literal">ORDER BY</code> keys
  274. (the second one being rather useless since it's a constant).
  275. </p><p>
  276. If <code class="literal">DISTINCT</code> is specified in addition to an
  277. <em class="replaceable"><code>order_by_clause</code></em>, then all the <code class="literal">ORDER BY</code>
  278. expressions must match regular arguments of the aggregate; that is,
  279. you cannot sort on an expression that is not included in the
  280. <code class="literal">DISTINCT</code> list.
  281. </p><div class="note"><h3 class="title">Note</h3><p>
  282. The ability to specify both <code class="literal">DISTINCT</code> and <code class="literal">ORDER BY</code>
  283. in an aggregate function is a <span class="productname">PostgreSQL</span> extension.
  284. </p></div><p>
  285. Placing <code class="literal">ORDER BY</code> within the aggregate's regular argument
  286. list, as described so far, is used when ordering the input rows for
  287. general-purpose and statistical aggregates, for which ordering is
  288. optional. There is a
  289. subclass of aggregate functions called <em class="firstterm">ordered-set
  290. aggregates</em> for which an <em class="replaceable"><code>order_by_clause</code></em>
  291. is <span class="emphasis"><em>required</em></span>, usually because the aggregate's computation is
  292. only sensible in terms of a specific ordering of its input rows.
  293. Typical examples of ordered-set aggregates include rank and percentile
  294. calculations. For an ordered-set aggregate,
  295. the <em class="replaceable"><code>order_by_clause</code></em> is written
  296. inside <code class="literal">WITHIN GROUP (...)</code>, as shown in the final syntax
  297. alternative above. The expressions in
  298. the <em class="replaceable"><code>order_by_clause</code></em> are evaluated once per
  299. input row just like regular aggregate arguments, sorted as per
  300. the <em class="replaceable"><code>order_by_clause</code></em>'s requirements, and fed
  301. to the aggregate function as input arguments. (This is unlike the case
  302. for a non-<code class="literal">WITHIN GROUP</code> <em class="replaceable"><code>order_by_clause</code></em>,
  303. which is not treated as argument(s) to the aggregate function.) The
  304. argument expressions preceding <code class="literal">WITHIN GROUP</code>, if any, are
  305. called <em class="firstterm">direct arguments</em> to distinguish them from
  306. the <em class="firstterm">aggregated arguments</em> listed in
  307. the <em class="replaceable"><code>order_by_clause</code></em>. Unlike regular aggregate
  308. arguments, direct arguments are evaluated only once per aggregate call,
  309. not once per input row. This means that they can contain variables only
  310. if those variables are grouped by <code class="literal">GROUP BY</code>; this restriction
  311. is the same as if the direct arguments were not inside an aggregate
  312. expression at all. Direct arguments are typically used for things like
  313. percentile fractions, which only make sense as a single value per
  314. aggregation calculation. The direct argument list can be empty; in this
  315. case, write just <code class="literal">()</code> not <code class="literal">(*)</code>.
  316. (<span class="productname">PostgreSQL</span> will actually accept either spelling, but
  317. only the first way conforms to the SQL standard.)
  318. </p><p>
  319. <a id="id-1.5.3.6.15.15.1" class="indexterm"></a>
  320. An example of an ordered-set aggregate call is:
  321. </p><pre class="programlisting">
  322. SELECT percentile_cont(0.5) WITHIN GROUP (ORDER BY income) FROM households;
  323. percentile_cont
  324. -----------------
  325. 50489
  326. </pre><p>
  327. which obtains the 50th percentile, or median, value of
  328. the <code class="structfield">income</code> column from table <code class="structname">households</code>.
  329. Here, <code class="literal">0.5</code> is a direct argument; it would make no sense
  330. for the percentile fraction to be a value varying across rows.
  331. </p><p>
  332. If <code class="literal">FILTER</code> is specified, then only the input
  333. rows for which the <em class="replaceable"><code>filter_clause</code></em>
  334. evaluates to true are fed to the aggregate function; other rows
  335. are discarded. For example:
  336. </p><pre class="programlisting">
  337. SELECT
  338. count(*) AS unfiltered,
  339. count(*) FILTER (WHERE i &lt; 5) AS filtered
  340. FROM generate_series(1,10) AS s(i);
  341. unfiltered | filtered
  342. ------------+----------
  343. 10 | 4
  344. (1 row)
  345. </pre><p>
  346. </p><p>
  347. The predefined aggregate functions are described in <a class="xref" href="functions-aggregate.html" title="9.20. Aggregate Functions">Section 9.20</a>. Other aggregate functions can be added
  348. by the user.
  349. </p><p>
  350. An aggregate expression can only appear in the result list or
  351. <code class="literal">HAVING</code> clause of a <code class="command">SELECT</code> command.
  352. It is forbidden in other clauses, such as <code class="literal">WHERE</code>,
  353. because those clauses are logically evaluated before the results
  354. of aggregates are formed.
  355. </p><p>
  356. When an aggregate expression appears in a subquery (see
  357. <a class="xref" href="sql-expressions.html#SQL-SYNTAX-SCALAR-SUBQUERIES" title="4.2.11. Scalar Subqueries">Section 4.2.11</a> and
  358. <a class="xref" href="functions-subquery.html" title="9.22. Subquery Expressions">Section 9.22</a>), the aggregate is normally
  359. evaluated over the rows of the subquery. But an exception occurs
  360. if the aggregate's arguments (and <em class="replaceable"><code>filter_clause</code></em>
  361. if any) contain only outer-level variables:
  362. the aggregate then belongs to the nearest such outer level, and is
  363. evaluated over the rows of that query. The aggregate expression
  364. as a whole is then an outer reference for the subquery it appears in,
  365. and acts as a constant over any one evaluation of that subquery.
  366. The restriction about
  367. appearing only in the result list or <code class="literal">HAVING</code> clause
  368. applies with respect to the query level that the aggregate belongs to.
  369. </p></div><div class="sect2" id="SYNTAX-WINDOW-FUNCTIONS"><div class="titlepage"><div><div><h3 class="title">4.2.8. Window Function Calls</h3></div></div></div><a id="id-1.5.3.6.16.2" class="indexterm"></a><a id="id-1.5.3.6.16.3" class="indexterm"></a><p>
  370. A <em class="firstterm">window function call</em> represents the application
  371. of an aggregate-like function over some portion of the rows selected
  372. by a query. Unlike non-window aggregate calls, this is not tied
  373. to grouping of the selected rows into a single output row — each
  374. row remains separate in the query output. However the window function
  375. has access to all the rows that would be part of the current row's
  376. group according to the grouping specification (<code class="literal">PARTITION BY</code>
  377. list) of the window function call.
  378. The syntax of a window function call is one of the following:
  379. </p><pre class="synopsis">
  380. <em class="replaceable"><code>function_name</code></em> ([<span class="optional"><em class="replaceable"><code>expression</code></em> [<span class="optional">, <em class="replaceable"><code>expression</code></em> ... </span>]</span>]) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ] OVER <em class="replaceable"><code>window_name</code></em>
  381. <em class="replaceable"><code>function_name</code></em> ([<span class="optional"><em class="replaceable"><code>expression</code></em> [<span class="optional">, <em class="replaceable"><code>expression</code></em> ... </span>]</span>]) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ] OVER ( <em class="replaceable"><code>window_definition</code></em> )
  382. <em class="replaceable"><code>function_name</code></em> ( * ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ] OVER <em class="replaceable"><code>window_name</code></em>
  383. <em class="replaceable"><code>function_name</code></em> ( * ) [ FILTER ( WHERE <em class="replaceable"><code>filter_clause</code></em> ) ] OVER ( <em class="replaceable"><code>window_definition</code></em> )
  384. </pre><p>
  385. where <em class="replaceable"><code>window_definition</code></em>
  386. has the syntax
  387. </p><pre class="synopsis">
  388. [ <em class="replaceable"><code>existing_window_name</code></em> ]
  389. [ PARTITION BY <em class="replaceable"><code>expression</code></em> [, ...] ]
  390. [ ORDER BY <em class="replaceable"><code>expression</code></em> [ ASC | DESC | USING <em class="replaceable"><code>operator</code></em> ] [ NULLS { FIRST | LAST } ] [, ...] ]
  391. [ <em class="replaceable"><code>frame_clause</code></em> ]
  392. </pre><p>
  393. The optional <em class="replaceable"><code>frame_clause</code></em>
  394. can be one of
  395. </p><pre class="synopsis">
  396. { RANGE | ROWS | GROUPS } <em class="replaceable"><code>frame_start</code></em> [ <em class="replaceable"><code>frame_exclusion</code></em> ]
  397. { RANGE | ROWS | GROUPS } BETWEEN <em class="replaceable"><code>frame_start</code></em> AND <em class="replaceable"><code>frame_end</code></em> [ <em class="replaceable"><code>frame_exclusion</code></em> ]
  398. </pre><p>
  399. where <em class="replaceable"><code>frame_start</code></em>
  400. and <em class="replaceable"><code>frame_end</code></em> can be one of
  401. </p><pre class="synopsis">
  402. UNBOUNDED PRECEDING
  403. <em class="replaceable"><code>offset</code></em> PRECEDING
  404. CURRENT ROW
  405. <em class="replaceable"><code>offset</code></em> FOLLOWING
  406. UNBOUNDED FOLLOWING
  407. </pre><p>
  408. and <em class="replaceable"><code>frame_exclusion</code></em> can be one of
  409. </p><pre class="synopsis">
  410. EXCLUDE CURRENT ROW
  411. EXCLUDE GROUP
  412. EXCLUDE TIES
  413. EXCLUDE NO OTHERS
  414. </pre><p>
  415. </p><p>
  416. Here, <em class="replaceable"><code>expression</code></em> represents any value
  417. expression that does not itself contain window function calls.
  418. </p><p>
  419. <em class="replaceable"><code>window_name</code></em> is a reference to a named window
  420. specification defined in the query's <code class="literal">WINDOW</code> clause.
  421. Alternatively, a full <em class="replaceable"><code>window_definition</code></em> can
  422. be given within parentheses, using the same syntax as for defining a
  423. named window in the <code class="literal">WINDOW</code> clause; see the
  424. <a class="xref" href="sql-select.html" title="SELECT"><span class="refentrytitle">SELECT</span></a> reference page for details. It's worth
  425. pointing out that <code class="literal">OVER wname</code> is not exactly equivalent to
  426. <code class="literal">OVER (wname ...)</code>; the latter implies copying and modifying the
  427. window definition, and will be rejected if the referenced window
  428. specification includes a frame clause.
  429. </p><p>
  430. The <code class="literal">PARTITION BY</code> clause groups the rows of the query into
  431. <em class="firstterm">partitions</em>, which are processed separately by the window
  432. function. <code class="literal">PARTITION BY</code> works similarly to a query-level
  433. <code class="literal">GROUP BY</code> clause, except that its expressions are always just
  434. expressions and cannot be output-column names or numbers.
  435. Without <code class="literal">PARTITION BY</code>, all rows produced by the query are
  436. treated as a single partition.
  437. The <code class="literal">ORDER BY</code> clause determines the order in which the rows
  438. of a partition are processed by the window function. It works similarly
  439. to a query-level <code class="literal">ORDER BY</code> clause, but likewise cannot use
  440. output-column names or numbers. Without <code class="literal">ORDER BY</code>, rows are
  441. processed in an unspecified order.
  442. </p><p>
  443. The <em class="replaceable"><code>frame_clause</code></em> specifies
  444. the set of rows constituting the <em class="firstterm">window frame</em>, which is a
  445. subset of the current partition, for those window functions that act on
  446. the frame instead of the whole partition. The set of rows in the frame
  447. can vary depending on which row is the current row. The frame can be
  448. specified in <code class="literal">RANGE</code>, <code class="literal">ROWS</code>
  449. or <code class="literal">GROUPS</code> mode; in each case, it runs from
  450. the <em class="replaceable"><code>frame_start</code></em> to
  451. the <em class="replaceable"><code>frame_end</code></em>.
  452. If <em class="replaceable"><code>frame_end</code></em> is omitted, the end defaults
  453. to <code class="literal">CURRENT ROW</code>.
  454. </p><p>
  455. A <em class="replaceable"><code>frame_start</code></em> of <code class="literal">UNBOUNDED PRECEDING</code> means
  456. that the frame starts with the first row of the partition, and similarly
  457. a <em class="replaceable"><code>frame_end</code></em> of <code class="literal">UNBOUNDED FOLLOWING</code> means
  458. that the frame ends with the last row of the partition.
  459. </p><p>
  460. In <code class="literal">RANGE</code> or <code class="literal">GROUPS</code> mode,
  461. a <em class="replaceable"><code>frame_start</code></em> of
  462. <code class="literal">CURRENT ROW</code> means the frame starts with the current
  463. row's first <em class="firstterm">peer</em> row (a row that the
  464. window's <code class="literal">ORDER BY</code> clause sorts as equivalent to the
  465. current row), while a <em class="replaceable"><code>frame_end</code></em> of
  466. <code class="literal">CURRENT ROW</code> means the frame ends with the current
  467. row's last peer row.
  468. In <code class="literal">ROWS</code> mode, <code class="literal">CURRENT ROW</code> simply
  469. means the current row.
  470. </p><p>
  471. In the <em class="replaceable"><code>offset</code></em> <code class="literal">PRECEDING</code>
  472. and <em class="replaceable"><code>offset</code></em> <code class="literal">FOLLOWING</code> frame
  473. options, the <em class="replaceable"><code>offset</code></em> must be an expression not
  474. containing any variables, aggregate functions, or window functions.
  475. The meaning of the <em class="replaceable"><code>offset</code></em> depends on the
  476. frame mode:
  477. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  478. In <code class="literal">ROWS</code> mode,
  479. the <em class="replaceable"><code>offset</code></em> must yield a non-null,
  480. non-negative integer, and the option means that the frame starts or
  481. ends the specified number of rows before or after the current row.
  482. </p></li><li class="listitem"><p>
  483. In <code class="literal">GROUPS</code> mode,
  484. the <em class="replaceable"><code>offset</code></em> again must yield a non-null,
  485. non-negative integer, and the option means that the frame starts or
  486. ends the specified number of <em class="firstterm">peer groups</em>
  487. before or after the current row's peer group, where a peer group is a
  488. set of rows that are equivalent in the <code class="literal">ORDER BY</code>
  489. ordering. (There must be an <code class="literal">ORDER BY</code> clause
  490. in the window definition to use <code class="literal">GROUPS</code> mode.)
  491. </p></li><li class="listitem"><p>
  492. In <code class="literal">RANGE</code> mode, these options require that
  493. the <code class="literal">ORDER BY</code> clause specify exactly one column.
  494. The <em class="replaceable"><code>offset</code></em> specifies the maximum
  495. difference between the value of that column in the current row and
  496. its value in preceding or following rows of the frame. The data type
  497. of the <em class="replaceable"><code>offset</code></em> expression varies depending
  498. on the data type of the ordering column. For numeric ordering
  499. columns it is typically of the same type as the ordering column,
  500. but for datetime ordering columns it is an <code class="type">interval</code>.
  501. For example, if the ordering column is of type <code class="type">date</code>
  502. or <code class="type">timestamp</code>, one could write <code class="literal">RANGE BETWEEN
  503. '1 day' PRECEDING AND '10 days' FOLLOWING</code>.
  504. The <em class="replaceable"><code>offset</code></em> is still required to be
  505. non-null and non-negative, though the meaning
  506. of <span class="quote">“<span class="quote">non-negative</span>”</span> depends on its data type.
  507. </p></li></ul></div><p>
  508. In any case, the distance to the end of the frame is limited by the
  509. distance to the end of the partition, so that for rows near the partition
  510. ends the frame might contain fewer rows than elsewhere.
  511. </p><p>
  512. Notice that in both <code class="literal">ROWS</code> and <code class="literal">GROUPS</code>
  513. mode, <code class="literal">0 PRECEDING</code> and <code class="literal">0 FOLLOWING</code>
  514. are equivalent to <code class="literal">CURRENT ROW</code>. This normally holds
  515. in <code class="literal">RANGE</code> mode as well, for an appropriate
  516. data-type-specific meaning of <span class="quote">“<span class="quote">zero</span>”</span>.
  517. </p><p>
  518. The <em class="replaceable"><code>frame_exclusion</code></em> option allows rows around
  519. the current row to be excluded from the frame, even if they would be
  520. included according to the frame start and frame end options.
  521. <code class="literal">EXCLUDE CURRENT ROW</code> excludes the current row from the
  522. frame.
  523. <code class="literal">EXCLUDE GROUP</code> excludes the current row and its
  524. ordering peers from the frame.
  525. <code class="literal">EXCLUDE TIES</code> excludes any peers of the current
  526. row from the frame, but not the current row itself.
  527. <code class="literal">EXCLUDE NO OTHERS</code> simply specifies explicitly the
  528. default behavior of not excluding the current row or its peers.
  529. </p><p>
  530. The default framing option is <code class="literal">RANGE UNBOUNDED PRECEDING</code>,
  531. which is the same as <code class="literal">RANGE BETWEEN UNBOUNDED PRECEDING AND
  532. CURRENT ROW</code>. With <code class="literal">ORDER BY</code>, this sets the frame to be
  533. all rows from the partition start up through the current row's last
  534. <code class="literal">ORDER BY</code> peer. Without <code class="literal">ORDER BY</code>,
  535. this means all rows of the partition are included in the window frame,
  536. since all rows become peers of the current row.
  537. </p><p>
  538. Restrictions are that
  539. <em class="replaceable"><code>frame_start</code></em> cannot be <code class="literal">UNBOUNDED FOLLOWING</code>,
  540. <em class="replaceable"><code>frame_end</code></em> cannot be <code class="literal">UNBOUNDED PRECEDING</code>,
  541. and the <em class="replaceable"><code>frame_end</code></em> choice cannot appear earlier in the
  542. above list of <em class="replaceable"><code>frame_start</code></em>
  543. and <em class="replaceable"><code>frame_end</code></em> options than
  544. the <em class="replaceable"><code>frame_start</code></em> choice does — for example
  545. <code class="literal">RANGE BETWEEN CURRENT ROW AND <em class="replaceable"><code>offset</code></em>
  546. PRECEDING</code> is not allowed.
  547. But, for example, <code class="literal">ROWS BETWEEN 7 PRECEDING AND 8
  548. PRECEDING</code> is allowed, even though it would never select any
  549. rows.
  550. </p><p>
  551. If <code class="literal">FILTER</code> is specified, then only the input
  552. rows for which the <em class="replaceable"><code>filter_clause</code></em>
  553. evaluates to true are fed to the window function; other rows
  554. are discarded. Only window functions that are aggregates accept
  555. a <code class="literal">FILTER</code> clause.
  556. </p><p>
  557. The built-in window functions are described in <a class="xref" href="functions-window.html#FUNCTIONS-WINDOW-TABLE" title="Table 9.60. General-Purpose Window Functions">Table 9.60</a>. Other window functions can be added by
  558. the user. Also, any built-in or user-defined general-purpose or
  559. statistical aggregate can be used as a window function. (Ordered-set
  560. and hypothetical-set aggregates cannot presently be used as window functions.)
  561. </p><p>
  562. The syntaxes using <code class="literal">*</code> are used for calling parameter-less
  563. aggregate functions as window functions, for example
  564. <code class="literal">count(*) OVER (PARTITION BY x ORDER BY y)</code>.
  565. The asterisk (<code class="literal">*</code>) is customarily not used for
  566. window-specific functions. Window-specific functions do not
  567. allow <code class="literal">DISTINCT</code> or <code class="literal">ORDER BY</code> to be used within the
  568. function argument list.
  569. </p><p>
  570. Window function calls are permitted only in the <code class="literal">SELECT</code>
  571. list and the <code class="literal">ORDER BY</code> clause of the query.
  572. </p><p>
  573. More information about window functions can be found in
  574. <a class="xref" href="tutorial-window.html" title="3.5. Window Functions">Section 3.5</a>,
  575. <a class="xref" href="functions-window.html" title="9.21. Window Functions">Section 9.21</a>, and
  576. <a class="xref" href="queries-table-expressions.html#QUERIES-WINDOW" title="7.2.5. Window Function Processing">Section 7.2.5</a>.
  577. </p></div><div class="sect2" id="SQL-SYNTAX-TYPE-CASTS"><div class="titlepage"><div><div><h3 class="title">4.2.9. Type Casts</h3></div></div></div><a id="id-1.5.3.6.17.2" class="indexterm"></a><a id="id-1.5.3.6.17.3" class="indexterm"></a><a id="id-1.5.3.6.17.4" class="indexterm"></a><p>
  578. A type cast specifies a conversion from one data type to another.
  579. <span class="productname">PostgreSQL</span> accepts two equivalent syntaxes
  580. for type casts:
  581. </p><pre class="synopsis">
  582. CAST ( <em class="replaceable"><code>expression</code></em> AS <em class="replaceable"><code>type</code></em> )
  583. <em class="replaceable"><code>expression</code></em>::<em class="replaceable"><code>type</code></em>
  584. </pre><p>
  585. The <code class="literal">CAST</code> syntax conforms to SQL; the syntax with
  586. <code class="literal">::</code> is historical <span class="productname">PostgreSQL</span>
  587. usage.
  588. </p><p>
  589. When a cast is applied to a value expression of a known type, it
  590. represents a run-time type conversion. The cast will succeed only
  591. if a suitable type conversion operation has been defined. Notice that this
  592. is subtly different from the use of casts with constants, as shown in
  593. <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS-GENERIC" title="4.1.2.7. Constants of Other Types">Section 4.1.2.7</a>. A cast applied to an
  594. unadorned string literal represents the initial assignment of a type
  595. to a literal constant value, and so it will succeed for any type
  596. (if the contents of the string literal are acceptable input syntax for the
  597. data type).
  598. </p><p>
  599. An explicit type cast can usually be omitted if there is no ambiguity as
  600. to the type that a value expression must produce (for example, when it is
  601. assigned to a table column); the system will automatically apply a
  602. type cast in such cases. However, automatic casting is only done for
  603. casts that are marked <span class="quote">“<span class="quote">OK to apply implicitly</span>”</span>
  604. in the system catalogs. Other casts must be invoked with
  605. explicit casting syntax. This restriction is intended to prevent
  606. surprising conversions from being applied silently.
  607. </p><p>
  608. It is also possible to specify a type cast using a function-like
  609. syntax:
  610. </p><pre class="synopsis">
  611. <em class="replaceable"><code>typename</code></em> ( <em class="replaceable"><code>expression</code></em> )
  612. </pre><p>
  613. However, this only works for types whose names are also valid as
  614. function names. For example, <code class="literal">double precision</code>
  615. cannot be used this way, but the equivalent <code class="literal">float8</code>
  616. can. Also, the names <code class="literal">interval</code>, <code class="literal">time</code>, and
  617. <code class="literal">timestamp</code> can only be used in this fashion if they are
  618. double-quoted, because of syntactic conflicts. Therefore, the use of
  619. the function-like cast syntax leads to inconsistencies and should
  620. probably be avoided.
  621. </p><div class="note"><h3 class="title">Note</h3><p>
  622. The function-like syntax is in fact just a function call. When
  623. one of the two standard cast syntaxes is used to do a run-time
  624. conversion, it will internally invoke a registered function to
  625. perform the conversion. By convention, these conversion functions
  626. have the same name as their output type, and thus the <span class="quote">“<span class="quote">function-like
  627. syntax</span>”</span> is nothing more than a direct invocation of the underlying
  628. conversion function. Obviously, this is not something that a portable
  629. application should rely on. For further details see
  630. <a class="xref" href="sql-createcast.html" title="CREATE CAST"><span class="refentrytitle">CREATE CAST</span></a>.
  631. </p></div></div><div class="sect2" id="SQL-SYNTAX-COLLATE-EXPRS"><div class="titlepage"><div><div><h3 class="title">4.2.10. Collation Expressions</h3></div></div></div><a id="id-1.5.3.6.18.2" class="indexterm"></a><p>
  632. The <code class="literal">COLLATE</code> clause overrides the collation of
  633. an expression. It is appended to the expression it applies to:
  634. </p><pre class="synopsis">
  635. <em class="replaceable"><code>expr</code></em> COLLATE <em class="replaceable"><code>collation</code></em>
  636. </pre><p>
  637. where <em class="replaceable"><code>collation</code></em> is a possibly
  638. schema-qualified identifier. The <code class="literal">COLLATE</code>
  639. clause binds tighter than operators; parentheses can be used when
  640. necessary.
  641. </p><p>
  642. If no collation is explicitly specified, the database system
  643. either derives a collation from the columns involved in the
  644. expression, or it defaults to the default collation of the
  645. database if no column is involved in the expression.
  646. </p><p>
  647. The two common uses of the <code class="literal">COLLATE</code> clause are
  648. overriding the sort order in an <code class="literal">ORDER BY</code> clause, for
  649. example:
  650. </p><pre class="programlisting">
  651. SELECT a, b, c FROM tbl WHERE ... ORDER BY a COLLATE "C";
  652. </pre><p>
  653. and overriding the collation of a function or operator call that
  654. has locale-sensitive results, for example:
  655. </p><pre class="programlisting">
  656. SELECT * FROM tbl WHERE a &gt; 'foo' COLLATE "C";
  657. </pre><p>
  658. Note that in the latter case the <code class="literal">COLLATE</code> clause is
  659. attached to an input argument of the operator we wish to affect.
  660. It doesn't matter which argument of the operator or function call the
  661. <code class="literal">COLLATE</code> clause is attached to, because the collation that is
  662. applied by the operator or function is derived by considering all
  663. arguments, and an explicit <code class="literal">COLLATE</code> clause will override the
  664. collations of all other arguments. (Attaching non-matching
  665. <code class="literal">COLLATE</code> clauses to more than one argument, however, is an
  666. error. For more details see <a class="xref" href="collation.html" title="23.2. Collation Support">Section 23.2</a>.)
  667. Thus, this gives the same result as the previous example:
  668. </p><pre class="programlisting">
  669. SELECT * FROM tbl WHERE a COLLATE "C" &gt; 'foo';
  670. </pre><p>
  671. But this is an error:
  672. </p><pre class="programlisting">
  673. SELECT * FROM tbl WHERE (a &gt; 'foo') COLLATE "C";
  674. </pre><p>
  675. because it attempts to apply a collation to the result of the
  676. <code class="literal">&gt;</code> operator, which is of the non-collatable data type
  677. <code class="type">boolean</code>.
  678. </p></div><div class="sect2" id="SQL-SYNTAX-SCALAR-SUBQUERIES"><div class="titlepage"><div><div><h3 class="title">4.2.11. Scalar Subqueries</h3></div></div></div><a id="id-1.5.3.6.19.2" class="indexterm"></a><p>
  679. A scalar subquery is an ordinary
  680. <code class="command">SELECT</code> query in parentheses that returns exactly one
  681. row with one column. (See <a class="xref" href="queries.html" title="Chapter 7. Queries">Chapter 7</a> for information about writing queries.)
  682. The <code class="command">SELECT</code> query is executed
  683. and the single returned value is used in the surrounding value expression.
  684. It is an error to use a query that
  685. returns more than one row or more than one column as a scalar subquery.
  686. (But if, during a particular execution, the subquery returns no rows,
  687. there is no error; the scalar result is taken to be null.)
  688. The subquery can refer to variables from the surrounding query,
  689. which will act as constants during any one evaluation of the subquery.
  690. See also <a class="xref" href="functions-subquery.html" title="9.22. Subquery Expressions">Section 9.22</a> for other expressions involving subqueries.
  691. </p><p>
  692. For example, the following finds the largest city population in each
  693. state:
  694. </p><pre class="programlisting">
  695. SELECT name, (SELECT max(pop) FROM cities WHERE cities.state = states.name)
  696. FROM states;
  697. </pre><p>
  698. </p></div><div class="sect2" id="SQL-SYNTAX-ARRAY-CONSTRUCTORS"><div class="titlepage"><div><div><h3 class="title">4.2.12. Array Constructors</h3></div></div></div><a id="id-1.5.3.6.20.2" class="indexterm"></a><a id="id-1.5.3.6.20.3" class="indexterm"></a><p>
  699. An array constructor is an expression that builds an
  700. array value using values for its member elements. A simple array
  701. constructor
  702. consists of the key word <code class="literal">ARRAY</code>, a left square bracket
  703. <code class="literal">[</code>, a list of expressions (separated by commas) for the
  704. array element values, and finally a right square bracket <code class="literal">]</code>.
  705. For example:
  706. </p><pre class="programlisting">
  707. SELECT ARRAY[1,2,3+4];
  708. array
  709. ---------
  710. {1,2,7}
  711. (1 row)
  712. </pre><p>
  713. By default,
  714. the array element type is the common type of the member expressions,
  715. determined using the same rules as for <code class="literal">UNION</code> or
  716. <code class="literal">CASE</code> constructs (see <a class="xref" href="typeconv-union-case.html" title="10.5. UNION, CASE, and Related Constructs">Section 10.5</a>).
  717. You can override this by explicitly casting the array constructor to the
  718. desired type, for example:
  719. </p><pre class="programlisting">
  720. SELECT ARRAY[1,2,22.7]::integer[];
  721. array
  722. ----------
  723. {1,2,23}
  724. (1 row)
  725. </pre><p>
  726. This has the same effect as casting each expression to the array
  727. element type individually.
  728. For more on casting, see <a class="xref" href="sql-expressions.html#SQL-SYNTAX-TYPE-CASTS" title="4.2.9. Type Casts">Section 4.2.9</a>.
  729. </p><p>
  730. Multidimensional array values can be built by nesting array
  731. constructors.
  732. In the inner constructors, the key word <code class="literal">ARRAY</code> can
  733. be omitted. For example, these produce the same result:
  734. </p><pre class="programlisting">
  735. SELECT ARRAY[ARRAY[1,2], ARRAY[3,4]];
  736. array
  737. ---------------
  738. {{1,2},{3,4}}
  739. (1 row)
  740. SELECT ARRAY[[1,2],[3,4]];
  741. array
  742. ---------------
  743. {{1,2},{3,4}}
  744. (1 row)
  745. </pre><p>
  746. Since multidimensional arrays must be rectangular, inner constructors
  747. at the same level must produce sub-arrays of identical dimensions.
  748. Any cast applied to the outer <code class="literal">ARRAY</code> constructor propagates
  749. automatically to all the inner constructors.
  750. </p><p>
  751. Multidimensional array constructor elements can be anything yielding
  752. an array of the proper kind, not only a sub-<code class="literal">ARRAY</code> construct.
  753. For example:
  754. </p><pre class="programlisting">
  755. CREATE TABLE arr(f1 int[], f2 int[]);
  756. INSERT INTO arr VALUES (ARRAY[[1,2],[3,4]], ARRAY[[5,6],[7,8]]);
  757. SELECT ARRAY[f1, f2, '{{9,10},{11,12}}'::int[]] FROM arr;
  758. array
  759. ------------------------------------------------
  760. {{{1,2},{3,4}},{{5,6},{7,8}},{{9,10},{11,12}}}
  761. (1 row)
  762. </pre><p>
  763. </p><p>
  764. You can construct an empty array, but since it's impossible to have an
  765. array with no type, you must explicitly cast your empty array to the
  766. desired type. For example:
  767. </p><pre class="programlisting">
  768. SELECT ARRAY[]::integer[];
  769. array
  770. -------
  771. {}
  772. (1 row)
  773. </pre><p>
  774. </p><p>
  775. It is also possible to construct an array from the results of a
  776. subquery. In this form, the array constructor is written with the
  777. key word <code class="literal">ARRAY</code> followed by a parenthesized (not
  778. bracketed) subquery. For example:
  779. </p><pre class="programlisting">
  780. SELECT ARRAY(SELECT oid FROM pg_proc WHERE proname LIKE 'bytea%');
  781. array
  782. -----------------------------------------------------------------------
  783. {2011,1954,1948,1952,1951,1244,1950,2005,1949,1953,2006,31,2412,2413}
  784. (1 row)
  785. SELECT ARRAY(SELECT ARRAY[i, i*2] FROM generate_series(1,5) AS a(i));
  786. array
  787. ----------------------------------
  788. {{1,2},{2,4},{3,6},{4,8},{5,10}}
  789. (1 row)
  790. </pre><p>
  791. The subquery must return a single column.
  792. If the subquery's output column is of a non-array type, the resulting
  793. one-dimensional array will have an element for each row in the
  794. subquery result, with an element type matching that of the
  795. subquery's output column.
  796. If the subquery's output column is of an array type, the result will be
  797. an array of the same type but one higher dimension; in this case all
  798. the subquery rows must yield arrays of identical dimensionality, else
  799. the result would not be rectangular.
  800. </p><p>
  801. The subscripts of an array value built with <code class="literal">ARRAY</code>
  802. always begin with one. For more information about arrays, see
  803. <a class="xref" href="arrays.html" title="8.15. Arrays">Section 8.15</a>.
  804. </p></div><div class="sect2" id="SQL-SYNTAX-ROW-CONSTRUCTORS"><div class="titlepage"><div><div><h3 class="title">4.2.13. Row Constructors</h3></div></div></div><a id="id-1.5.3.6.21.2" class="indexterm"></a><a id="id-1.5.3.6.21.3" class="indexterm"></a><a id="id-1.5.3.6.21.4" class="indexterm"></a><p>
  805. A row constructor is an expression that builds a row value (also
  806. called a composite value) using values
  807. for its member fields. A row constructor consists of the key word
  808. <code class="literal">ROW</code>, a left parenthesis, zero or more
  809. expressions (separated by commas) for the row field values, and finally
  810. a right parenthesis. For example:
  811. </p><pre class="programlisting">
  812. SELECT ROW(1,2.5,'this is a test');
  813. </pre><p>
  814. The key word <code class="literal">ROW</code> is optional when there is more than one
  815. expression in the list.
  816. </p><p>
  817. A row constructor can include the syntax
  818. <em class="replaceable"><code>rowvalue</code></em><code class="literal">.*</code>,
  819. which will be expanded to a list of the elements of the row value,
  820. just as occurs when the <code class="literal">.*</code> syntax is used at the top level
  821. of a <code class="command">SELECT</code> list (see <a class="xref" href="rowtypes.html#ROWTYPES-USAGE" title="8.16.5. Using Composite Types in Queries">Section 8.16.5</a>).
  822. For example, if table <code class="literal">t</code> has
  823. columns <code class="literal">f1</code> and <code class="literal">f2</code>, these are the same:
  824. </p><pre class="programlisting">
  825. SELECT ROW(t.*, 42) FROM t;
  826. SELECT ROW(t.f1, t.f2, 42) FROM t;
  827. </pre><p>
  828. </p><div class="note"><h3 class="title">Note</h3><p>
  829. Before <span class="productname">PostgreSQL</span> 8.2, the
  830. <code class="literal">.*</code> syntax was not expanded in row constructors, so
  831. that writing <code class="literal">ROW(t.*, 42)</code> created a two-field row whose first
  832. field was another row value. The new behavior is usually more useful.
  833. If you need the old behavior of nested row values, write the inner
  834. row value without <code class="literal">.*</code>, for instance
  835. <code class="literal">ROW(t, 42)</code>.
  836. </p></div><p>
  837. By default, the value created by a <code class="literal">ROW</code> expression is of
  838. an anonymous record type. If necessary, it can be cast to a named
  839. composite type — either the row type of a table, or a composite type
  840. created with <code class="command">CREATE TYPE AS</code>. An explicit cast might be needed
  841. to avoid ambiguity. For example:
  842. </p><pre class="programlisting">
  843. CREATE TABLE mytable(f1 int, f2 float, f3 text);
  844. CREATE FUNCTION getf1(mytable) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
  845. -- No cast needed since only one getf1() exists
  846. SELECT getf1(ROW(1,2.5,'this is a test'));
  847. getf1
  848. -------
  849. 1
  850. (1 row)
  851. CREATE TYPE myrowtype AS (f1 int, f2 text, f3 numeric);
  852. CREATE FUNCTION getf1(myrowtype) RETURNS int AS 'SELECT $1.f1' LANGUAGE SQL;
  853. -- Now we need a cast to indicate which function to call:
  854. SELECT getf1(ROW(1,2.5,'this is a test'));
  855. ERROR: function getf1(record) is not unique
  856. SELECT getf1(ROW(1,2.5,'this is a test')::mytable);
  857. getf1
  858. -------
  859. 1
  860. (1 row)
  861. SELECT getf1(CAST(ROW(11,'this is a test',2.5) AS myrowtype));
  862. getf1
  863. -------
  864. 11
  865. (1 row)
  866. </pre><p>
  867. </p><p>
  868. Row constructors can be used to build composite values to be stored
  869. in a composite-type table column, or to be passed to a function that
  870. accepts a composite parameter. Also,
  871. it is possible to compare two row values or test a row with
  872. <code class="literal">IS NULL</code> or <code class="literal">IS NOT NULL</code>, for example:
  873. </p><pre class="programlisting">
  874. SELECT ROW(1,2.5,'this is a test') = ROW(1, 3, 'not the same');
  875. SELECT ROW(table.*) IS NULL FROM table; -- detect all-null rows
  876. </pre><p>
  877. For more detail see <a class="xref" href="functions-comparisons.html" title="9.23. Row and Array Comparisons">Section 9.23</a>.
  878. Row constructors can also be used in connection with subqueries,
  879. as discussed in <a class="xref" href="functions-subquery.html" title="9.22. Subquery Expressions">Section 9.22</a>.
  880. </p></div><div class="sect2" id="SYNTAX-EXPRESS-EVAL"><div class="titlepage"><div><div><h3 class="title">4.2.14. Expression Evaluation Rules</h3></div></div></div><a id="id-1.5.3.6.22.2" class="indexterm"></a><p>
  881. The order of evaluation of subexpressions is not defined. In
  882. particular, the inputs of an operator or function are not necessarily
  883. evaluated left-to-right or in any other fixed order.
  884. </p><p>
  885. Furthermore, if the result of an expression can be determined by
  886. evaluating only some parts of it, then other subexpressions
  887. might not be evaluated at all. For instance, if one wrote:
  888. </p><pre class="programlisting">
  889. SELECT true OR somefunc();
  890. </pre><p>
  891. then <code class="literal">somefunc()</code> would (probably) not be called
  892. at all. The same would be the case if one wrote:
  893. </p><pre class="programlisting">
  894. SELECT somefunc() OR true;
  895. </pre><p>
  896. Note that this is not the same as the left-to-right
  897. <span class="quote">“<span class="quote">short-circuiting</span>”</span> of Boolean operators that is found
  898. in some programming languages.
  899. </p><p>
  900. As a consequence, it is unwise to use functions with side effects
  901. as part of complex expressions. It is particularly dangerous to
  902. rely on side effects or evaluation order in <code class="literal">WHERE</code> and <code class="literal">HAVING</code> clauses,
  903. since those clauses are extensively reprocessed as part of
  904. developing an execution plan. Boolean
  905. expressions (<code class="literal">AND</code>/<code class="literal">OR</code>/<code class="literal">NOT</code> combinations) in those clauses can be reorganized
  906. in any manner allowed by the laws of Boolean algebra.
  907. </p><p>
  908. When it is essential to force evaluation order, a <code class="literal">CASE</code>
  909. construct (see <a class="xref" href="functions-conditional.html" title="9.17. Conditional Expressions">Section 9.17</a>) can be
  910. used. For example, this is an untrustworthy way of trying to
  911. avoid division by zero in a <code class="literal">WHERE</code> clause:
  912. </p><pre class="programlisting">
  913. SELECT ... WHERE x &gt; 0 AND y/x &gt; 1.5;
  914. </pre><p>
  915. But this is safe:
  916. </p><pre class="programlisting">
  917. SELECT ... WHERE CASE WHEN x &gt; 0 THEN y/x &gt; 1.5 ELSE false END;
  918. </pre><p>
  919. A <code class="literal">CASE</code> construct used in this fashion will defeat optimization
  920. attempts, so it should only be done when necessary. (In this particular
  921. example, it would be better to sidestep the problem by writing
  922. <code class="literal">y &gt; 1.5*x</code> instead.)
  923. </p><p>
  924. <code class="literal">CASE</code> is not a cure-all for such issues, however.
  925. One limitation of the technique illustrated above is that it does not
  926. prevent early evaluation of constant subexpressions.
  927. As described in <a class="xref" href="xfunc-volatility.html" title="37.7. Function Volatility Categories">Section 37.7</a>, functions and
  928. operators marked <code class="literal">IMMUTABLE</code> can be evaluated when
  929. the query is planned rather than when it is executed. Thus for example
  930. </p><pre class="programlisting">
  931. SELECT CASE WHEN x &gt; 0 THEN x ELSE 1/0 END FROM tab;
  932. </pre><p>
  933. is likely to result in a division-by-zero failure due to the planner
  934. trying to simplify the constant subexpression,
  935. even if every row in the table has <code class="literal">x &gt; 0</code> so that the
  936. <code class="literal">ELSE</code> arm would never be entered at run time.
  937. </p><p>
  938. While that particular example might seem silly, related cases that don't
  939. obviously involve constants can occur in queries executed within
  940. functions, since the values of function arguments and local variables
  941. can be inserted into queries as constants for planning purposes.
  942. Within <span class="application">PL/pgSQL</span> functions, for example, using an
  943. <code class="literal">IF</code>-<code class="literal">THEN</code>-<code class="literal">ELSE</code> statement to protect
  944. a risky computation is much safer than just nesting it in a
  945. <code class="literal">CASE</code> expression.
  946. </p><p>
  947. Another limitation of the same kind is that a <code class="literal">CASE</code> cannot
  948. prevent evaluation of an aggregate expression contained within it,
  949. because aggregate expressions are computed before other
  950. expressions in a <code class="literal">SELECT</code> list or <code class="literal">HAVING</code> clause
  951. are considered. For example, the following query can cause a
  952. division-by-zero error despite seemingly having protected against it:
  953. </p><pre class="programlisting">
  954. SELECT CASE WHEN min(employees) &gt; 0
  955. THEN avg(expenses / employees)
  956. END
  957. FROM departments;
  958. </pre><p>
  959. The <code class="function">min()</code> and <code class="function">avg()</code> aggregates are computed
  960. concurrently over all the input rows, so if any row
  961. has <code class="structfield">employees</code> equal to zero, the division-by-zero error
  962. will occur before there is any opportunity to test the result of
  963. <code class="function">min()</code>. Instead, use a <code class="literal">WHERE</code>
  964. or <code class="literal">FILTER</code> clause to prevent problematic input rows from
  965. reaching an aggregate function in the first place.
  966. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="sql-syntax-lexical.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="sql-syntax.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="sql-syntax-calling-funcs.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">4.1. Lexical Structure </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 4.3. Calling Functions</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1