FROM
clause derives a table from one or more tables in a comma-separated table reference list.
Here is the basic syntax of the FROM
clause:
table_reference
can be a table name, a derived table such as a subquery, a JOIN
construct, or complex combinations.
If multiple sources are specified, the result is all the sources’ Cartesian product (i.e., cross join). The result of the FROM
list is an intermediate virtual table that can then be subject to transformations by the WHERE
, GROUP BY
, and HAVING
clauses and is finally the result of the overall table expression.
Joined tables
A joined table is a table derived from two other (real or derived) tables according to the rules of the particular join type. Inner, outer, and cross-joins are available. Syntax:Subqueries
Subqueries specifying a derived table must be enclosed in parentheses and must be assigned a table alias name. Syntax:FROM table1 AS alias_name
.
Table functions
Table functions produce a set of rows made up of either base data types (scalar types) or composite data types (table rows). They are used like a table, view, or subquery in theFROM
clause of a query. Columns returned by table functions can be included in SELECT
, JOIN
, or WHERE
clauses in the same manner as table columns, view, or subquery columns.
LATERAL
subqueries
Subqueries appearing in FROM
can be preceded by the keyword LATERAL
. This allows them to reference columns provided by preceding FROM
items. Without LATERAL
, each subquery is evaluated independently and so cannot cross-reference any other FROM
item.
To create a LATERAL
subquery, use the LATERAL
keyword directly before the inner subquery’s SELECT
statement.
The following query includes two LATERAL
subqueries. The first LATERAL
subquery calculates the maximum sale amount and caches the result in a derived table max_sale
. The second LATERAL
subquery finds the customer name based on the maximum sale amount from the derived table, and stores the result in another derived table max_sale_customer
.