4 SQL+Basics
4 SQL+Basics
1
© Pearson Education Limited 1995, 2005
2
© Pearson Education Limited 1995, 2005
1
Example 5.1 All Columns, All Rows
3
© Pearson Education Limited 1995, 2005
4
© Pearson Education Limited 1995, 2005
2
Example 5.2 Specific Columns, All Rows
5
© Pearson Education Limited 1995, 2005
SELECT propertyNo
FROM Viewing;
6
© Pearson Education Limited 1995, 2005
3
Example 5.3 Use of DISTINCT
Use DISTINCT to eliminate duplicates:
SELECT DISTINCT propertyNo
FROM Viewing;
7
© Pearson Education Limited 1995, 2005
4
Example 5.4 Calculated Fields
To name column, use AS clause:
SELECT staffNo, fName, lName, salary/12
AS monthlySalary
FROM Staff;
9
© Pearson Education Limited 1995, 2005
10
© Pearson Education Limited 1995, 2005
5
Example 5.6 Compound Comparison Search
Condition
List addresses of all branch offices in London or
Glasgow.
SELECT *
FROM Branch
WHERE city = ‘London’ OR city = ‘Glasgow’;
11
© Pearson Education Limited 1995, 2005
Subqueries
Some SQL statements can have a SELECT
embedded within them.
12
© Pearson Education Limited 1995, 2005
6
Example 5.19 Subquery with Equality
List staff who work in branch at ‘163 Main St’.
13
© Pearson Education Limited 1995, 2005
14
© Pearson Education Limited 1995, 2005
7
Example 5.19 Subquery with Equality
15
© Pearson Education Limited 1995, 2005
16
© Pearson Education Limited 1995, 2005
8
Example 5.20 Subquery with Aggregate
Cannot write ‘WHERE salary > AVG(salary)’
Instead, use subquery to find average salary
(17000), and then use outer SELECT to find those
staff with salary greater than this:
17
© Pearson Education Limited 1995, 2005
18
© Pearson Education Limited 1995, 2005
9
Multi-Table Queries
Can use subqueries provided result columns come
from same table.
If
result columns come from more than one table
must use a join.
Toperform join, include more than one table in
FROM clause.
Usecomma as separator and typically include
WHERE clause to specify join column(s).
19
© Pearson Education Limited 1995, 2005
Multi-Table Queries
Also
possible to use an alias for a table named in
FROM clause.
20
© Pearson Education Limited 1995, 2005
10
Example 5.24 Simple Join
List names of all clients who have viewed a
property along with any comment supplied.
21
© Pearson Education Limited 1995, 2005
22
© Pearson Education Limited 1995, 2005
11