SQIT3043 Chapter 8 - SQL (Latest)
SQIT3043 Chapter 8 - SQL (Latest)
1
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
8.2
WRITING SQL COMMANDS
An SQL statement consists of reserved words and user-defined words.
Reserved Words
Reserved words are fixed part of the
SQL language and have a fixed
meaning
Examples: CREATE TABLE, SELECT,
INSERT etc.
Must be spelled exactly as required
and cannot be split across lines.
User-defined words
Made up by the user (according
to certain syntax rules)
Represent the names of various
database objects such as tables,
columns, views, indexes and so on.
2
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
Client
PrivateOwner
street
city
postcode
telNo1
telNo2
telNo3
mngrStaffNo
B002
56 Clover Dr
London
NW106EU
01112334
01233242
04323212
SA9
B003
163 Main St
Glasgow
G119QX
05453432
05434545
00764432
SL21
B004
32 Manse Rd
Bristol
BS991NZ
05646373
07854554
02122424
SM99
B005
22 Deer St
London
SW14Eh
05436365
02434432
0234335
ST02
B007
16 Agyril
Aberdeen
Ab23SU
00536353
00534322
00423211
SK12
branchNo
Staff
staffNo
staffName
position
salary
supervisorStaffNo
SA9
John White
Manager
30000
SS12
B005
SG14
Ann Beech
Assistant
12000
SG37
B003
18000
SA9
B003
9000
SG37
B007
B003
B005
SG37
SG5
David Ford
Supervisor
Mary Howe
Assistant
SL21
Susan Brand
Manager
24000
SS13
SL41
Julie Lee
Assistant
9000
SG37
PropertyForRent
property
No
propertyStreet
PA14
16 Holhead
PL49
6 Argyll St
PG4
property
City
property
Postcode
property
Type
rooms
rent
deposit
owner
No
Aberdeen
AB75SU
London
NW2
6 Lawrence St
Glasgow
PG36
2 Manor Rd
PG21
18 Dale Rd
PG16
5 Novar Rd
staff
No
branch
No
House
650
1300
CO46
SA9
B007
Flat
400
800
CO87
SL41
B005
G119QX
Flat
350
700
CO40
SG5
B003
Glasgow
G324QX
Flat
375
750
CO93
SG37
B003
Glasgow
G12
House
600
1200
CO87
SG37
B003
Glasgow
G129AX
Flat
450
900
CO93
SG14
B003
3
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
clientName
telNo
prefType
maxRent
CR56
Aline Steward
0141-848-182
Flat
$350.00
CR62
Marry Tregear
021224-19672
Flat
$600.00
CR74
Mike Ritchie
01475-392178
House
$750.00
CR76
John Kay
0207-774-563
Flat
$425.00
PrivateOwner
ownerNo
ownerName
ownerAddress
ownerTelNo
CR56
Joe Keogh
01224861212
CR62
Carol Farrel
01413577419
CR74
Tina Murphy
01419431728
CR76
Tony Shaw
01412257025
4
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
8.4
DATA DEFINITION
Data Definition Language (DDL), is the part of SQL that allows a
database user to create and restructure database objects, such as
the creation or the deletion of a table.
Two of the most common SQL DDL statements are:
CREATE DATABASE to create a database
CREATE TABLE to create a table
SQIT3043
SQIT3043
d) FOREIGN KEY
- A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
- Ensure the referential integrity of the data in one table to match values in
another table
- The FOREIGN KEY constraint is used to prevent actions that would destroy
links between tables.
- The FOREIGN KEY constraint also prevents invalid data from being
inserted into the foreign key column, because it has to be one of the
values contained in the table it points to.
e) CHECK
- Ensures that the value in a column meets a specific condition
- The CHECK constraint is used to limit the value range that can be placed
in a column.
- If you define a CHECK constraint on a single column it allows only certain
values for this column.
- If you define a CHECK constraint on a table it can limit the values in
certain columns based on values in other columns in the row.
f) DEFAULT
- Specifies a default value when specified none for this column
- The DEFAULT constraint is used to insert a default value into a column.
- The default value will be added to all new records, if no other value is
specified.
Exercise: Write the SQL statements to create all the remaining tables in
DreamHome database.
7
SQIT3043
8
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
Example:
INSERT INTO PropertyForRent (propertyNo, propertyStreet, propertyCity, propertyPostcode,
propertyType, rooms, rent, deposit, ownerNo, staffNo, bName, branchNo)
VALUES (PA14, 16 Holhead, Aberdeen. AB75SU, House, 6, 650.00, 1300, CO46, SA9, ,
B007);
The value in column rooms is an integer literal and the value in column rent and
deposit are decimal number literal; they are not enclosed in single quotes. All
other columns are character strings and are enclosed in single quotes ( ).
8.5.1 Simple Queries (SELECT)
The purpose of SELECT statements is to retrieve and display data from one
or more database tables. SELECT is the most frequently used SQL command
and has the following form:
SELECT [DISTINCT | ALL] {*| [columnExpression [AS newname]] [,]}
FROM TableName [alias] [,]
[WHERE condition]
[GROUP BY columnList] [HAVING condition]
[ORDER BY columnList]
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
Description
specifies the table or tables to be used
filter the rows subject to some condition
Forms groups of rows with the same column value
Filters the groups subject to some condition
specifies which columns are to appear in the output
Specifies the order of the output.
9
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
Because many SQL retrievals require all columns of a table, there is a quick way
of expressing all column in SQL , using an asterisk (*) in place of the column
names, The following statement is an equivalent and shorter way of expressing
this query:
SELECT *
FROM Staff;
staffName
John White
position
Manager
salary
supervisorStaffNo
30000
SS12
B005
B003
branchNo
SG14
Ann Beech
Assistant
12000
SG37
SG37
David Ford
Supervisor
18000
SA9
B003
SG5
Mary Howe
Assistant
9000
SG37
B007
SL21
Susan Brand
Manager
24000
SS13
B003
SL41
Julie Lee
Assistant
9000
SG37
B005
10
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
In this example a new table is created from Staff containing only the designated
columns stafNo, fName, lName, and salary. The results are shown in Table 8.2. Note that,
unless specified, the rows in the result table may not be sorted. Microsoft Office
Access would sort this result table based on primary key staffNo. The explanation
of how to sort the rows of a result table will be discussed in the next section.
Table 8.2 Result table for Example 8.2
staffNo
staffName
salary
SA9
John White
30000
SG14
Ann Beech
12000
SG37
David Ford
18000
SG5
Mary Howe
9000
SL21
Susan Brand
SL41
Julie Lee
24000
9000
The result table is shown in Table 8.3(a). Notice that there are several duplicates,
SELECT does not eliminate duplicates when it projects over one or more
column.
11
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
To eliminate the duplicates, we use the DISTINCT keyword. Rewriting the query
as:
SELECT DISTINCT supervisorStaffNo
FROM Staff;
We get the result table shown in Table 8.3(b) with the duplicates eliminated.
Table 8.3(b) Result table for Example 8.3(a) with duplicates eliminated
supervisorStaffNo
SS12
SG37
SA9
SS13
This query is almost identical to Example 8.2, with the exception that monthly
salaries are required. In this case, the desired result can be obtained by simply
dividing the salary by 12, giving the result table shown in Table 8.4.
Table 8.4 Result table for Example 8.4
staffNo
staffName
Col3
SA9
John White
2500
SG14
Ann Beech
1000
SG37
David Ford
1500
SG5
Mary Howe
750
SL21
Susan Brand
SL41
Julie Lee
2000
750
SQIT3043
The third column of this result table has been output col3. Normally, a column in
the result table takes its name from corresponding column in database table
from which it has been retrieved; However, in this case, SQL does not know how
to label the column. Some SQL syntax gives the column name corresponding to
its position in the table (for example col3); some may leave the column name
blank or use the expression entered in the SELECT list.
The ISO standard allows the column to be named using an AS clause, In the
previous example, we could have written:
SELECT stafNo, staffName, salary/12 AS monthlySalary
FROM Staff;
In this case, the column heading of the result table would be monthlySalary rather
than col3
13
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
Here, the table is Staff and the predicate is salary > 10000. The selection creates a
new table containing only those Staff rows with a salary greater than 10000. The
result of this operation is shown in Table 8.5.
Table 8.5 Result table for Example 8.5
staffNo
staffName
position
salary
SA9
John White
Manager
30000
SG14
Ann Beech
Assistant
12000
SG37
David Ford
Supervisor
18000
SL21
Susan Brand
Manager
24000
Description
Equal
is not equal to
is less than
is greater than
Operator
!=
<=
>=
Description
is not equal to (allowed in some dialects)
is less than or equal to
is greater than or equal to
14
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
More complex predicates can be generated using the logical operators AND,
OR and NOT, with parentheses (if needed or desired) to show the order of the
evaluation. The rules for evaluating a conditional expression are;
An expression is evaluated left to right;
Subexpressions in brackets are evaluated first;
NOTs are evaluated before ANDs and ORs;
ANDs are evaluated before ORs.
The use of parentheses is always recommended, in order to remove any possible
ambiguities.
EXAMPLE 8.6: Compound comparison search condition
List the address of all offices in London or Glasgow.
SELECT *
FROM Branch
WHERE city = London OR city = Glasgow;
In this example the logical operator OR is used in the WHERE clause to find the
branches in London (city = London) or in Glasgow (city = Glasgow). The result table is
shown in Table 8.6.
Table 7.6 Result table for Example 7.6
branchNo
street
city
postcode
B002
56 Clover Dr
London
NW106EU
B003
163 Main St
Glasgow
G119QX
B005
22 Deer St
London
SW14Eh
The BETWEEN test includes the endpoints of the range, so any members of staff
with a salary of 20000 or 30000 would be included in the result. The result table is
shown in Table 8.7.
Table 8.7 Result table for Example 8.7
staffNo
staffName
position
salary
SA9
John White
Manager
30000
SL21
Susan Brand
Manager
24000
There is also a negated version of the range test (NOT BETWEEN) that checks
for value outside the range. The BETWEEN test does not add much to the
expressive power of SQL, because it can be expressed equally well using two
15
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
However, the BETWEEN test is a simpler way to express a search condition when
considering a range of values.
EXAMPLE 8.8: Set membership search condition (IN / NOTIN)
List all manager and supervisors.
SELECT staffNo, staffName, position, salary
FROM Staff
WHERE position IN (Manager, Supervisor);
The set membership test (IN) tests whether a data value matches one of a list of
values, in this case either Manager or Supervisor. The result table is shown in Table
8.8.
Table 8.8 Result table for Example 8.8
staffNo
staffName
position
SA9
John White
Manager
SG37
David Ford
Supervisor
SL21
Susan Brand
Manager
There is a negated version (NOT IN) that can be used to check for data values
that do not lie in a specific of values. Like BETWEEN, the IN test does not add
much to the expressive power of SQL. We could have expresses the previous
query as:
SELECT staffNo, staffName, position, salary
FROM Staff
WHERE position =Manager OR position = Supervisor;
However, the IN test provides a more efficient way of expressing the search
condition, particularly if the set contains many values.
16
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
Using the pattern-matching search condition of SQL, we can find all owners with
the string Glasgow in their address using the following query, producing the result
table shown in Table 8.9.
SELECT ownerNo, ownerNAme, ownerAddress, ownerTelNo
FROM PrivateOwner
WHERE address LIKE %Glasgow%;
Note that some RDBMSs, such as a Microsoft Office Access, use the wildcard
characters * and ? instead of % and _.
Table 8.9 Result table for Example 8.9
ownerNo
ownerName
ownerAddress
Owner
TelNo
CR62
Carol Farrel
01413577419
CR74
Tina Murphy
01419431728
CR76
Tony Shaw
01412257025
17
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
clientNo
propertyNo
CR56
CR76
CR56
CR62
CR56
PA14
PG4
PG4
PA14
PG36
viewDate
24-May-08
20-Apr-08
26-May-08
14-Mat-08
28-Apr-08
comment
too small
too remote
no dining room
We can see that there are two viewing for property PG4: one with a comment,
the other without a comment. In this simple example, you may think that the
latter row could be accessed by using one of the search conditions:
(propertyNo = PG4 AND comment = )
or
(propertyNo = PG4 AND comment <> too remote)
However either of these would work. A null comment is considered to have an
unknown value, so we cannot test whether it is equal or not equal to another
string. If we tried to execute the SELECT statement using either of these
compound conditions, we would get an empty result table. Instead, we have to
test for null explicitly using the special keyword IS NULL.
SELECT clientNo, viewDate
FROM Viewing
WHERE propertyNo =PG4 AND comment IS NULL;
The result table is shown in Table 8.10. The negated version (IS NOT NULL) can
be used to test for values that are not null.
Table 8.10 Result table for Example 8.10
clientNo
CR56
viewDate
26-May- 08
18
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
INSERT
UPDATE
DELETE
As we are inserting data into each column in the order the table was created,
there is no need to specify a column list. Note that character literals such as
Alan must be enclosed in single quotes.
19
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
As we are inserting data into only certain columns, we must specify the names
of the columns that we are inserting data into. The order for the column names is
not significant, but it is normal to specify them in the order they appear in the
table. We could also express the INSERT statements as:
INSERT INTO Staff
can be the name of a base table or an update view. The SET clause
specifies the names of one or more columns that are to be updated. The
WHERE clause is optional; if omitted, the named columns are updated for all
rows in the table. If a WHERE clause is specified; only those rows that satisfy the
searchCondition are updated. The new dataValue(s) must be compatible with the data
type(s) for the corresponding column(s).
TableName
As the update applies to all rows in the Staff table, the WHERE clause is omitted
20
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
The WHERE clause finds the row that contain data for Managers and the
update salary = salary *1.05 is applied only to these particular rows.
EXAMPLE 8.15: UPDATE multiple columns
Promote David Ford (staffNo = SG14) to Manager and change his salary to
18000.
UPDATE Staff
SET position = Manager, salary = 18000
WHERE staffNo = SG14;
21
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
As with the INSERT and UPDATE statements, TableName can be the name of a
base table or an update view. The searchCondition is optional; if omitted, all rows
are deleted from the table. This does not delete the table itself-to delete the
table contents and the table definition, the DROP TABLE statements must be
used instead. If a searchCondition is specified, only those rows that satisfy the
condition are deleted.
EXAMPLE 8.16: DELETE specific row
Delete viewing that relate to property PG4
DELETE FROM Viewing
WHERE propertyNo = PG4;
The WHERE clause finds the row for property PG4 and the delete operation is
applied only to the particular rows.
No WHERE clause has been specified, so delete operation applies to all rows in
the table. This query removes all rows from the table, leaving only the table
definition, so that we are still able to insert data into the table a later stage.
22
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
staffName
John White
Susan Brand
David Ford
Ann Beech
Mary Howe
Julie Lee
salary
30000
24000
18000
12000
9000
9000
If the values of the major sort key are unique, there is no need for additional keys
to control the sort.
However, if the values of the major sort key are not unique, there may be
multiple rows in the result table with the same value for the major sort key.
23
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
In this case, it may be desirable to order rows with the same value for the major
sort key by some additional sort key. If a second element appears in the ORDER
BY clause, it is called a minor sort key:
SELECT propertyNo, propertyType, rooms, rent
FROM PropertyForRent
ORDER BY propertyType, rent DESC;
propertyNo
PG16
PL49
PG36
PG4
PA14
PG21
propertyType
Flat
Flat
Flat
Flat
House
House
rooms
4
4
3
3
6
5
rent
450
400
375
350
650
600
Properties
returns the number of values in a specified column
returns the sum of the values in a specified column
returns the average of the values in a specified
column
returns the smallest value in a specified column
returns the largest value in a specified column
These functions operate on a single column of a table and return a single value.
COUNT, MIN, and MAX apply to both numeric and nonnumeric fields, but SUM
and AVG may be used on numeric fields only.
Apart from COUNT(*), each function eliminates nulls first and operates only on
the remaining non-null values. An aggregate function can be used only in the
SELECT list and in the HAVING clause.
If the SELECT list includes an aggregate function and no GROUP BY clause is
being used to group data together, then no item in the SELECT list can include
any reference to a column unless that column is the argument to an aggregate
function.
24
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
25
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
mycount
3
1
2
mysum
54000
9000
39000
SQIT3043
clientName
Aline Steward
John Kay
Aline Steward
Marry Tregear
Aline Steward
propertyNo
PA14
PG4
PG4
PA14
PG36
comments
too small
too remote
no dining room
The SQL standard provides the following alternative way to specify this join:
SELECT clientNo, clientName, propertyNo, comments
FROM Client JOIN Viewing
ON clientNo.client = clientNo.viewing;
27
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
When you want to review, add, change, or delete data from your database
consider using a query.
Using a query, you can answer very specific questions about your data that
would be difficult to answer by looking at table data directly. You can use
queries to filter your data, to perform calculations with your data, and to
summarize your data. You can also use queries to automate many data
management tasks and to review changes in your data before you commit
to those changes.
NOTE: Aggregate query functions, such as Sum or Count, are not available in Web queries.
When you run a select query, MS Access displays the results in a datasheet.
The result is called a record set, and you can work with it in the same way
that you work with a datasheet. For example, you can add or change data,
and MS Access will write your changes to the tables that serve as the record
sources for your query.
A query is a request for data results, for action on data, or for both. You can
use a query to answer a simple question, to perform calculations, to
combine data from different tables, or even to add, change, or delete table
data. Queries that you use to retrieve data from a table or to make
calculations are called select queries. Queries that add, change, or delete
data are called action queries.
You can also use a query to supply data for a form or report. In a welldesigned database, the data that you want to present by using a form or
report is often located in several different tables. By using a query, you can
assemble the data that you want to use before you design your form or
report.
For this section, we are going to use the DreamHome Database that you
have created in class as examples.
SQIT3043
Suppose that you want to review a list of properties and their monthly rents. You
can create a query that returns property and rental information by using the
following procedure:
i.
ii.
iii.
ii.
iii.
In the Show Table dialog box, on the Tables tab, doubleclick PrivateOwner and PropertyForRent.
iv.
Note the line, called a join, that connects the ownerNo field in the PrivateOwner
table and the ownerNo field in the PropertyForRent table. This line shows the
relationship between the two tables.
v.
SQIT3043
In the query design grid, in the propertyCity column, clear the check box
in the Show row. (Optional)
vii.
Clearing the Show check box prevents the query from displaying the city in its
results, and typing Leeds in the Criteria row of the propertyCity column specifies
that you want to see only records where the value of the propertyCity field is
Leeds. Meanwhile, typing NOT NULL in the Criteria row of the ownerNo column
specifies that you want to see only records where the value of the ownerNo is
supplied (if the value is NULL, it shows that the property is owned by a business
and not a private owners). In this case, the query returns only the private owners
for properties that are located in Leeds.
Note that you do not have to display a field to use it with a criterion.
viii.
The query runs, and then displays a list of private owners for properties that are
located in Leeds.
ix.
In the Query Name box, type Private Owners for Properties by Cities, and
then click OK.
30
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
In the previous example, you created a query that returns private owners for
properties located in Leeds. You can modify the query to prompt you to specify
the city each time that you run the query by using the following procedure:
i.
ii.
iii.
In the Navigation Pane, right-click the query named Private Owners for
Properties by Cities (that you created in the previous section), and then
click Design View on the shortcut menu.
iv.
In the query design grid, in the Criteria row of the propertyCity column,
delete Leeds, and then type [For which city?].
The string [For which city?] is your parameter prompt. The square brackets
indicate that you want the query to ask for input, and the text (in this
case, For which city?) is the question that the parameter prompt displays.
NOTE Neither a period (.) nor an exclamation point (!) can be used as text in a
parameter prompt.
v.
Select the check box in the Show row of the propertyCity column, so that
the query results will display the city.
vi.
The query runs, and then displays orders for private owners in London.
But what if you don't know what values you can specify? To make your
parameter more flexible, you can use wildcard characters as part of the
prompt:
viii.
On the Home tab, in the Views group, click View, and then click Design
View.
ix.
In the query design grid, in the Criteria row of the City column, type Like
[For which city?]&"*".
31
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
In this parameter prompt, the Like keyword, the ampersand (&), and the asterisk
(*) enclosed in quotation marks allow the user to type a combination of
characters, including wildcard characters, to return a variety of results. For
example, if the user types *, the query returns all cities; if the user types L, the
query returns all cities that start with the letter "L;" and if the user types *s*, the
query returns all cities that contain the letter "s."
x.
The query runs, and then displays orders for customers in Leeds and
London.
ii.
In the Query Parameters dialog box, in the Parameter column, type the
prompt for each parameter for which you want to specify the data type.
Make sure that each parameter matches the prompt that you use in
the Criteria row of the query design grid.
iii.
In the Data Type column, select the data type for each parameter.
32
MOHD. NOOR ABDUL HAMID
[email protected]
SQIT3043
For example, in the Dreamhome database, you might want to know the total
amount of deposit have been collected for all the leases. To do this you must
first set a query that list all deposit paid by the clients. The information needed
for this query come from two table which are; Lease and PropertyForRent:
i.
ii.
iii.
In the Show Table dialog box, on the Tables tab, doubleclick Lease and PropertyForRent.
iv.
v.
vi.
In the query design grid, in the depositPaid column, clear the check
box in the Show row and in the criteria type Yes. This is done since the
query is meant to show lease which the deposit has been paid by the
clients and we dont want this field to be shown in the query result.
vii.
viii.
In the Query Name box, type Leases with Paid Deposit, and then
click OK.
ix.
SQIT3043
x.
The query runs, and then displays Leases where the deposit have been
paid by the clients.
Run the Leases with Paid Deposit query, and leave the results open in
Datasheet view.
ii.
iii.
Click the cell in the last row of the datasheet named Total.
Note that an arrow appears in the cell.
iv.
v.
vi.
You can group by field values by using the Totals row in the design grid.
34
SQIT3043
You can add a datasheet Total row to the results of a totals query.
When you use the Totals row in the design grid, you must choose an
aggregate function for each field. If you do not want to perform a
calculation on a field, you can group by the field.
iii.
For example, suppose that you want to send data for private owners for
properties in Leeds to a business partner (let say a property maintenance
company) in Leeds who uses Access to prepare reports. Instead of sending all
your properties and private owners data, you want to restrict the data that you
send to data specific to properties in Leeds.
You can build a select query that contains data about properties in Leeds, and
then use the select query to create the new table by using the following
procedure:
i.
ii.
iii.
iv.
v.
SQIT3043
vi.
vii.
viii.
ix.
x.
In the Query Name box, type Private owners for properties in Leeds, and
then click OK.
xi.
On the Home tab, in the Views group, click View, and then click Design
View.
xii.
On the Design tab, in the Query Type group, click Make Table.
The Make Table dialog box appears.
xiii.
xiv.
xv.
36
MOHD. NOOR ABDUL HAMID
[email protected]