Selection Queries

Selection queries read and process data in CockroachDB. They are moregeneral than simple SELECT clauses: they cangroup one or more selection clauses with setoperations and can request a specificordering or row limit.

Selection queries can occur:

Synopsis

WITHcommon_table_expr,select_clausesort_clauselimit_clauseoffset_clause

Parameters

ParameterDescription
common_table_exprSee Common Table Expressions.
select_clauseA valid selection clause, either simple or using set operations.
sort_clauseAn optional ORDER BY clause. See Ordering Query Results for details.
limit_clauseAn optional LIMIT clause. See Limiting Query Results for details.
offset_clauseAn optional OFFSET clause. See Limiting Query Results for details.

The optional LIMIT and OFFSET clauses can appear in any order, but must appear after ORDER BY, if also present.

Note:
Because the WITH, ORDER BY, LIMIT and OFFSET sub-clauses are all optional, any simple selection clause is also a valid selection query.

Selection clauses

Selection clauses are the main component of a selection query. Theydefine tabular data. There are four specific syntax forms collectively named selection clauses:

FormUsage
SELECTLoad or compute tabular data from various sources. This is the most common selection clause.
VALUESList tabular data by the client.
TABLELoad tabular data from the database.
Set OperationsCombine tabular data from two or more selection clauses.

Note:
To perform joins or other relational operations over selection clauses, use a table expression and convert it back into a selection clause with TABLE or SELECT.

Synopsis

simple_select_clausevalues_clausetable_clauseset_operation(simple_select_clausevalues_clausetable_clauseset_operation)

VALUES clause

Syntax

VALUES(a_expr,),

A VALUES clause defines tabular data defined by the expressionslisted within parentheses. Each parenthesis group defines a single rowin the resulting table.

The columns of the resulting table data have automatically generatednames. These names can be modified withAS when theVALUES clause is used as a sub-query.

Example

  1. > VALUES (1, 2, 3), (4, 5, 6);
  1. +---------+---------+---------+
  2. | column1 | column2 | column3 |
  3. +---------+---------+---------+
  4. | 1 | 2 | 3 |
  5. | 4 | 5 | 6 |
  6. +---------+---------+---------+

TABLE clause

Syntax

TABLEtable_ref

A TABLE clause reads tabular data from a specified table. Thecolumns of the resulting table data are named after the schema of thetable.

In general, TABLE x is equivalent to SELECT * FROM x, but it isshorter to type.

Note:
Any table expression between parentheses is a valid operand for TABLE, not just simple table or view names.

Example

  1. > CREATE TABLE employee_copy AS TABLE employee;

This statement copies the content from table employee into a newtable. However, note that the TABLE clause does not preserve the indexing,foreign key, or constraint and default information from the schema of thetable it reads from, so in this example, the new table employee_copywill likely have a simpler schema than employee.

Other examples:

  1. > TABLE employee;
  1. > INSERT INTO employee_copy TABLE employee;

SELECT clause

See Simple SELECT Clause for moredetails.

Set operations

Set operations combine data from two selectionclauses. They are valid as operand to otherset operations or as main component in a selection query.

Synopsis

select_clauseUNIONINTERSECTEXCEPTALLDISTINCTselect_clause

Set operators

SQL lets you compare the results of multiple selection clauses. You can think of each of the set operators as representing a Boolean operator:

  • UNION = OR
  • INTERSECT = AND
  • EXCEPT = NOT
    By default, each of these comparisons displays only one copy of each value (similar to SELECT DISTINCT). However, each function also lets you add an ALL to the clause to display duplicate values.

Union: Combine two queries

UNION combines the results of two queries into one result.

  1. > SELECT name
  2. FROM accounts
  3. WHERE state_opened IN ('AZ', 'NY')
  4. UNION
  5. SELECT name
  6. FROM mortgages
  7. WHERE state_opened IN ('AZ', 'NY');
  1. +-----------------+
  2. | name |
  3. +-----------------+
  4. | Naseem Joossens |
  5. | Ricarda Caron |
  6. | Carola Dahl |
  7. | Aygün Sanna |
  8. +-----------------+

To show duplicate rows, you can use ALL.

  1. > SELECT name
  2. FROM accounts
  3. WHERE state_opened IN ('AZ', 'NY')
  4. UNION ALL
  5. SELECT name
  6. FROM mortgages
  7. WHERE state_opened IN ('AZ', 'NY');
  1. +-----------------+
  2. | name |
  3. +-----------------+
  4. | Naseem Joossens |
  5. | Ricarda Caron |
  6. | Carola Dahl |
  7. | Naseem Joossens |
  8. | Aygün Sanna |
  9. | Carola Dahl |
  10. +-----------------+

Intersect: Retrieve intersection of two queries

INTERSECT finds only values that are present in both query operands.

  1. > SELECT name
  2. FROM accounts
  3. WHERE state_opened IN ('NJ', 'VA')
  4. INTERSECT
  5. SELECT name
  6. FROM mortgages;
  1. +-----------------+
  2. | name |
  3. +-----------------+
  4. | Danijel Whinery |
  5. | Agar Archer |
  6. +-----------------+

Except: Exclude one query's results from another

EXCEPT finds values that are present in the first query operand but not the second.

  1. > SELECT name
  2. FROM mortgages
  3. EXCEPT
  4. SELECT name
  5. FROM accounts;
  1. +------------------+
  2. | name |
  3. +------------------+
  4. | Günay García |
  5. | Karla Goddard |
  6. | Cybele Seaver |
  7. +------------------+

Ordering results

The following sections provide examples. For more details, see Ordering Query Results.

Order retrieved rows by one column

  1. > SELECT *
  2. FROM accounts
  3. WHERE balance BETWEEN 350 AND 500
  4. ORDER BY balance DESC;
  1. +----+--------------------+---------+----------+--------------+
  2. | id | name | balance | type | state_opened |
  3. +----+--------------------+---------+----------+--------------+
  4. | 12 | Raniya Žitnik | 500 | savings | CT |
  5. | 59 | Annibale Karga | 500 | savings | ND |
  6. | 27 | Adelbert Ventura | 500 | checking | IA |
  7. | 86 | Theresa Slaski | 500 | checking | WY |
  8. | 73 | Ruadh Draganov | 500 | checking | TN |
  9. | 16 | Virginia Ruan | 400 | checking | HI |
  10. | 43 | Tahirih Malinowski | 400 | checking | MS |
  11. | 50 | Dusan Mallory | 350 | savings | NV |
  12. +----+--------------------+---------+----------+--------------+

Order retrieved rows by multiple columns

Columns are sorted in the order you list them in sortby_list. For example, ORDER BY a, b sorts the rows by column a and then sorts rows with the same a value by their column b values.

  1. > SELECT *
  2. FROM accounts
  3. WHERE balance BETWEEN 350 AND 500
  4. ORDER BY balance DESC, name ASC;
  1. +----+--------------------+---------+----------+--------------+
  2. | id | name | balance | type | state_opened |
  3. +----+--------------------+---------+----------+--------------+
  4. | 27 | Adelbert Ventura | 500 | checking | IA |
  5. | 59 | Annibale Karga | 500 | savings | ND |
  6. | 12 | Raniya Žitnik | 500 | savings | CT |
  7. | 73 | Ruadh Draganov | 500 | checking | TN |
  8. | 86 | Theresa Slaski | 500 | checking | WY |
  9. | 43 | Tahirih Malinowski | 400 | checking | MS |
  10. | 16 | Virginia Ruan | 400 | checking | HI |
  11. | 50 | Dusan Mallory | 350 | savings | NV |
  12. +----+--------------------+---------+----------+--------------+

Limiting row count and pagination

The following sections provide examples. For more details, see Limiting Query Results.

Limit number of retrieved results

You can reduce the number of results with LIMIT.

  1. > SELECT id, name
  2. FROM accounts
  3. LIMIT 5;
  1. +----+------------------+
  2. | id | name |
  3. +----+------------------+
  4. | 1 | Bjorn Fairclough |
  5. | 2 | Bjorn Fairclough |
  6. | 3 | Arturo Nevin |
  7. | 4 | Arturo Nevin |
  8. | 5 | Naseem Joossens |
  9. +----+------------------+

Paginate through limited results

If you want to limit the number of results, but go beyond the initial set, use OFFSET to proceed to the next set of results. This is often used to paginate through large tables where not all of the values need to be immediately retrieved.

  1. > SELECT id, name
  2. FROM accounts
  3. LIMIT 5
  4. OFFSET 5;
  1. +----+------------------+
  2. | id | name |
  3. +----+------------------+
  4. | 6 | Juno Studwick |
  5. | 7 | Juno Studwick |
  6. | 8 | Eutychia Roberts |
  7. | 9 | Ricarda Moriarty |
  8. | 10 | Henrik Brankovic |
  9. +----+------------------+

Composability

Selection clauses are defined in the context of selection queries. Table expressions are defined in the context of the FROM sub-clause of SELECT. Nevertheless, they can be integrated with one another to form more complex queries or statements.

Using any selection clause as a selection query

Any selection clause can be used as aselection query with no change.

For example, the construct SELECT * FROM accounts is a selection clause. It is also a valid selection query, and thus can be used as a stand-alone statement by appending a semicolon:

  1. > SELECT * FROM accounts;
  1. +----+-----------------------+---------+----------+--------------+
  2. | id | name | balance | type | state_opened |
  3. +----+-----------------------+---------+----------+--------------+
  4. | 1 | Bjorn Fairclough | 1200 | checking | AL |
  5. | 2 | Bjorn Fairclough | 2500 | savings | AL |
  6. | 3 | Arturo Nevin | 250 | checking | AK |
  7. [ truncated ]
  8. +----+-----------------------+---------+----------+--------------+

Likewise, the construct VALUES (1), (2), (3) is also a selectionclause and thus can also be used as a selection query on its own:

  1. > VALUES (1), (2), (3);
  1. +---------+
  2. | column1 |
  3. +---------+
  4. | 1 |
  5. | 2 |
  6. | 3 |
  7. +---------+
  8. (3 rows)

Using any table expression as selection clause

Any table expression can be used as a selection clause (and thus also a selection query) by prefixing it with TABLE or by using it as an operand to SELECT * FROM.

For example, the simple table name customers is a table expression, which designates all rows in that table. The expressions TABLE accounts and SELECT * FROM accounts are valid selection clauses.

Likewise, the SQL join expression customers c JOIN orders o ON c.id = o.customer_id is a table expression. You can turn it into a valid selection clause, and thus a valid selection query as follows:

  1. > TABLE (customers c JOIN orders o ON c.id = o.customer_id);
  1. > SELECT * FROM customers c JOIN orders o ON c.id = o.customer_id;

Using any selection query as table expression

Any selection query (or selection clause) can be used as a tableexpression by enclosing it between parentheses, which forms asubquery.

For example, the following construct is a selection query, but is not a valid table expression:

  1. > SELECT * FROM customers ORDER BY name LIMIT 5

To make it valid as operand to FROM or another table expression, you can enclose it between parentheses as follows:

  1. > SELECT id FROM (SELECT * FROM customers ORDER BY name LIMIT 5);
  1. > SELECT o.id
  2. FROM orders o
  3. JOIN (SELECT * FROM customers ORDER BY name LIMIT 5) AS c
  4. ON o.customer_id = c.id;

Using selection queries with other statements

Selection queries are also valid as operand in contexts that require tabular data.

For example:

StatementExample using SELECTExample using VALUESExample using TABLE
INSERTINSERT INTO foo SELECT FROM barINSERT INTO foo VALUES (1), (2), (3)INSERT INTO foo TABLE bar
UPSERTUPSERT INTO foo SELECT FROM barUPSERT INTO foo VALUES (1), (2), (3)UPSERT INTO foo TABLE bar
CREATE TABLE ASCREATE TABLE foo AS SELECT FROM bar CREATE TABLE foo AS VALUES (1),(2),(3)CREATE TABLE foo AS TABLE bar
ALTER … SPLIT ATALTER TABLE foo SPLIT AT SELECT FROM bar ALTER TABLE foo SPLIT AT VALUES (1),(2),(3)ALTER TABLE foo SPLIT AT TABLE bar
Subquery in a table expressionSELECT FROM (SELECT FROM bar)SELECT FROM (VALUES (1),(2),(3))SELECT FROM (TABLE bar)
Subquery in a scalar expressionSELECT FROM foo WHERE x IN (SELECT FROM bar)SELECT FROM foo WHERE x IN (VALUES (1),(2),(3))SELECT FROM foo WHERE x IN (TABLE bar)

See also

Was this page helpful?
YesNo