focus on the abstract structure and not on specific examples. The way we write
SQL constructs must be directed only by the logic of the query and not by the
content of a particular database instance. Just because the query generated the
right answer for a particular instance of the database does not mean that it is
correct.
The main retrieval construction is the select phrase. Consider a query that
we solved previously using relational algebra. Recall that in Example 4.1.25 we
found the names of all instructors who have taught any student who lives in
Brookline. The solution involved using product, selection, and projection:
T1 := (STUDENTS × GRADES × INSTRUCTORS)
T2 := T1 where STUDENTS.stno = GRADES.stno and
GRADES.empno = INSTRUCTORS.empno and
STUDENTS.city = ’Brookline’
ANS := T2[INSTRUCTORS.name].
In SQL the same problem can be resolved using a single select phrase as in:
select INSTRUCTORS.name from STUDENTS, GRADES, INSTRUCTORS
where STUDENTS.stno = GRADES.stno and
GRADES.empno = INSTRUCTORS.empno and
STUDENTS.city = ’Brookline’;
We can conceptualize the execution of this typical select using the opera-
tions of relational algebra as follows:
1. The execution begins by performing the product of the tables listed after
the reserved word from. In our case, this involves computing the product
STUDENTS × GRADES × INSTRUCTORS
2. The selection specified after the reserved word where is executed next,
if the where part is present (we shall see that this may or may not be
present in a select.) In our case, this amounts to retaining that part of
the table product that satisfies the condition:
STUDENTS.stno = GRADES.stno and GRADES.empno = INSTRUCTORS.empno
and STUDENTS.city = ’Brookline’
3. Finally, the result of the second phase is projected on the attributes
listed between select and from, that is, in our case, on the attribute
INSTRUCTORS.name.
We use a string constant (also known as a literal ) in the above select, namely
’Brookline’. String constant must begin and end with a single quote.
SQL is not case-sensitive. This means that you may or may not use capital
letters in any place in an SQL construction (except for string comparisons)
without any effect on the value returned by the query.
As we mentioned above, the where part of a select (also known as the where
clause) is optional. This allows us to compute table projections in SQL as we
show next.