gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

962 行
57KB

  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>7.2. Table 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="queries-overview.html" title="7.1. Overview" /><link rel="next" href="queries-select-lists.html" title="7.3. Select Lists" /></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">7.2. Table Expressions</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="queries-overview.html" title="7.1. Overview">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="queries.html" title="Chapter 7. Queries">Up</a></td><th width="60%" align="center">Chapter 7. Queries</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="queries-select-lists.html" title="7.3. Select Lists">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="QUERIES-TABLE-EXPRESSIONS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">7.2. Table Expressions</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="queries-table-expressions.html#QUERIES-FROM">7.2.1. The <code class="literal">FROM</code> Clause</a></span></dt><dt><span class="sect2"><a href="queries-table-expressions.html#QUERIES-WHERE">7.2.2. The <code class="literal">WHERE</code> Clause</a></span></dt><dt><span class="sect2"><a href="queries-table-expressions.html#QUERIES-GROUP">7.2.3. The <code class="literal">GROUP BY</code> and <code class="literal">HAVING</code> Clauses</a></span></dt><dt><span class="sect2"><a href="queries-table-expressions.html#QUERIES-GROUPING-SETS">7.2.4. <code class="literal">GROUPING SETS</code>, <code class="literal">CUBE</code>, and <code class="literal">ROLLUP</code></a></span></dt><dt><span class="sect2"><a href="queries-table-expressions.html#QUERIES-WINDOW">7.2.5. Window Function Processing</a></span></dt></dl></div><a id="id-1.5.6.6.2" class="indexterm"></a><p>
  3. A <em class="firstterm">table expression</em> computes a table. The
  4. table expression contains a <code class="literal">FROM</code> clause that is
  5. optionally followed by <code class="literal">WHERE</code>, <code class="literal">GROUP BY</code>, and
  6. <code class="literal">HAVING</code> clauses. Trivial table expressions simply refer
  7. to a table on disk, a so-called base table, but more complex
  8. expressions can be used to modify or combine base tables in various
  9. ways.
  10. </p><p>
  11. The optional <code class="literal">WHERE</code>, <code class="literal">GROUP BY</code>, and
  12. <code class="literal">HAVING</code> clauses in the table expression specify a
  13. pipeline of successive transformations performed on the table
  14. derived in the <code class="literal">FROM</code> clause. All these transformations
  15. produce a virtual table that provides the rows that are passed to
  16. the select list to compute the output rows of the query.
  17. </p><div class="sect2" id="QUERIES-FROM"><div class="titlepage"><div><div><h3 class="title">7.2.1. The <code class="literal">FROM</code> Clause</h3></div></div></div><p>
  18. The <a class="xref" href="sql-select.html#SQL-FROM" title="FROM Clause"><code class="literal">FROM</code> Clause</a> derives a
  19. table from one or more other tables given in a comma-separated
  20. table reference list.
  21. </p><pre class="synopsis">
  22. FROM <em class="replaceable"><code>table_reference</code></em> [<span class="optional">, <em class="replaceable"><code>table_reference</code></em> [<span class="optional">, ...</span>]</span>]
  23. </pre><p>
  24. A table reference can be a table name (possibly schema-qualified),
  25. or a derived table such as a subquery, a <code class="literal">JOIN</code> construct, or
  26. complex combinations of these. If more than one table reference is
  27. listed in the <code class="literal">FROM</code> clause, the tables are cross-joined
  28. (that is, the Cartesian product of their rows is formed; see below).
  29. The result of the <code class="literal">FROM</code> list is an intermediate virtual
  30. table that can then be subject to
  31. transformations by the <code class="literal">WHERE</code>, <code class="literal">GROUP BY</code>,
  32. and <code class="literal">HAVING</code> clauses and is finally the result of the
  33. overall table expression.
  34. </p><a id="id-1.5.6.6.5.3" class="indexterm"></a><p>
  35. When a table reference names a table that is the parent of a
  36. table inheritance hierarchy, the table reference produces rows of
  37. not only that table but all of its descendant tables, unless the
  38. key word <code class="literal">ONLY</code> precedes the table name. However, the
  39. reference produces only the columns that appear in the named table
  40. — any columns added in subtables are ignored.
  41. </p><p>
  42. Instead of writing <code class="literal">ONLY</code> before the table name, you can write
  43. <code class="literal">*</code> after the table name to explicitly specify that descendant
  44. tables are included. There is no real reason to use this syntax any more,
  45. because searching descendant tables is now always the default behavior.
  46. However, it is supported for compatibility with older releases.
  47. </p><div class="sect3" id="QUERIES-JOIN"><div class="titlepage"><div><div><h4 class="title">7.2.1.1. Joined Tables</h4></div></div></div><a id="id-1.5.6.6.5.6.2" class="indexterm"></a><p>
  48. A joined table is a table derived from two other (real or
  49. derived) tables according to the rules of the particular join
  50. type. Inner, outer, and cross-joins are available.
  51. The general syntax of a joined table is
  52. </p><pre class="synopsis">
  53. <em class="replaceable"><code>T1</code></em> <em class="replaceable"><code>join_type</code></em> <em class="replaceable"><code>T2</code></em> [<span class="optional"> <em class="replaceable"><code>join_condition</code></em> </span>]
  54. </pre><p>
  55. Joins of all types can be chained together, or nested: either or
  56. both <em class="replaceable"><code>T1</code></em> and
  57. <em class="replaceable"><code>T2</code></em> can be joined tables. Parentheses
  58. can be used around <code class="literal">JOIN</code> clauses to control the join
  59. order. In the absence of parentheses, <code class="literal">JOIN</code> clauses
  60. nest left-to-right.
  61. </p><div class="variablelist"><p class="title"><strong>Join Types</strong></p><dl class="variablelist"><dt><span class="term">Cross join
  62. <a id="id-1.5.6.6.5.6.4.2.1.1" class="indexterm"></a>
  63. <a id="id-1.5.6.6.5.6.4.2.1.2" class="indexterm"></a>
  64. </span></dt><dd><pre class="synopsis">
  65. <em class="replaceable"><code>T1</code></em> CROSS JOIN <em class="replaceable"><code>T2</code></em>
  66. </pre><p>
  67. For every possible combination of rows from
  68. <em class="replaceable"><code>T1</code></em> and
  69. <em class="replaceable"><code>T2</code></em> (i.e., a Cartesian product),
  70. the joined table will contain a
  71. row consisting of all columns in <em class="replaceable"><code>T1</code></em>
  72. followed by all columns in <em class="replaceable"><code>T2</code></em>. If
  73. the tables have N and M rows respectively, the joined
  74. table will have N * M rows.
  75. </p><p>
  76. <code class="literal">FROM <em class="replaceable"><code>T1</code></em> CROSS JOIN
  77. <em class="replaceable"><code>T2</code></em></code> is equivalent to
  78. <code class="literal">FROM <em class="replaceable"><code>T1</code></em> INNER JOIN
  79. <em class="replaceable"><code>T2</code></em> ON TRUE</code> (see below).
  80. It is also equivalent to
  81. <code class="literal">FROM <em class="replaceable"><code>T1</code></em>,
  82. <em class="replaceable"><code>T2</code></em></code>.
  83. </p><div class="note"><h3 class="title">Note</h3><p>
  84. This latter equivalence does not hold exactly when more than two
  85. tables appear, because <code class="literal">JOIN</code> binds more tightly than
  86. comma. For example
  87. <code class="literal">FROM <em class="replaceable"><code>T1</code></em> CROSS JOIN
  88. <em class="replaceable"><code>T2</code></em> INNER JOIN <em class="replaceable"><code>T3</code></em>
  89. ON <em class="replaceable"><code>condition</code></em></code>
  90. is not the same as
  91. <code class="literal">FROM <em class="replaceable"><code>T1</code></em>,
  92. <em class="replaceable"><code>T2</code></em> INNER JOIN <em class="replaceable"><code>T3</code></em>
  93. ON <em class="replaceable"><code>condition</code></em></code>
  94. because the <em class="replaceable"><code>condition</code></em> can
  95. reference <em class="replaceable"><code>T1</code></em> in the first case but not
  96. the second.
  97. </p></div><p>
  98. </p></dd><dt><span class="term">Qualified joins
  99. <a id="id-1.5.6.6.5.6.4.3.1.1" class="indexterm"></a>
  100. <a id="id-1.5.6.6.5.6.4.3.1.2" class="indexterm"></a>
  101. </span></dt><dd><pre class="synopsis">
  102. <em class="replaceable"><code>T1</code></em> { [<span class="optional">INNER</span>] | { LEFT | RIGHT | FULL } [<span class="optional">OUTER</span>] } JOIN <em class="replaceable"><code>T2</code></em> ON <em class="replaceable"><code>boolean_expression</code></em>
  103. <em class="replaceable"><code>T1</code></em> { [<span class="optional">INNER</span>] | { LEFT | RIGHT | FULL } [<span class="optional">OUTER</span>] } JOIN <em class="replaceable"><code>T2</code></em> USING ( <em class="replaceable"><code>join column list</code></em> )
  104. <em class="replaceable"><code>T1</code></em> NATURAL { [<span class="optional">INNER</span>] | { LEFT | RIGHT | FULL } [<span class="optional">OUTER</span>] } JOIN <em class="replaceable"><code>T2</code></em>
  105. </pre><p>
  106. The words <code class="literal">INNER</code> and
  107. <code class="literal">OUTER</code> are optional in all forms.
  108. <code class="literal">INNER</code> is the default;
  109. <code class="literal">LEFT</code>, <code class="literal">RIGHT</code>, and
  110. <code class="literal">FULL</code> imply an outer join.
  111. </p><p>
  112. The <em class="firstterm">join condition</em> is specified in the
  113. <code class="literal">ON</code> or <code class="literal">USING</code> clause, or implicitly by
  114. the word <code class="literal">NATURAL</code>. The join condition determines
  115. which rows from the two source tables are considered to
  116. <span class="quote">“<span class="quote">match</span>”</span>, as explained in detail below.
  117. </p><p>
  118. The possible types of qualified join are:
  119. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term"><code class="literal">INNER JOIN</code></span></dt><dd><p>
  120. For each row R1 of T1, the joined table has a row for each
  121. row in T2 that satisfies the join condition with R1.
  122. </p></dd><dt><span class="term"><code class="literal">LEFT OUTER JOIN</code>
  123. <a id="id-1.5.6.6.5.6.4.3.2.4.1.2.1.2" class="indexterm"></a>
  124. <a id="id-1.5.6.6.5.6.4.3.2.4.1.2.1.3" class="indexterm"></a>
  125. </span></dt><dd><p>
  126. First, an inner join is performed. Then, for each row in
  127. T1 that does not satisfy the join condition with any row in
  128. T2, a joined row is added with null values in columns of
  129. T2. Thus, the joined table always has at least
  130. one row for each row in T1.
  131. </p></dd><dt><span class="term"><code class="literal">RIGHT OUTER JOIN</code>
  132. <a id="id-1.5.6.6.5.6.4.3.2.4.1.3.1.2" class="indexterm"></a>
  133. <a id="id-1.5.6.6.5.6.4.3.2.4.1.3.1.3" class="indexterm"></a>
  134. </span></dt><dd><p>
  135. First, an inner join is performed. Then, for each row in
  136. T2 that does not satisfy the join condition with any row in
  137. T1, a joined row is added with null values in columns of
  138. T1. This is the converse of a left join: the result table
  139. will always have a row for each row in T2.
  140. </p></dd><dt><span class="term"><code class="literal">FULL OUTER JOIN</code></span></dt><dd><p>
  141. First, an inner join is performed. Then, for each row in
  142. T1 that does not satisfy the join condition with any row in
  143. T2, a joined row is added with null values in columns of
  144. T2. Also, for each row of T2 that does not satisfy the
  145. join condition with any row in T1, a joined row with null
  146. values in the columns of T1 is added.
  147. </p></dd></dl></div><p>
  148. </p><p>
  149. The <code class="literal">ON</code> clause is the most general kind of join
  150. condition: it takes a Boolean value expression of the same
  151. kind as is used in a <code class="literal">WHERE</code> clause. A pair of rows
  152. from <em class="replaceable"><code>T1</code></em> and <em class="replaceable"><code>T2</code></em> match if the
  153. <code class="literal">ON</code> expression evaluates to true.
  154. </p><p>
  155. The <code class="literal">USING</code> clause is a shorthand that allows you to take
  156. advantage of the specific situation where both sides of the join use
  157. the same name for the joining column(s). It takes a
  158. comma-separated list of the shared column names
  159. and forms a join condition that includes an equality comparison
  160. for each one. For example, joining <em class="replaceable"><code>T1</code></em>
  161. and <em class="replaceable"><code>T2</code></em> with <code class="literal">USING (a, b)</code> produces
  162. the join condition <code class="literal">ON <em class="replaceable"><code>T1</code></em>.a
  163. = <em class="replaceable"><code>T2</code></em>.a AND <em class="replaceable"><code>T1</code></em>.b
  164. = <em class="replaceable"><code>T2</code></em>.b</code>.
  165. </p><p>
  166. Furthermore, the output of <code class="literal">JOIN USING</code> suppresses
  167. redundant columns: there is no need to print both of the matched
  168. columns, since they must have equal values. While <code class="literal">JOIN
  169. ON</code> produces all columns from <em class="replaceable"><code>T1</code></em> followed by all
  170. columns from <em class="replaceable"><code>T2</code></em>, <code class="literal">JOIN USING</code> produces one
  171. output column for each of the listed column pairs (in the listed
  172. order), followed by any remaining columns from <em class="replaceable"><code>T1</code></em>,
  173. followed by any remaining columns from <em class="replaceable"><code>T2</code></em>.
  174. </p><p>
  175. <a id="id-1.5.6.6.5.6.4.3.2.8.1" class="indexterm"></a>
  176. <a id="id-1.5.6.6.5.6.4.3.2.8.2" class="indexterm"></a>
  177. Finally, <code class="literal">NATURAL</code> is a shorthand form of
  178. <code class="literal">USING</code>: it forms a <code class="literal">USING</code> list
  179. consisting of all column names that appear in both
  180. input tables. As with <code class="literal">USING</code>, these columns appear
  181. only once in the output table. If there are no common
  182. column names, <code class="literal">NATURAL JOIN</code> behaves like
  183. <code class="literal">JOIN ... ON TRUE</code>, producing a cross-product join.
  184. </p><div class="note"><h3 class="title">Note</h3><p>
  185. <code class="literal">USING</code> is reasonably safe from column changes
  186. in the joined relations since only the listed columns
  187. are combined. <code class="literal">NATURAL</code> is considerably more risky since
  188. any schema changes to either relation that cause a new matching
  189. column name to be present will cause the join to combine that new
  190. column as well.
  191. </p></div></dd></dl></div><p>
  192. To put this together, assume we have tables <code class="literal">t1</code>:
  193. </p><pre class="programlisting">
  194. num | name
  195. -----+------
  196. 1 | a
  197. 2 | b
  198. 3 | c
  199. </pre><p>
  200. and <code class="literal">t2</code>:
  201. </p><pre class="programlisting">
  202. num | value
  203. -----+-------
  204. 1 | xxx
  205. 3 | yyy
  206. 5 | zzz
  207. </pre><p>
  208. then we get the following results for the various joins:
  209. </p><pre class="screen">
  210. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 CROSS JOIN t2;</code></strong>
  211. num | name | num | value
  212. -----+------+-----+-------
  213. 1 | a | 1 | xxx
  214. 1 | a | 3 | yyy
  215. 1 | a | 5 | zzz
  216. 2 | b | 1 | xxx
  217. 2 | b | 3 | yyy
  218. 2 | b | 5 | zzz
  219. 3 | c | 1 | xxx
  220. 3 | c | 3 | yyy
  221. 3 | c | 5 | zzz
  222. (9 rows)
  223. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 INNER JOIN t2 ON t1.num = t2.num;</code></strong>
  224. num | name | num | value
  225. -----+------+-----+-------
  226. 1 | a | 1 | xxx
  227. 3 | c | 3 | yyy
  228. (2 rows)
  229. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 INNER JOIN t2 USING (num);</code></strong>
  230. num | name | value
  231. -----+------+-------
  232. 1 | a | xxx
  233. 3 | c | yyy
  234. (2 rows)
  235. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 NATURAL INNER JOIN t2;</code></strong>
  236. num | name | value
  237. -----+------+-------
  238. 1 | a | xxx
  239. 3 | c | yyy
  240. (2 rows)
  241. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num;</code></strong>
  242. num | name | num | value
  243. -----+------+-----+-------
  244. 1 | a | 1 | xxx
  245. 2 | b | |
  246. 3 | c | 3 | yyy
  247. (3 rows)
  248. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 LEFT JOIN t2 USING (num);</code></strong>
  249. num | name | value
  250. -----+------+-------
  251. 1 | a | xxx
  252. 2 | b |
  253. 3 | c | yyy
  254. (3 rows)
  255. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 RIGHT JOIN t2 ON t1.num = t2.num;</code></strong>
  256. num | name | num | value
  257. -----+------+-----+-------
  258. 1 | a | 1 | xxx
  259. 3 | c | 3 | yyy
  260. | | 5 | zzz
  261. (3 rows)
  262. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 FULL JOIN t2 ON t1.num = t2.num;</code></strong>
  263. num | name | num | value
  264. -----+------+-----+-------
  265. 1 | a | 1 | xxx
  266. 2 | b | |
  267. 3 | c | 3 | yyy
  268. | | 5 | zzz
  269. (4 rows)
  270. </pre><p>
  271. </p><p>
  272. The join condition specified with <code class="literal">ON</code> can also contain
  273. conditions that do not relate directly to the join. This can
  274. prove useful for some queries but needs to be thought out
  275. carefully. For example:
  276. </p><pre class="screen">
  277. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num AND t2.value = 'xxx';</code></strong>
  278. num | name | num | value
  279. -----+------+-----+-------
  280. 1 | a | 1 | xxx
  281. 2 | b | |
  282. 3 | c | |
  283. (3 rows)
  284. </pre><p>
  285. Notice that placing the restriction in the <code class="literal">WHERE</code> clause
  286. produces a different result:
  287. </p><pre class="screen">
  288. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM t1 LEFT JOIN t2 ON t1.num = t2.num WHERE t2.value = 'xxx';</code></strong>
  289. num | name | num | value
  290. -----+------+-----+-------
  291. 1 | a | 1 | xxx
  292. (1 row)
  293. </pre><p>
  294. This is because a restriction placed in the <code class="literal">ON</code>
  295. clause is processed <span class="emphasis"><em>before</em></span> the join, while
  296. a restriction placed in the <code class="literal">WHERE</code> clause is processed
  297. <span class="emphasis"><em>after</em></span> the join.
  298. That does not matter with inner joins, but it matters a lot with outer
  299. joins.
  300. </p></div><div class="sect3" id="QUERIES-TABLE-ALIASES"><div class="titlepage"><div><div><h4 class="title">7.2.1.2. Table and Column Aliases</h4></div></div></div><a id="id-1.5.6.6.5.7.2" class="indexterm"></a><a id="id-1.5.6.6.5.7.3" class="indexterm"></a><p>
  301. A temporary name can be given to tables and complex table
  302. references to be used for references to the derived table in
  303. the rest of the query. This is called a <em class="firstterm">table
  304. alias</em>.
  305. </p><p>
  306. To create a table alias, write
  307. </p><pre class="synopsis">
  308. FROM <em class="replaceable"><code>table_reference</code></em> AS <em class="replaceable"><code>alias</code></em>
  309. </pre><p>
  310. or
  311. </p><pre class="synopsis">
  312. FROM <em class="replaceable"><code>table_reference</code></em> <em class="replaceable"><code>alias</code></em>
  313. </pre><p>
  314. The <code class="literal">AS</code> key word is optional noise.
  315. <em class="replaceable"><code>alias</code></em> can be any identifier.
  316. </p><p>
  317. A typical application of table aliases is to assign short
  318. identifiers to long table names to keep the join clauses
  319. readable. For example:
  320. </p><pre class="programlisting">
  321. SELECT * FROM some_very_long_table_name s JOIN another_fairly_long_name a ON s.id = a.num;
  322. </pre><p>
  323. </p><p>
  324. The alias becomes the new name of the table reference so far as the
  325. current query is concerned — it is not allowed to refer to the
  326. table by the original name elsewhere in the query. Thus, this is not
  327. valid:
  328. </p><pre class="programlisting">
  329. SELECT * FROM my_table AS m WHERE my_table.a &gt; 5; -- wrong
  330. </pre><p>
  331. </p><p>
  332. Table aliases are mainly for notational convenience, but it is
  333. necessary to use them when joining a table to itself, e.g.:
  334. </p><pre class="programlisting">
  335. SELECT * FROM people AS mother JOIN people AS child ON mother.id = child.mother_id;
  336. </pre><p>
  337. Additionally, an alias is required if the table reference is a
  338. subquery (see <a class="xref" href="queries-table-expressions.html#QUERIES-SUBQUERIES" title="7.2.1.3. Subqueries">Section 7.2.1.3</a>).
  339. </p><p>
  340. Parentheses are used to resolve ambiguities. In the following example,
  341. the first statement assigns the alias <code class="literal">b</code> to the second
  342. instance of <code class="literal">my_table</code>, but the second statement assigns the
  343. alias to the result of the join:
  344. </p><pre class="programlisting">
  345. SELECT * FROM my_table AS a CROSS JOIN my_table AS b ...
  346. SELECT * FROM (my_table AS a CROSS JOIN my_table) AS b ...
  347. </pre><p>
  348. </p><p>
  349. Another form of table aliasing gives temporary names to the columns of
  350. the table, as well as the table itself:
  351. </p><pre class="synopsis">
  352. FROM <em class="replaceable"><code>table_reference</code></em> [<span class="optional">AS</span>] <em class="replaceable"><code>alias</code></em> ( <em class="replaceable"><code>column1</code></em> [<span class="optional">, <em class="replaceable"><code>column2</code></em> [<span class="optional">, ...</span>]</span>] )
  353. </pre><p>
  354. If fewer column aliases are specified than the actual table has
  355. columns, the remaining columns are not renamed. This syntax is
  356. especially useful for self-joins or subqueries.
  357. </p><p>
  358. When an alias is applied to the output of a <code class="literal">JOIN</code>
  359. clause, the alias hides the original
  360. name(s) within the <code class="literal">JOIN</code>. For example:
  361. </p><pre class="programlisting">
  362. SELECT a.* FROM my_table AS a JOIN your_table AS b ON ...
  363. </pre><p>
  364. is valid SQL, but:
  365. </p><pre class="programlisting">
  366. SELECT a.* FROM (my_table AS a JOIN your_table AS b ON ...) AS c
  367. </pre><p>
  368. is not valid; the table alias <code class="literal">a</code> is not visible
  369. outside the alias <code class="literal">c</code>.
  370. </p></div><div class="sect3" id="QUERIES-SUBQUERIES"><div class="titlepage"><div><div><h4 class="title">7.2.1.3. Subqueries</h4></div></div></div><a id="id-1.5.6.6.5.8.2" class="indexterm"></a><p>
  371. Subqueries specifying a derived table must be enclosed in
  372. parentheses and <span class="emphasis"><em>must</em></span> be assigned a table
  373. alias name (as in <a class="xref" href="queries-table-expressions.html#QUERIES-TABLE-ALIASES" title="7.2.1.2. Table and Column Aliases">Section 7.2.1.2</a>). For
  374. example:
  375. </p><pre class="programlisting">
  376. FROM (SELECT * FROM table1) AS alias_name
  377. </pre><p>
  378. </p><p>
  379. This example is equivalent to <code class="literal">FROM table1 AS
  380. alias_name</code>. More interesting cases, which cannot be
  381. reduced to a plain join, arise when the subquery involves
  382. grouping or aggregation.
  383. </p><p>
  384. A subquery can also be a <code class="command">VALUES</code> list:
  385. </p><pre class="programlisting">
  386. FROM (VALUES ('anne', 'smith'), ('bob', 'jones'), ('joe', 'blow'))
  387. AS names(first, last)
  388. </pre><p>
  389. Again, a table alias is required. Assigning alias names to the columns
  390. of the <code class="command">VALUES</code> list is optional, but is good practice.
  391. For more information see <a class="xref" href="queries-values.html" title="7.7. VALUES Lists">Section 7.7</a>.
  392. </p></div><div class="sect3" id="QUERIES-TABLEFUNCTIONS"><div class="titlepage"><div><div><h4 class="title">7.2.1.4. Table Functions</h4></div></div></div><a id="id-1.5.6.6.5.9.2" class="indexterm"></a><a id="id-1.5.6.6.5.9.3" class="indexterm"></a><p>
  393. Table functions are functions that produce a set of rows, made up
  394. of either base data types (scalar types) or composite data types
  395. (table rows). They are used like a table, view, or subquery in
  396. the <code class="literal">FROM</code> clause of a query. Columns returned by table
  397. functions can be included in <code class="literal">SELECT</code>,
  398. <code class="literal">JOIN</code>, or <code class="literal">WHERE</code> clauses in the same manner
  399. as columns of a table, view, or subquery.
  400. </p><p>
  401. Table functions may also be combined using the <code class="literal">ROWS FROM</code>
  402. syntax, with the results returned in parallel columns; the number of
  403. result rows in this case is that of the largest function result, with
  404. smaller results padded with null values to match.
  405. </p><pre class="synopsis">
  406. <em class="replaceable"><code>function_call</code></em> [<span class="optional">WITH ORDINALITY</span>] [<span class="optional">[<span class="optional">AS</span>] <em class="replaceable"><code>table_alias</code></em> [<span class="optional">(<em class="replaceable"><code>column_alias</code></em> [<span class="optional">, ... </span>])</span>]</span>]
  407. ROWS FROM( <em class="replaceable"><code>function_call</code></em> [<span class="optional">, ... </span>] ) [<span class="optional">WITH ORDINALITY</span>] [<span class="optional">[<span class="optional">AS</span>] <em class="replaceable"><code>table_alias</code></em> [<span class="optional">(<em class="replaceable"><code>column_alias</code></em> [<span class="optional">, ... </span>])</span>]</span>]
  408. </pre><p>
  409. If the <code class="literal">WITH ORDINALITY</code> clause is specified, an
  410. additional column of type <code class="type">bigint</code> will be added to the
  411. function result columns. This column numbers the rows of the function
  412. result set, starting from 1. (This is a generalization of the
  413. SQL-standard syntax for <code class="literal">UNNEST ... WITH ORDINALITY</code>.)
  414. By default, the ordinal column is called <code class="literal">ordinality</code>, but
  415. a different column name can be assigned to it using
  416. an <code class="literal">AS</code> clause.
  417. </p><p>
  418. The special table function <code class="literal">UNNEST</code> may be called with
  419. any number of array parameters, and it returns a corresponding number of
  420. columns, as if <code class="literal">UNNEST</code>
  421. (<a class="xref" href="functions-array.html" title="9.18. Array Functions and Operators">Section 9.18</a>) had been called on each parameter
  422. separately and combined using the <code class="literal">ROWS FROM</code> construct.
  423. </p><pre class="synopsis">
  424. UNNEST( <em class="replaceable"><code>array_expression</code></em> [<span class="optional">, ... </span>] ) [<span class="optional">WITH ORDINALITY</span>] [<span class="optional">[<span class="optional">AS</span>] <em class="replaceable"><code>table_alias</code></em> [<span class="optional">(<em class="replaceable"><code>column_alias</code></em> [<span class="optional">, ... </span>])</span>]</span>]
  425. </pre><p>
  426. If no <em class="replaceable"><code>table_alias</code></em> is specified, the function
  427. name is used as the table name; in the case of a <code class="literal">ROWS FROM()</code>
  428. construct, the first function's name is used.
  429. </p><p>
  430. If column aliases are not supplied, then for a function returning a base
  431. data type, the column name is also the same as the function name. For a
  432. function returning a composite type, the result columns get the names
  433. of the individual attributes of the type.
  434. </p><p>
  435. Some examples:
  436. </p><pre class="programlisting">
  437. CREATE TABLE foo (fooid int, foosubid int, fooname text);
  438. CREATE FUNCTION getfoo(int) RETURNS SETOF foo AS $$
  439. SELECT * FROM foo WHERE fooid = $1;
  440. $$ LANGUAGE SQL;
  441. SELECT * FROM getfoo(1) AS t1;
  442. SELECT * FROM foo
  443. WHERE foosubid IN (
  444. SELECT foosubid
  445. FROM getfoo(foo.fooid) z
  446. WHERE z.fooid = foo.fooid
  447. );
  448. CREATE VIEW vw_getfoo AS SELECT * FROM getfoo(1);
  449. SELECT * FROM vw_getfoo;
  450. </pre><p>
  451. </p><p>
  452. In some cases it is useful to define table functions that can
  453. return different column sets depending on how they are invoked.
  454. To support this, the table function can be declared as returning
  455. the pseudo-type <code class="type">record</code>. When such a function is used in
  456. a query, the expected row structure must be specified in the
  457. query itself, so that the system can know how to parse and plan
  458. the query. This syntax looks like:
  459. </p><pre class="synopsis">
  460. <em class="replaceable"><code>function_call</code></em> [<span class="optional">AS</span>] <em class="replaceable"><code>alias</code></em> (<em class="replaceable"><code>column_definition</code></em> [<span class="optional">, ... </span>])
  461. <em class="replaceable"><code>function_call</code></em> AS [<span class="optional"><em class="replaceable"><code>alias</code></em></span>] (<em class="replaceable"><code>column_definition</code></em> [<span class="optional">, ... </span>])
  462. ROWS FROM( ... <em class="replaceable"><code>function_call</code></em> AS (<em class="replaceable"><code>column_definition</code></em> [<span class="optional">, ... </span>]) [<span class="optional">, ... </span>] )
  463. </pre><p>
  464. When not using the <code class="literal">ROWS FROM()</code> syntax,
  465. the <em class="replaceable"><code>column_definition</code></em> list replaces the column
  466. alias list that could otherwise be attached to the <code class="literal">FROM</code>
  467. item; the names in the column definitions serve as column aliases.
  468. When using the <code class="literal">ROWS FROM()</code> syntax,
  469. a <em class="replaceable"><code>column_definition</code></em> list can be attached to
  470. each member function separately; or if there is only one member function
  471. and no <code class="literal">WITH ORDINALITY</code> clause,
  472. a <em class="replaceable"><code>column_definition</code></em> list can be written in
  473. place of a column alias list following <code class="literal">ROWS FROM()</code>.
  474. </p><p>
  475. Consider this example:
  476. </p><pre class="programlisting">
  477. SELECT *
  478. FROM dblink('dbname=mydb', 'SELECT proname, prosrc FROM pg_proc')
  479. AS t1(proname name, prosrc text)
  480. WHERE proname LIKE 'bytea%';
  481. </pre><p>
  482. The <a class="xref" href="contrib-dblink-function.html" title="dblink"><span class="refentrytitle">dblink</span></a> function
  483. (part of the <a class="xref" href="dblink.html" title="F.10. dblink">dblink</a> module) executes
  484. a remote query. It is declared to return
  485. <code class="type">record</code> since it might be used for any kind of query.
  486. The actual column set must be specified in the calling query so
  487. that the parser knows, for example, what <code class="literal">*</code> should
  488. expand to.
  489. </p></div><div class="sect3" id="QUERIES-LATERAL"><div class="titlepage"><div><div><h4 class="title">7.2.1.5. <code class="literal">LATERAL</code> Subqueries</h4></div></div></div><a id="id-1.5.6.6.5.10.2" class="indexterm"></a><p>
  490. Subqueries appearing in <code class="literal">FROM</code> can be
  491. preceded by the key word <code class="literal">LATERAL</code>. This allows them to
  492. reference columns provided by preceding <code class="literal">FROM</code> items.
  493. (Without <code class="literal">LATERAL</code>, each subquery is
  494. evaluated independently and so cannot cross-reference any other
  495. <code class="literal">FROM</code> item.)
  496. </p><p>
  497. Table functions appearing in <code class="literal">FROM</code> can also be
  498. preceded by the key word <code class="literal">LATERAL</code>, but for functions the
  499. key word is optional; the function's arguments can contain references
  500. to columns provided by preceding <code class="literal">FROM</code> items in any case.
  501. </p><p>
  502. A <code class="literal">LATERAL</code> item can appear at top level in the
  503. <code class="literal">FROM</code> list, or within a <code class="literal">JOIN</code> tree. In the latter
  504. case it can also refer to any items that are on the left-hand side of a
  505. <code class="literal">JOIN</code> that it is on the right-hand side of.
  506. </p><p>
  507. When a <code class="literal">FROM</code> item contains <code class="literal">LATERAL</code>
  508. cross-references, evaluation proceeds as follows: for each row of the
  509. <code class="literal">FROM</code> item providing the cross-referenced column(s), or
  510. set of rows of multiple <code class="literal">FROM</code> items providing the
  511. columns, the <code class="literal">LATERAL</code> item is evaluated using that
  512. row or row set's values of the columns. The resulting row(s) are
  513. joined as usual with the rows they were computed from. This is
  514. repeated for each row or set of rows from the column source table(s).
  515. </p><p>
  516. A trivial example of <code class="literal">LATERAL</code> is
  517. </p><pre class="programlisting">
  518. SELECT * FROM foo, LATERAL (SELECT * FROM bar WHERE bar.id = foo.bar_id) ss;
  519. </pre><p>
  520. This is not especially useful since it has exactly the same result as
  521. the more conventional
  522. </p><pre class="programlisting">
  523. SELECT * FROM foo, bar WHERE bar.id = foo.bar_id;
  524. </pre><p>
  525. <code class="literal">LATERAL</code> is primarily useful when the cross-referenced
  526. column is necessary for computing the row(s) to be joined. A common
  527. application is providing an argument value for a set-returning function.
  528. For example, supposing that <code class="function">vertices(polygon)</code> returns the
  529. set of vertices of a polygon, we could identify close-together vertices
  530. of polygons stored in a table with:
  531. </p><pre class="programlisting">
  532. SELECT p1.id, p2.id, v1, v2
  533. FROM polygons p1, polygons p2,
  534. LATERAL vertices(p1.poly) v1,
  535. LATERAL vertices(p2.poly) v2
  536. WHERE (v1 &lt;-&gt; v2) &lt; 10 AND p1.id != p2.id;
  537. </pre><p>
  538. This query could also be written
  539. </p><pre class="programlisting">
  540. SELECT p1.id, p2.id, v1, v2
  541. FROM polygons p1 CROSS JOIN LATERAL vertices(p1.poly) v1,
  542. polygons p2 CROSS JOIN LATERAL vertices(p2.poly) v2
  543. WHERE (v1 &lt;-&gt; v2) &lt; 10 AND p1.id != p2.id;
  544. </pre><p>
  545. or in several other equivalent formulations. (As already mentioned,
  546. the <code class="literal">LATERAL</code> key word is unnecessary in this example, but
  547. we use it for clarity.)
  548. </p><p>
  549. It is often particularly handy to <code class="literal">LEFT JOIN</code> to a
  550. <code class="literal">LATERAL</code> subquery, so that source rows will appear in
  551. the result even if the <code class="literal">LATERAL</code> subquery produces no
  552. rows for them. For example, if <code class="function">get_product_names()</code> returns
  553. the names of products made by a manufacturer, but some manufacturers in
  554. our table currently produce no products, we could find out which ones
  555. those are like this:
  556. </p><pre class="programlisting">
  557. SELECT m.name
  558. FROM manufacturers m LEFT JOIN LATERAL get_product_names(m.id) pname ON true
  559. WHERE pname IS NULL;
  560. </pre><p>
  561. </p></div></div><div class="sect2" id="QUERIES-WHERE"><div class="titlepage"><div><div><h3 class="title">7.2.2. The <code class="literal">WHERE</code> Clause</h3></div></div></div><a id="id-1.5.6.6.6.2" class="indexterm"></a><p>
  562. The syntax of the <a class="xref" href="sql-select.html#SQL-WHERE" title="WHERE Clause"><code class="literal">WHERE</code> Clause</a> is
  563. </p><pre class="synopsis">
  564. WHERE <em class="replaceable"><code>search_condition</code></em>
  565. </pre><p>
  566. where <em class="replaceable"><code>search_condition</code></em> is any value
  567. expression (see <a class="xref" href="sql-expressions.html" title="4.2. Value Expressions">Section 4.2</a>) that
  568. returns a value of type <code class="type">boolean</code>.
  569. </p><p>
  570. After the processing of the <code class="literal">FROM</code> clause is done, each
  571. row of the derived virtual table is checked against the search
  572. condition. If the result of the condition is true, the row is
  573. kept in the output table, otherwise (i.e., if the result is
  574. false or null) it is discarded. The search condition typically
  575. references at least one column of the table generated in the
  576. <code class="literal">FROM</code> clause; this is not required, but otherwise the
  577. <code class="literal">WHERE</code> clause will be fairly useless.
  578. </p><div class="note"><h3 class="title">Note</h3><p>
  579. The join condition of an inner join can be written either in
  580. the <code class="literal">WHERE</code> clause or in the <code class="literal">JOIN</code> clause.
  581. For example, these table expressions are equivalent:
  582. </p><pre class="programlisting">
  583. FROM a, b WHERE a.id = b.id AND b.val &gt; 5
  584. </pre><p>
  585. and:
  586. </p><pre class="programlisting">
  587. FROM a INNER JOIN b ON (a.id = b.id) WHERE b.val &gt; 5
  588. </pre><p>
  589. or perhaps even:
  590. </p><pre class="programlisting">
  591. FROM a NATURAL JOIN b WHERE b.val &gt; 5
  592. </pre><p>
  593. Which one of these you use is mainly a matter of style. The
  594. <code class="literal">JOIN</code> syntax in the <code class="literal">FROM</code> clause is
  595. probably not as portable to other SQL database management systems,
  596. even though it is in the SQL standard. For
  597. outer joins there is no choice: they must be done in
  598. the <code class="literal">FROM</code> clause. The <code class="literal">ON</code> or <code class="literal">USING</code>
  599. clause of an outer join is <span class="emphasis"><em>not</em></span> equivalent to a
  600. <code class="literal">WHERE</code> condition, because it results in the addition
  601. of rows (for unmatched input rows) as well as the removal of rows
  602. in the final result.
  603. </p></div><p>
  604. Here are some examples of <code class="literal">WHERE</code> clauses:
  605. </p><pre class="programlisting">
  606. SELECT ... FROM fdt WHERE c1 &gt; 5
  607. SELECT ... FROM fdt WHERE c1 IN (1, 2, 3)
  608. SELECT ... FROM fdt WHERE c1 IN (SELECT c1 FROM t2)
  609. SELECT ... FROM fdt WHERE c1 IN (SELECT c3 FROM t2 WHERE c2 = fdt.c1 + 10)
  610. SELECT ... FROM fdt WHERE c1 BETWEEN (SELECT c3 FROM t2 WHERE c2 = fdt.c1 + 10) AND 100
  611. SELECT ... FROM fdt WHERE EXISTS (SELECT c1 FROM t2 WHERE c2 &gt; fdt.c1)
  612. </pre><p>
  613. <code class="literal">fdt</code> is the table derived in the
  614. <code class="literal">FROM</code> clause. Rows that do not meet the search
  615. condition of the <code class="literal">WHERE</code> clause are eliminated from
  616. <code class="literal">fdt</code>. Notice the use of scalar subqueries as
  617. value expressions. Just like any other query, the subqueries can
  618. employ complex table expressions. Notice also how
  619. <code class="literal">fdt</code> is referenced in the subqueries.
  620. Qualifying <code class="literal">c1</code> as <code class="literal">fdt.c1</code> is only necessary
  621. if <code class="literal">c1</code> is also the name of a column in the derived
  622. input table of the subquery. But qualifying the column name adds
  623. clarity even when it is not needed. This example shows how the column
  624. naming scope of an outer query extends into its inner queries.
  625. </p></div><div class="sect2" id="QUERIES-GROUP"><div class="titlepage"><div><div><h3 class="title">7.2.3. The <code class="literal">GROUP BY</code> and <code class="literal">HAVING</code> Clauses</h3></div></div></div><a id="id-1.5.6.6.7.2" class="indexterm"></a><a id="id-1.5.6.6.7.3" class="indexterm"></a><p>
  626. After passing the <code class="literal">WHERE</code> filter, the derived input
  627. table might be subject to grouping, using the <code class="literal">GROUP BY</code>
  628. clause, and elimination of group rows using the <code class="literal">HAVING</code>
  629. clause.
  630. </p><pre class="synopsis">
  631. SELECT <em class="replaceable"><code>select_list</code></em>
  632. FROM ...
  633. [<span class="optional">WHERE ...</span>]
  634. GROUP BY <em class="replaceable"><code>grouping_column_reference</code></em> [<span class="optional">, <em class="replaceable"><code>grouping_column_reference</code></em></span>]...
  635. </pre><p>
  636. The <a class="xref" href="sql-select.html#SQL-GROUPBY" title="GROUP BY Clause"><code class="literal">GROUP BY</code> Clause</a> is
  637. used to group together those rows in a table that have the same
  638. values in all the columns listed. The order in which the columns
  639. are listed does not matter. The effect is to combine each set
  640. of rows having common values into one group row that
  641. represents all rows in the group. This is done to
  642. eliminate redundancy in the output and/or compute aggregates that
  643. apply to these groups. For instance:
  644. </p><pre class="screen">
  645. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM test1;</code></strong>
  646. x | y
  647. ---+---
  648. a | 3
  649. c | 2
  650. b | 5
  651. a | 1
  652. (4 rows)
  653. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT x FROM test1 GROUP BY x;</code></strong>
  654. x
  655. ---
  656. a
  657. b
  658. c
  659. (3 rows)
  660. </pre><p>
  661. </p><p>
  662. In the second query, we could not have written <code class="literal">SELECT *
  663. FROM test1 GROUP BY x</code>, because there is no single value
  664. for the column <code class="literal">y</code> that could be associated with each
  665. group. The grouped-by columns can be referenced in the select list since
  666. they have a single value in each group.
  667. </p><p>
  668. In general, if a table is grouped, columns that are not
  669. listed in <code class="literal">GROUP BY</code> cannot be referenced except in aggregate
  670. expressions. An example with aggregate expressions is:
  671. </p><pre class="screen">
  672. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT x, sum(y) FROM test1 GROUP BY x;</code></strong>
  673. x | sum
  674. ---+-----
  675. a | 4
  676. b | 5
  677. c | 2
  678. (3 rows)
  679. </pre><p>
  680. Here <code class="literal">sum</code> is an aggregate function that
  681. computes a single value over the entire group. More information
  682. about the available aggregate functions can be found in <a class="xref" href="functions-aggregate.html" title="9.20. Aggregate Functions">Section 9.20</a>.
  683. </p><div class="tip"><h3 class="title">Tip</h3><p>
  684. Grouping without aggregate expressions effectively calculates the
  685. set of distinct values in a column. This can also be achieved
  686. using the <code class="literal">DISTINCT</code> clause (see <a class="xref" href="queries-select-lists.html#QUERIES-DISTINCT" title="7.3.3. DISTINCT">Section 7.3.3</a>).
  687. </p></div><p>
  688. Here is another example: it calculates the total sales for each
  689. product (rather than the total sales of all products):
  690. </p><pre class="programlisting">
  691. SELECT product_id, p.name, (sum(s.units) * p.price) AS sales
  692. FROM products p LEFT JOIN sales s USING (product_id)
  693. GROUP BY product_id, p.name, p.price;
  694. </pre><p>
  695. In this example, the columns <code class="literal">product_id</code>,
  696. <code class="literal">p.name</code>, and <code class="literal">p.price</code> must be
  697. in the <code class="literal">GROUP BY</code> clause since they are referenced in
  698. the query select list (but see below). The column
  699. <code class="literal">s.units</code> does not have to be in the <code class="literal">GROUP
  700. BY</code> list since it is only used in an aggregate expression
  701. (<code class="literal">sum(...)</code>), which represents the sales
  702. of a product. For each product, the query returns a summary row about
  703. all sales of the product.
  704. </p><a id="id-1.5.6.6.7.11" class="indexterm"></a><p>
  705. If the products table is set up so that, say,
  706. <code class="literal">product_id</code> is the primary key, then it would be
  707. enough to group by <code class="literal">product_id</code> in the above example,
  708. since name and price would be <em class="firstterm">functionally
  709. dependent</em> on the product ID, and so there would be no
  710. ambiguity about which name and price value to return for each product
  711. ID group.
  712. </p><p>
  713. In strict SQL, <code class="literal">GROUP BY</code> can only group by columns of
  714. the source table but <span class="productname">PostgreSQL</span> extends
  715. this to also allow <code class="literal">GROUP BY</code> to group by columns in the
  716. select list. Grouping by value expressions instead of simple
  717. column names is also allowed.
  718. </p><a id="id-1.5.6.6.7.14" class="indexterm"></a><p>
  719. If a table has been grouped using <code class="literal">GROUP BY</code>,
  720. but only certain groups are of interest, the
  721. <code class="literal">HAVING</code> clause can be used, much like a
  722. <code class="literal">WHERE</code> clause, to eliminate groups from the result.
  723. The syntax is:
  724. </p><pre class="synopsis">
  725. SELECT <em class="replaceable"><code>select_list</code></em> FROM ... [<span class="optional">WHERE ...</span>] GROUP BY ... HAVING <em class="replaceable"><code>boolean_expression</code></em>
  726. </pre><p>
  727. Expressions in the <code class="literal">HAVING</code> clause can refer both to
  728. grouped expressions and to ungrouped expressions (which necessarily
  729. involve an aggregate function).
  730. </p><p>
  731. Example:
  732. </p><pre class="screen">
  733. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT x, sum(y) FROM test1 GROUP BY x HAVING sum(y) &gt; 3;</code></strong>
  734. x | sum
  735. ---+-----
  736. a | 4
  737. b | 5
  738. (2 rows)
  739. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT x, sum(y) FROM test1 GROUP BY x HAVING x &lt; 'c';</code></strong>
  740. x | sum
  741. ---+-----
  742. a | 4
  743. b | 5
  744. (2 rows)
  745. </pre><p>
  746. </p><p>
  747. Again, a more realistic example:
  748. </p><pre class="programlisting">
  749. SELECT product_id, p.name, (sum(s.units) * (p.price - p.cost)) AS profit
  750. FROM products p LEFT JOIN sales s USING (product_id)
  751. WHERE s.date &gt; CURRENT_DATE - INTERVAL '4 weeks'
  752. GROUP BY product_id, p.name, p.price, p.cost
  753. HAVING sum(p.price * s.units) &gt; 5000;
  754. </pre><p>
  755. In the example above, the <code class="literal">WHERE</code> clause is selecting
  756. rows by a column that is not grouped (the expression is only true for
  757. sales during the last four weeks), while the <code class="literal">HAVING</code>
  758. clause restricts the output to groups with total gross sales over
  759. 5000. Note that the aggregate expressions do not necessarily need
  760. to be the same in all parts of the query.
  761. </p><p>
  762. If a query contains aggregate function calls, but no <code class="literal">GROUP BY</code>
  763. clause, grouping still occurs: the result is a single group row (or
  764. perhaps no rows at all, if the single row is then eliminated by
  765. <code class="literal">HAVING</code>).
  766. The same is true if it contains a <code class="literal">HAVING</code> clause, even
  767. without any aggregate function calls or <code class="literal">GROUP BY</code> clause.
  768. </p></div><div class="sect2" id="QUERIES-GROUPING-SETS"><div class="titlepage"><div><div><h3 class="title">7.2.4. <code class="literal">GROUPING SETS</code>, <code class="literal">CUBE</code>, and <code class="literal">ROLLUP</code></h3></div></div></div><a id="id-1.5.6.6.8.2" class="indexterm"></a><a id="id-1.5.6.6.8.3" class="indexterm"></a><a id="id-1.5.6.6.8.4" class="indexterm"></a><p>
  769. More complex grouping operations than those described above are possible
  770. using the concept of <em class="firstterm">grouping sets</em>. The data selected by
  771. the <code class="literal">FROM</code> and <code class="literal">WHERE</code> clauses is grouped separately
  772. by each specified grouping set, aggregates computed for each group just as
  773. for simple <code class="literal">GROUP BY</code> clauses, and then the results returned.
  774. For example:
  775. </p><pre class="screen">
  776. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT * FROM items_sold;</code></strong>
  777. brand | size | sales
  778. -------+------+-------
  779. Foo | L | 10
  780. Foo | M | 20
  781. Bar | M | 15
  782. Bar | L | 5
  783. (4 rows)
  784. <code class="prompt">=&gt;</code> <strong class="userinput"><code>SELECT brand, size, sum(sales) FROM items_sold GROUP BY GROUPING SETS ((brand), (size), ());</code></strong>
  785. brand | size | sum
  786. -------+------+-----
  787. Foo | | 30
  788. Bar | | 20
  789. | L | 15
  790. | M | 35
  791. | | 50
  792. (5 rows)
  793. </pre><p>
  794. </p><p>
  795. Each sublist of <code class="literal">GROUPING SETS</code> may specify zero or more columns
  796. or expressions and is interpreted the same way as though it were directly
  797. in the <code class="literal">GROUP BY</code> clause. An empty grouping set means that all
  798. rows are aggregated down to a single group (which is output even if no
  799. input rows were present), as described above for the case of aggregate
  800. functions with no <code class="literal">GROUP BY</code> clause.
  801. </p><p>
  802. References to the grouping columns or expressions are replaced
  803. by null values in result rows for grouping sets in which those
  804. columns do not appear. To distinguish which grouping a particular output
  805. row resulted from, see <a class="xref" href="functions-aggregate.html#FUNCTIONS-GROUPING-TABLE" title="Table 9.59. Grouping Operations">Table 9.59</a>.
  806. </p><p>
  807. A shorthand notation is provided for specifying two common types of grouping set.
  808. A clause of the form
  809. </p><pre class="programlisting">
  810. ROLLUP ( <em class="replaceable"><code>e1</code></em>, <em class="replaceable"><code>e2</code></em>, <em class="replaceable"><code>e3</code></em>, ... )
  811. </pre><p>
  812. represents the given list of expressions and all prefixes of the list including
  813. the empty list; thus it is equivalent to
  814. </p><pre class="programlisting">
  815. GROUPING SETS (
  816. ( <em class="replaceable"><code>e1</code></em>, <em class="replaceable"><code>e2</code></em>, <em class="replaceable"><code>e3</code></em>, ... ),
  817. ...
  818. ( <em class="replaceable"><code>e1</code></em>, <em class="replaceable"><code>e2</code></em> ),
  819. ( <em class="replaceable"><code>e1</code></em> ),
  820. ( )
  821. )
  822. </pre><p>
  823. This is commonly used for analysis over hierarchical data; e.g. total
  824. salary by department, division, and company-wide total.
  825. </p><p>
  826. A clause of the form
  827. </p><pre class="programlisting">
  828. CUBE ( <em class="replaceable"><code>e1</code></em>, <em class="replaceable"><code>e2</code></em>, ... )
  829. </pre><p>
  830. represents the given list and all of its possible subsets (i.e. the power
  831. set). Thus
  832. </p><pre class="programlisting">
  833. CUBE ( a, b, c )
  834. </pre><p>
  835. is equivalent to
  836. </p><pre class="programlisting">
  837. GROUPING SETS (
  838. ( a, b, c ),
  839. ( a, b ),
  840. ( a, c ),
  841. ( a ),
  842. ( b, c ),
  843. ( b ),
  844. ( c ),
  845. ( )
  846. )
  847. </pre><p>
  848. </p><p>
  849. The individual elements of a <code class="literal">CUBE</code> or <code class="literal">ROLLUP</code>
  850. clause may be either individual expressions, or sublists of elements in
  851. parentheses. In the latter case, the sublists are treated as single
  852. units for the purposes of generating the individual grouping sets.
  853. For example:
  854. </p><pre class="programlisting">
  855. CUBE ( (a, b), (c, d) )
  856. </pre><p>
  857. is equivalent to
  858. </p><pre class="programlisting">
  859. GROUPING SETS (
  860. ( a, b, c, d ),
  861. ( a, b ),
  862. ( c, d ),
  863. ( )
  864. )
  865. </pre><p>
  866. and
  867. </p><pre class="programlisting">
  868. ROLLUP ( a, (b, c), d )
  869. </pre><p>
  870. is equivalent to
  871. </p><pre class="programlisting">
  872. GROUPING SETS (
  873. ( a, b, c, d ),
  874. ( a, b, c ),
  875. ( a ),
  876. ( )
  877. )
  878. </pre><p>
  879. </p><p>
  880. The <code class="literal">CUBE</code> and <code class="literal">ROLLUP</code> constructs can be used either
  881. directly in the <code class="literal">GROUP BY</code> clause, or nested inside a
  882. <code class="literal">GROUPING SETS</code> clause. If one <code class="literal">GROUPING SETS</code> clause
  883. is nested inside another, the effect is the same as if all the elements of
  884. the inner clause had been written directly in the outer clause.
  885. </p><p>
  886. If multiple grouping items are specified in a single <code class="literal">GROUP BY</code>
  887. clause, then the final list of grouping sets is the cross product of the
  888. individual items. For example:
  889. </p><pre class="programlisting">
  890. GROUP BY a, CUBE (b, c), GROUPING SETS ((d), (e))
  891. </pre><p>
  892. is equivalent to
  893. </p><pre class="programlisting">
  894. GROUP BY GROUPING SETS (
  895. (a, b, c, d), (a, b, c, e),
  896. (a, b, d), (a, b, e),
  897. (a, c, d), (a, c, e),
  898. (a, d), (a, e)
  899. )
  900. </pre><p>
  901. </p><div class="note"><h3 class="title">Note</h3><p>
  902. The construct <code class="literal">(a, b)</code> is normally recognized in expressions as
  903. a <a class="link" href="sql-expressions.html#SQL-SYNTAX-ROW-CONSTRUCTORS" title="4.2.13. Row Constructors">row constructor</a>.
  904. Within the <code class="literal">GROUP BY</code> clause, this does not apply at the top
  905. levels of expressions, and <code class="literal">(a, b)</code> is parsed as a list of
  906. expressions as described above. If for some reason you <span class="emphasis"><em>need</em></span>
  907. a row constructor in a grouping expression, use <code class="literal">ROW(a, b)</code>.
  908. </p></div></div><div class="sect2" id="QUERIES-WINDOW"><div class="titlepage"><div><div><h3 class="title">7.2.5. Window Function Processing</h3></div></div></div><a id="id-1.5.6.6.9.2" class="indexterm"></a><p>
  909. If the query contains any window functions (see
  910. <a class="xref" href="tutorial-window.html" title="3.5. Window Functions">Section 3.5</a>,
  911. <a class="xref" href="functions-window.html" title="9.21. Window Functions">Section 9.21</a> and
  912. <a class="xref" href="sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS" title="4.2.8. Window Function Calls">Section 4.2.8</a>), these functions are evaluated
  913. after any grouping, aggregation, and <code class="literal">HAVING</code> filtering is
  914. performed. That is, if the query uses any aggregates, <code class="literal">GROUP
  915. BY</code>, or <code class="literal">HAVING</code>, then the rows seen by the window functions
  916. are the group rows instead of the original table rows from
  917. <code class="literal">FROM</code>/<code class="literal">WHERE</code>.
  918. </p><p>
  919. When multiple window functions are used, all the window functions having
  920. syntactically equivalent <code class="literal">PARTITION BY</code> and <code class="literal">ORDER BY</code>
  921. clauses in their window definitions are guaranteed to be evaluated in a
  922. single pass over the data. Therefore they will see the same sort ordering,
  923. even if the <code class="literal">ORDER BY</code> does not uniquely determine an ordering.
  924. However, no guarantees are made about the evaluation of functions having
  925. different <code class="literal">PARTITION BY</code> or <code class="literal">ORDER BY</code> specifications.
  926. (In such cases a sort step is typically required between the passes of
  927. window function evaluations, and the sort is not guaranteed to preserve
  928. ordering of rows that its <code class="literal">ORDER BY</code> sees as equivalent.)
  929. </p><p>
  930. Currently, window functions always require presorted data, and so the
  931. query output will be ordered according to one or another of the window
  932. functions' <code class="literal">PARTITION BY</code>/<code class="literal">ORDER BY</code> clauses.
  933. It is not recommended to rely on this, however. Use an explicit
  934. top-level <code class="literal">ORDER BY</code> clause if you want to be sure the
  935. results are sorted in a particular way.
  936. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="queries-overview.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="queries.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="queries-select-lists.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">7.1. Overview </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 7.3. Select Lists</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1