SELECT clauses: they can group one or more selection clauses with set operations and can request a specific ordering or row limit.
Selection queries can occur:
- At the top level of a query, like other SQL statements
- Between parentheses as a subquery
- As operand to other statements that take tabular data as input (e.g.,
INSERT,UPSERT,CREATE TABLE AS, orALTER ... SPLIT AT)
Syntax
Parameters
See Common Table Expressions.
A valid selection clause, either simple or using set operations.
An optional
ORDER BY clause for ordering query results.An optional
LIMIT clause for limiting the number of results.An optional
OFFSET clause for skipping rows.The
FOR UPDATE and FOR SHARE clauses are used to lock SELECT statements.Selection clauses
A selection clause defines tabular data. There are four specific syntax forms:SELECT- Load or compute tabular data from various sources (most common)VALUES- List tabular data by the clientTABLE- Load tabular data from the database- Set operations - Combine tabular data from two or more selection clauses
VALUES clause
AVALUES clause defines tabular data by the expressions listed within parentheses. Each parenthesis group defines a single row in the resulting table.
TABLE clause
ATABLE clause reads tabular data from a specified table. The columns of the resulting table data are named after the schema of the table.
TABLE x is equivalent to SELECT * FROM x.
employee into a new table.
SELECT clause
TheSELECT clause is the most common selection clause. It can:
- Retrieve specific columns:
SELECT name, age FROM users - Use
*to select all columns:SELECT * FROM users - Apply filtering with
WHERE:SELECT * FROM users WHERE age > 18 - Perform joins:
SELECT * FROM users JOIN orders ON users.id = orders.user_id - Aggregate data:
SELECT COUNT(*), city FROM users GROUP BY city
Set operations
Set operations combine data from two selection clauses.UNION: Combine two queries
UNION combines the results of two queries into one result.
ALL:
INTERSECT: Retrieve intersection of two queries
INTERSECT selects only values that are present in both query operands.
EXCEPT: Exclude one query’s results from another
EXCEPT selects values that are present in the first query operand but not the second.
Order results
Order by one column
Order by multiple columns
Columns are sorted in the order you list them:Limit row count
You can reduce the number of results withLIMIT:
Row-level locking for concurrency control
SELECT FOR UPDATE locks the rows returned by a selection query, preventing concurrent updates.
See also
- Simple SELECT Clause
- SELECT FOR UPDATE
- Table Expressions
- ORDER BY
- LIMIT and OFFSET