Back to course home page
SQL SELECT Statement
The general form of a SQL SELECT statement is as follows:
] [, item
] , ...]
[ into table
] [, table
] , ...]
[ where predicate
[ group by column
[ having predicate
[ order by column
- Keywords are shown in bold face. These must be typed as
shown, but they may be in upper or lower case.
- Words shown in italics take on different values
depending on the database scheme and the desired query.
- Elements [in brackets] are optional. An ellipsis (...)
indicates any number of repetitions of the preceding optional
element. Options listed in a vertical stack are mutually exclusive.
- The query may span multiple lines, and must be terminated
by a semicolon in standard SQL92.
(PostgreSQL allows \g in place of the semicolon.)
- In the select clause, an item can be the name of a
table column or an expression involving various columns as well as
constants. The alias is a name which will appear at the head
of the column where the item is listed in the table produced in the
query. These aliases may not be used in the predicate of a
where or having clause, but may be used in an order
The keyword as is optional in SQL92 but
required before a column alias by PostgreSQL.
The qualifier all specifies that duplicate rows, if any,
should be retained in the result. This is the default. Use
distinct to require duplicates to be eliminated. Standard SQL92
allows unique as a synonym for distinct, but PostgreSQL does not.
- The into clause creates a new table to receive the
result of the query. The scheme of this table is defined by the
items in the select clause.
- The from clause specifies tables to be searched for the
query. If more than one table is listed, the Cartesian product is
implied. An alias renames a table, usually for purposes of
distinguishing different roles when the same table appears twice.
These aliases may be used in the predicate of the where
- The predicate of the where clause is any boolean
expression involving columns of the tables as well as constants.
Only rows satisfying the predicate will appear in the result.
- The group by clause is used when the select clause
contains aggregate operators, to apply the operators to groups of
rows having common values of the listed columns. The having
subclause limits the results to groups satisfying its predicate.
This predicate can only involve the grouping columns and
aggregate operations applied to the other columns.
- The order by clause specifies the sorting of the results
on the basis of the listed columns. The default order is asc
(ascending). Use desc for descending order.