Table Expressions

On this page Carat arrow pointing down
Warning:
CockroachDB v2.0 is no longer supported. For more details, see the Release Support Policy.

Table expressions define a data source in the FROM sub-clause of simple SELECT clauses, or as parameter to TABLE.

SQL Joins are a particular kind of table expression.

Synopsis

Parameters

Parameter Description
table_name A table or view name.
table_alias_name A name to use in an aliased table expression.
name One or more aliases for the column names, to use in an aliased table expression.
scan_parameters Optional syntax to force index selection.
func_application Results from a function.
explainable_stmt Use the result rows of an explainable statement.
select_stmt A selection query to use as subquery.
joined_table A join expression.

Table Expressions Language

The synopsis above really defines a mini-language to construct complex table expressions from simpler parts.

Construct Description Examples
table_name [@ scan_parameters] Access a table or view. accounts, accounts@name_idx
function_name ( exprs ... ) Generate tabular data using a scalar function or table generator function. sin(1.2), generate_series(1,10)
<table expr> [AS] name [( name [, ...] )] Rename a table and optionally columns. accounts a, accounts AS a, accounts AS a(id, b)
<table expr> WITH ORDINALITY Enumerate the result rows. accounts WITH ORDINALITY
<table expr> JOIN <table expr> ON ... Join expression. orders o JOIN customers c ON o.customer_id = c.id
(... subquery ...) A selection query used as subquery. (SELECT * FROM customers c)
[... statement ...] Use the result rows of an explainable statement.

This is a CockroachDB extension.
[SHOW COLUMNS FROM accounts]

The following sections provide details on each of these options.

Table Expressions That Generate Data

The following sections describe primary table expressions that produce data.

Access a Table or View

Table or View Names

Syntax:

identifier
identifier.identifier
identifier.identifier.identifier

A single SQL identifier in a table expression context designates the contents of the table, view, or sequence with that name in the current database, as configured by SET DATABASE.

Changed in v2.0: If the name is composed of two or more identifiers, name resolution rules apply.

For example:

icon/buttons/copy
> SELECT * FROM users; -- uses table `users` in the current database
> SELECT * FROM mydb.users; -- uses table `users` in database `mydb`

Force Index Selection

By using the explicit index annotation, you can override CockroachDB's index selection and use a specific index when reading from a named table.

Note:
Index selection can impact performance, but does not change the result of a query.
icon/buttons/copy
> SHOW INDEXES FROM accounts;
+----------+-------------------+--------+-----+--------+-----------+---------+----------+
|  Table   |       Name        | Unique | Seq | Column | Direction | Storing | Implicit |
+----------+-------------------+--------+-----+--------+-----------+---------+----------+
| accounts | primary           | true   |   1 | id     | ASC       | false   | false    |
| accounts | accounts_name_idx | false  |   1 | name   | ASC       | false   | false    |
| accounts | accounts_name_idx | false  |   2 | id     | ASC       | false   | true     |
+----------+-------------------+--------+-----+--------+-----------+---------+----------+
(3 rows)
icon/buttons/copy
> SELECT name, balance
FROM accounts@accounts_name_idx
WHERE name = 'Edna Barath';
+-------------+---------+
|    name     | balance |
+-------------+---------+
| Edna Barath |     750 |
| Edna Barath |    2200 |
+-------------+---------+

Access a Common Table Expression

A single identifier in a table expression context can refer to a common table expression defined earlier.

For example:

icon/buttons/copy
> WITH a AS (SELECT * FROM users)
  SELECT * FROM a; -- "a" refers to "WITH a AS .."

Results From a Function

A table expression can use the results from a function application as a data source.

Syntax:

name ( arguments... )

The name of a function, followed by an opening parenthesis, followed by zero or more scalar expressions, followed by a closing parenthesis.

The resolution of the function name follows the same rules as the resolution of table names. See Name Resolution for more details.

Scalar Function as Data Source

New in v2.0

When a function returning a single value is used as a table expression, it is interpreted as tabular data with a single column and single row containing the function results.

For example:

icon/buttons/copy
> SELECT * FROM sin(3.2)
+-----------------------+
|          sin          |
+-----------------------+
| -0.058374143427580086 |
+-----------------------+
Note:
CockroachDB only supports this syntax for compatibility with PostgreSQL. The canonical syntax to evaluate scalar functions is as a direct target of SELECT, for example SELECT sin(3.2).

Table Generator Functions

Some functions directly generate tabular data with multiple rows from a single function application. This is also called a "set-returning function".

For example:

icon/buttons/copy
> SELECT * FROM generate_series(1, 3)
+-----------------+
| generate_series |
+-----------------+
|               1 |
|               2 |
|               3 |
+-----------------+
Note:
Currently CockroachDB only supports a small set of generator function compatible with the PostgreSQL set-generating functions of the same name.

Operators That Extend a Table Expression

The following sections describe table expressions that change the metadata around tabular data, or add more data, without modifying the data of the underlying operand.

Aliased Table Expressions

Aliased table expressions rename tables and columns temporarily in the context of the current query.

Syntax:

<table expr> AS <name>
<table expr> AS <name>(<colname>, <colname>, ...)

In the first form, the table expression is equivalent to its left operand with a new name for the entire table, and where columns retain their original name.

In the second form, the columns are also renamed.

For example:

icon/buttons/copy
> SELECT c.x FROM (SELECT COUNT(*) AS x FROM users) AS c;
> SELECT c.x FROM (SELECT COUNT(*) FROM users) AS c(x);

Ordinality Annotation

Syntax:

<table expr> WITH ORDINALITY

Designates a data source equivalent to the table expression operand with an extra "Ordinality" column that enumerates every row in the data source.

For example:

icon/buttons/copy
> SELECT * FROM (VALUES('a'),('b'),('c'));
+---------+
| column1 |
+---------+
| a       |
| b       |
| c       |
+---------+
icon/buttons/copy
> SELECT * FROM (VALUES ('a'), ('b'), ('c')) WITH ORDINALITY;
+---------+------------+
| column1 | ordinality |
+---------+------------+
| a       |          1 |
| b       |          2 |
| c       |          3 |
+---------+------------+
Note:
WITH ORDINALITY necessarily prevents some optimizations of the surrounding query. Use it sparingly if performance is a concern, and always check the output of EXPLAIN in case of doubt.

Join Expressions

Join expressions combine the results of two or more table expressions based on conditions on the values of particular columns.

See Join Expressions for more details.

Using Other Queries as Table Expressions

The following sections describe how to use the results produced by another SQL query or statement as a table expression.

Subqueries as Table Expressions

Any selection query enclosed between parentheses can be used as a table expression, including simple SELECT clauses. This is called a "subquery".

Syntax:

( ... subquery ... )

For example:

icon/buttons/copy
> SELECT c+2                          FROM (SELECT COUNT(*) AS c FROM users);
> SELECT *                            FROM (VALUES(1), (2), (3));
> SELECT firstname || ' ' || lastname FROM (TABLE employees);
Note:
  • See also Subqueries for more details and performance best practices.
  • To use other statements that produce data in a table expression, for example SHOW, use the square bracket notation.

Using the Output of Other Statements

Syntax:

[ <statement> ]

An explainable statement between square brackets in a table expression context designates the output of executing said statement.

Note:
This is a CockroachDB extension. This syntax complements the subquery syntax using parentheses, which is restricted to selection queries. It was introduced to enable use of any explainable statement as subquery, including SHOW and other non-query statements.
For example:
icon/buttons/copy
> SELECT "Field" FROM [SHOW COLUMNS FROM customer];
+---------+
| Field   |
+---------+
| id      |
| name    |
| address |
+---------+

The following statement inserts Albert in the employee table and immediately creates a matching entry in the management table with the auto-generated employee ID, without requiring a round trip with the SQL client:

icon/buttons/copy
> INSERT INTO management(manager, reportee)
    VALUES ((SELECT id FROM employee WHERE name = 'Diana'),
            (SELECT id FROM [INSERT INTO employee(name) VALUES ('Albert') RETURNING id]));

Composability

Table expressions are used in the SELECT and TABLE variants of selection clauses, and thus can appear everywhere where a selection clause is possible. For example:

icon/buttons/copy
> SELECT ... FROM <table expr>, <table expr>, ...
> TABLE <table expr>
> INSERT INTO ... SELECT ... FROM <table expr>, <table expr>, ...
> INSERT INTO ... TABLE <table expr>
> CREATE TABLE ... AS SELECT ... FROM <table expr>, <table expr>, ...
> UPSERT INTO ... SELECT ... FROM <table expr>, <table expr>, ...

For more options to compose query results, see Selection Queries.

See Also


Yes No
On this page

Yes No