A SELECT statement in SQL returns a result set of records from one or more tables.
It is used to retrieve zero or more rows from one or more tables in a database. In most applications, SELECT
is the most commonly used Data Manipulation Language (DML) command. In specifying a SELECT
query, the user specifies a description of the desired result set, but they do not specify what physical operations must be executed to produce that result set. Translating the query into an optimal "query plan" is left to the database system, more specifically to the query optimiser.
Commonly available keywords related to SELECT include:
WHERE
– used to identify which rows to be retrieved, or applied to GROUP BY.
GROUP BY
– used to combine rows with related values into elements of a smaller set of rows.
HAVING
– used to identify which rows, following a GROUP BY, are to be retrieved.
ORDER BY
– used to identify which columns are used to sort the resulting data.
Examples
Table "T"
|
Query
|
Result
|
|
SELECT * FROM T;
|
|
|
SELECT C1 FROM T;
|
|
|
SELECT * FROM T WHERE C1 = 1;
|
|
|
SELECT * FROM T ORDER BY C1 DESC;
|
|
Given a table T, the query SELECT * FROM T;
will result in all the elements of all the rows of the table being shown.
With the same table, the query SELECT C1 FROM T;
will result in the elements from the column C1 of all the rows of the table being shown — in Relational algebra terms, a projection will be performed.
With the same table, the query SELECT * FROM T WHERE C1 = 1;
will result in all the elements of all the rows where the value of column C1 is '1' being shown — in Relational algebra terms, a selection will be performed, because of the WHERE keyword.
The last query SELECT * FROM T ORDER BY C1 DESC;
will output the same rows as the first query, however the results will be in reverse sort order (Z-A) because of the ORDER BY keyword using C1 as a sorting point. This query doesn't have a WHERE keyword, so anything and everything will be returned. Multiple ORDER BY items can be specified (seperated by comma [eg. ORDER BY C1 ASC, C2 DESC]) to further refine sorting.
See also