select.asciidoc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. [role="xpack"]
  2. [testenv="basic"]
  3. [[sql-syntax-select]]
  4. === SELECT
  5. .Synopsis
  6. [source, sql]
  7. ----
  8. SELECT select_expr [, ...]
  9. [ FROM table_name ]
  10. [ WHERE condition ]
  11. [ GROUP BY grouping_element [, ...] ]
  12. [ HAVING condition]
  13. [ ORDER BY expression [ ASC | DESC ] [, ...] ]
  14. [ LIMIT [ count ] ]
  15. ----
  16. .Description
  17. Retrieves rows from zero or more tables.
  18. The general execution of `SELECT` is as follows:
  19. . All elements in the `FROM` list are computed (each element can be base or alias table). Currently `FROM` supports exactly one table. Do note however that the table name can be a pattern (see <<sql-syntax-from, FROM Clause>> below).
  20. . If the `WHERE` clause is specified, all rows that do not satisfy the condition are eliminated from the output. (See <<sql-syntax-where, WHERE Clause>> below.)
  21. . If the `GROUP BY` clause is specified, or if there are aggregate function calls, the output is combined into groups of rows that match on one or more values, and the results of aggregate functions are computed. If the `HAVING` clause is present, it eliminates groups that do not satisfy the given condition. (See <<sql-syntax-group-by, GROUP BY Clause>> and <<sql-syntax-having, HAVING Clause>> below.)
  22. . The actual output rows are computed using the `SELECT` output expressions for each selected row or row group.
  23. . If the `ORDER BY` clause is specified, the returned rows are sorted in the specified order. If `ORDER BY` is not given, the rows are returned in whatever order the system finds fastest to produce. (See <<sql-syntax-order-by,ORDER BY Clause>> below.)
  24. . If the `LIMIT` is specified, the `SELECT` statement only returns a subset of the result rows. (See <<sql-syntax-limit, LIMIT Clause>> below.)
  25. [[sql-syntax-select-list]]
  26. ==== `SELECT` List
  27. `SELECT` list, namely the expressions between `SELECT` and `FROM`, represent the output rows of the `SELECT` statement.
  28. As with a table, every output column of a `SELECT` has a name which can be either specified per column through the `AS` keyword :
  29. [source,sql]
  30. ----
  31. SELECT column AS c
  32. ----
  33. assigned by {es-sql} if no name is given:
  34. [source,sql]
  35. ----
  36. SELECT 1 + 1
  37. ----
  38. or if it's a simple column reference, use its name as the column name:
  39. [source,sql]
  40. ----
  41. SELECT col FROM table
  42. ----
  43. [[sql-syntax-select-wildcard]]
  44. ==== Wildcard
  45. To select all the columns in the source, one can use `*`:
  46. ["source","sql",subs="attributes,callouts,macros"]
  47. --------------------------------------------------
  48. include-tagged::{sql-specs}/select.sql-spec[wildcardWithOrder]
  49. --------------------------------------------------
  50. which essentially returns all columsn found.
  51. [[sql-syntax-from]]
  52. [float]
  53. ==== FROM Clause
  54. The `FROM` clause specifies one table for the `SELECT` and has the following syntax:
  55. [source, sql]
  56. ----
  57. FROM table_name [ [ AS ] alias ]
  58. ----
  59. where:
  60. `table_name`::
  61. Represents the name (optionally qualified) of an existing table, either a concrete or base one (actual index) or alias.
  62. If the table name contains special SQL characters (such as `.`,`-`,etc...) use double quotes to escape them:
  63. [source, sql]
  64. ----
  65. SELECT ... FROM "some-table"
  66. ----
  67. The name can be a <<multi-index, pattern>> pointing to multiple indices (likely requiring quoting as mentioned above) with the restriction that *all* resolved concrete tables have **exact mapping**.
  68. `alias`::
  69. A substitute name for the `FROM` item containing the alias. An alias is used for brevity or to eliminate ambiguity. When an alias is provided, it completely hides the actual name of the table and must be used in its place.
  70. [[sql-syntax-where]]
  71. [float]
  72. ==== WHERE Clause
  73. The optional `WHERE` clause is used to filter rows from the query and has the following syntax:
  74. [source, sql]
  75. ----
  76. WHERE condition
  77. ----
  78. where:
  79. `condition`::
  80. Represents an expression that evaluates to a `boolean`. Only the rows that match the condition (to `true`) are returned.
  81. [[sql-syntax-group-by]]
  82. [float]
  83. ==== GROUP BY
  84. The `GROUP BY` clause is used to divide the results into groups of rows on matching values from the designated columns. It has the following syntax:
  85. [source, sql]
  86. ----
  87. GROUP BY grouping_element [, ...]
  88. ----
  89. where:
  90. `grouping_element`::
  91. Represents an expression on which rows are being grouped _on_. It can be a column name, name or ordinal number of a column or an arbitrary expression of column values.
  92. When a `GROUP BY` clause is used in a `SELECT`, _all_ output expressions must be either aggregate functions or expressions used for grouping or derivates of (otherwise there would be more than one possible value to return for each ungrouped column).
  93. [[sql-syntax-having]]
  94. [float]
  95. ==== HAVING
  96. The `HAVING` clause can be used _only_ along aggregate functions (and thus `GROUP BY`) to filter what groups are kept or not and has the following syntax:
  97. [source, sql]
  98. ----
  99. GROUP BY condition
  100. ----
  101. where:
  102. `condition`::
  103. Represents an expression that evaluates to a `boolean`. Only groups that match the condition (to `true`) are returned.
  104. Both `WHERE` and `HAVING` are used for filtering however there are several differences between them:
  105. . `WHERE` works on individual *rows*, `HAVING` works on the *groups* created by ``GROUP BY``
  106. . `WHERE` is evaluated *before* grouping, `HAVING` is evaluated *after* grouping
  107. Note that it is possible to have a `HAVING` clause without a ``GROUP BY``. In this case, an __implicit grouping__ is applied, meaning all selected rows are considered to form a single group and `HAVING` can be applied on any of the aggregate functions specified on this group. `
  108. As such a query emits only a single row (as there is only a single group), `HAVING` condition returns either one row (the group) or zero if the condition fails.
  109. [[sql-syntax-order-by]]
  110. [float]
  111. ==== ORDER BY
  112. The `ORDER BY` clause is used to sort the results of `SELECT` by one or more expressions:
  113. [source, sql]
  114. ----
  115. ORDER BY expression [ ASC | DESC ] [, ...]
  116. ----
  117. where:
  118. `expression`::
  119. Represents an input column, an output column or an ordinal number of the position (starting from one) of an output column. Additionally, ordering can be done based on the results _score_ `
  120. The direction, if not specified, is by default `ASC` (ascending). `
  121. Regardless of the ordering specified, null values are ordered last (at the end).
  122. IMPORTANT: When used along-side, `GROUP BY` expression can point _only_ to the columns used for grouping.
  123. For example, the following query sorts by an arbitrary input field (`page_count`):
  124. [source,js]
  125. --------------------------------------------------
  126. POST /_xpack/sql?format=txt
  127. {
  128. "query": "SELECT * FROM library ORDER BY page_count DESC LIMIT 5"
  129. }
  130. --------------------------------------------------
  131. // CONSOLE
  132. // TEST[setup:library]
  133. which results in something like:
  134. [source,text]
  135. --------------------------------------------------
  136. author | name | page_count | release_date
  137. -----------------+--------------------+---------------+------------------------
  138. Peter F. Hamilton|Pandora's Star |768 |2004-03-02T00:00:00.000Z
  139. Vernor Vinge |A Fire Upon the Deep|613 |1992-06-01T00:00:00.000Z
  140. Frank Herbert |Dune |604 |1965-06-01T00:00:00.000Z
  141. Alastair Reynolds|Revelation Space |585 |2000-03-15T00:00:00.000Z
  142. James S.A. Corey |Leviathan Wakes |561 |2011-06-02T00:00:00.000Z
  143. --------------------------------------------------
  144. // TESTRESPONSE[s/\|/\\|/ s/\+/\\+/]
  145. // TESTRESPONSE[_cat]
  146. [[sql-syntax-order-by-score]]
  147. ==== Order By Score
  148. When doing full-text queries in the `WHERE` clause, results can be returned based on their
  149. {defguide}/relevance-intro.html[score] or _relevance_ to the given query.
  150. NOTE: When doing multiple text queries in the `WHERE` clause then, their scores will be
  151. combined using the same rules as {es}'s
  152. <<query-dsl-bool-query,bool query>>.
  153. To sort based on the `score`, use the special function `SCORE()`:
  154. [source,js]
  155. --------------------------------------------------
  156. POST /_xpack/sql?format=txt
  157. {
  158. "query": "SELECT SCORE(), * FROM library WHERE match(name, 'dune') ORDER BY SCORE() DESC"
  159. }
  160. --------------------------------------------------
  161. // CONSOLE
  162. // TEST[setup:library]
  163. Which results in something like:
  164. [source,text]
  165. --------------------------------------------------
  166. SCORE() | author | name | page_count | release_date
  167. ---------------+---------------+-------------------+---------------+------------------------
  168. 2.288635 |Frank Herbert |Dune |604 |1965-06-01T00:00:00.000Z
  169. 1.8893257 |Frank Herbert |Dune Messiah |331 |1969-10-15T00:00:00.000Z
  170. 1.6086555 |Frank Herbert |Children of Dune |408 |1976-04-21T00:00:00.000Z
  171. 1.4005898 |Frank Herbert |God Emperor of Dune|454 |1981-05-28T00:00:00.000Z
  172. --------------------------------------------------
  173. // TESTRESPONSE[s/\|/\\|/ s/\+/\\+/ s/\(/\\\(/ s/\)/\\\)/]
  174. // TESTRESPONSE[_cat]
  175. Note that you can return `SCORE()` by adding it to the where clause. This
  176. is possible even if you are not sorting by `SCORE()`:
  177. [source,js]
  178. --------------------------------------------------
  179. POST /_xpack/sql?format=txt
  180. {
  181. "query": "SELECT SCORE(), * FROM library WHERE match(name, 'dune') ORDER BY page_count DESC"
  182. }
  183. --------------------------------------------------
  184. // CONSOLE
  185. // TEST[setup:library]
  186. [source,text]
  187. --------------------------------------------------
  188. SCORE() | author | name | page_count | release_date
  189. ---------------+---------------+-------------------+---------------+------------------------
  190. 2.288635 |Frank Herbert |Dune |604 |1965-06-01T00:00:00.000Z
  191. 1.4005898 |Frank Herbert |God Emperor of Dune|454 |1981-05-28T00:00:00.000Z
  192. 1.6086555 |Frank Herbert |Children of Dune |408 |1976-04-21T00:00:00.000Z
  193. 1.8893257 |Frank Herbert |Dune Messiah |331 |1969-10-15T00:00:00.000Z
  194. --------------------------------------------------
  195. // TESTRESPONSE[s/\|/\\|/ s/\+/\\+/ s/\(/\\\(/ s/\)/\\\)/]
  196. // TESTRESPONSE[_cat]
  197. NOTE:
  198. Trying to return `score` from a non full-text queries will return the same value for all results, as
  199. all are equilley relevant.
  200. [[sql-syntax-limit]]
  201. [float]
  202. ==== LIMIT
  203. The `LIMIT` clause restricts (limits) the number of rows returns using the format:
  204. [source, sql]
  205. ----
  206. LIMIT ( count | ALL )
  207. ----
  208. where
  209. count:: is a positive integer or zero indicating the maximum *possible* number of results being returned (as there might be less matches than the limit). If `0` is specified, no results are returned.
  210. ALL:: indicates there is no limit and thus all results are being returned.