Basic Query Structure
A typical SQL query has the following form.
SELECT A_1, ... , A_n
FROM r_1, ... , r_m
WHERE pA_i: Attributesr_i: Relationsp: Predicate
The result of an SQL query is a relation.
SELECT Clause
-
The
SELECTclause lists the attributes desired in the result of a query.It corresponds to the projection operation of the relational algebra. Note that SQL names are case insensitive.
-
The
DISTINCTkeyword inserted afterSELECTeliminates all duplicates. -
The
ALLkeyword, on the other hand, explicitly specifies that duplicates should not be removed, although it is the default ofSELECTclause. -
A
*in theSELECTclause denotes all attributes. -
An attribute can be a literal without
FROMclause.The result is a table with one column and a single row with the literal value.
-
An attribute can be a literal with
FROMclause.The result is a table with one column and rows (number equal to the number of rows on the table), each row with the literal value.
-
SELECTclause can contain arithmetic expressions (+,-,*,/) operating on constants or attributes of tuples.
FROM Clause
- The
FROMclause lists the relations involved in the query.
It corresponds to the Cartesian product of the relational algebra.
WHERE Clause
-
The
WHEREclause specifies conditions that the resulting relation must satisfy.It corresponds to the selection operation of the relational algebra.
-
SQL allows the use of the logical connectives
AND,OR, andNOT. -
The operands of the logical connectives can be expressions involving the comparison operators,
<,<=,>,>=,=, and<>.
Comparisons can be applied to results of arithmetic expressions.