You are on page 1of 1

70 Chapter 3: Selecting

3.2 Logical Execution of a SELECT


A SQL select consists of a query expression with some optional clauses: WITH,
ORDER BY, and FOR. The simplest query expression is a single query specifi-
cation; the simplest query specification is defined as the SELECT keyword
followed by a select list; and the simplest select list is a single literal like 1.
That means the simplest SQL select is SELECT 1, which returns a single
row consisting of a single column. Thats one extreme; at the other end of the
spectrum are giant selects spanning hundreds of lines of code, involving dozens
of tables in complex relationships, and returning thousands of rows.
<select> ::= [ <with_clause> ] -- WITH...
<query_expression> -- at least one SELECT...
[ <order_by_clause> ] -- ORDER BY...
[ <for_clause> ] -- FOR...
<query_expression> ::= <query_expression> <query_operator> <query_expression>
| <subquery>
| <query_specification>
<query_operator> ::= EXCEPT [ DISTINCT | ALL ]
| INTERSECT [ DISTINCT | ALL ]
| UNION [ DISTINCT | ALL ]
<subquery> ::= "(" <query_expression>
[ <order_by_clause> ]
[ <for_xml_clause> ] ")"
<query_specification> ::= SELECT
[ DISTINCT ]
[ <row_range> ]
<select_list>
[ <select_into> ]
[ <from_clause> ] -- default is FROM SYS.DUMMY
[ <where_clause> ]
[ <group_by_clause> ]
[ <having_clause> ]
<for_clause> ::= <for_intent_clause>
| <for_xml_clause>
<for_intent_clause> ::= FOR READ ONLY
| FOR UPDATE
| FOR UPDATE BY <concurrency_setting>
<concurrency_setting> ::= VALUES
| TIMESTAMP
| LOCK
<for_xml_clause> ::= FOR XML RAW [ "," ELEMENTS ] [ "," ROOT ]
| FOR XML AUTO [ "," ELEMENTS ] [ "," ROOT ]
| FOR XML EXPLICIT [ "," ELEMENTS ] [ "," ROOT ]

Note: This section begins a long discussion of the <query_specification>


shown above. Other clauses are described much later, or not at all. In particular,
the <with_clause> is discussed in Section 3.24, the <order_by_clause> is dis-
cussed in Section 3.17, and the EXCEPT, INTERSECT, and UNION operators are
discussed in Section 3.22. For more information about the <for_intent_clause>
and <for_xml_clause>, see the SQL Anywhere Help.

The SQL select is the most important, most powerful, and most difficult con-
struction in all of SQL. One of the main reasons for the difficulty is the fact that
the order in which the various clauses are coded bears little relationship to what
they actually do or the way the SQL select is executed. This section addresses
the question, What does the SQL select do? The answer to the question, How