Retrieving data (simple select statement)

Here is the generic SELECT statement, as it is defined by the SQL99 standard, for selecting data from a single table.

SELECT [DISTINCT] [<qualifier>.]<column_name> |
                  * |
                  <expression>
                   [AS <column_alias>],...
FROM  <table_or_view_name> |
      <inline_view>
       [[AS] <table_alias>]
[WHERE <predicate>]
[GROUP BY [<qualifier>.]<column_name>,...
 [HAVING <predicate>]
]
[ORDER_BY <column_name> |
          <column_number>
           [ASC | DESC],...
];

SELECT Clause: What Do We Select?

In the relational databases the SELECT statement selects values in the columns, literal values, or expressions. The returned values themselves could be of any valid data types. These values can be displayed in the client application, or written into a file, used in the intermediate calculations, or entered into database tables.

Single-column select

Multi-column select

Selecting all columns

Selecting distinct values

Using literals, functions, and calculated columns

Using subqueries in a SELECT clause

FROM Clause: Select from What?

The database objects you should be able to select from are tables and views. These come in many flavors — temporary tables, inline views, materialized views, to name just a few — but the truth is that there is nothing else in the RDBMS world to select from.

Using aliases in a FROM clause

Using subqueries in a FROM clause (inline views)

WHERE Clause: Setting Horizontal Limits

The SQL WHERE clause allows you to limit the number of rows in result sets returned by a query through specifying some condition or set of conditions. The search criteria specified in the WHERE clause evaluate to TRUE or FALSE, and all the rules of Boolean algebra are fully applicable there.

Using comparison operators

Using compound operators: AND, OR

Using the BETWEEN operator

Using the IN operator

Using the IS NULL operator

Using subqueries in a WHERE clause

GROUP BY and HAVING Clauses: Summarizing Results

Grouping records in the result set based on some criteria could provide a valuable insight into data that has accumulated in the table.

The HAVING clause used exclusively with the GROUP BY clause provides a means of additional selectivity.

ORDER BY Clause: Sorting Query Output

The query returns results matching the criteria unsorted — i.e., in the order they've been found in the table. To produce sorted output — alphabetically or numerically — you would use an ORDER BY clause.

Last updated