Lab2-1 - SQL
Lab2-1 - SQL
1. Construct simple SQL SELECT statements to generate results tables that satisfy given
information requests
2. Construct SQL UPDATE statements to make specified changes to existing records in the
underlying data tables
3. Construct SQL INSERT statements to add new records to the underlying data tables
4. Construct SQL DELETE statements to remove existing records from the underlying data
tables
This is a mandatory tutorial. In order to pass the coursework, you must achieve a score of 75% or
higher on the associated Blackboard quiz (Lab Quiz 2-1).
Preamble
This is the first of a series of tutorials that will give you the opportunity to apply, to concrete
scenarios, what you have learned in the lectures about database (DB) use, analysis and design. This
tutorial will focus on DB interaction, using the ISO standard querying language called SQL
(pronounced either as “S-Q-L” or “See-quel”). Specifically, you will work with the four main data
manipulation language (DML) commands: SELECT, UPDATE, INSERT and DELETE. If you are
attempting this prior to the SQL lecture, please refer to Chapter 3 of the textbook.
Although the format of the underlying database is MS Access 2002, it is beyond the scope of this
module to teach you how to use Access, or any other specific DB application (although feel free to
familiarise yourself with DB applications in your personal study time). Instead, you will interact with
this DB through a simple, custom SQL driven interface called SQL Lab.
There are three exercise sections in this tutorial. The first explains how to install and use the SQL Lab
tool. The second requires you to generate some more complicated SELECT commands. The third
section requires you to modify the contents of the DB.
You should find the SQL tool quite straightforward to use. In the top left of the form is a text box
where you will write your SQL commands. You can begin by copying the examples from the lecture
slides. Most will work straight off; some won’t (these are explained later). You must follow the
standard SQL syntax rules, but the underlying DBMS is not too fussy about how you format a
1
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
command - you can put everything on one line or use separate lines for each part. The syntax rules
were clearly explained in the lecture. However, the tool helps you by providing inline access to
templates for the four basic command structures. Just click on the SELECT, UPDATE, DELETE and
INSERT buttons to view these.
Any successful queries that you enter will result in new information appearing in both the Query
History and results table views. The former view provides a history of your interactions during the
present session, including the query submitted and the number of results or any errors that resulted.
The result table view shows the result of the last valid SELECT query.
During much of this module, we will learning about databases using the case of the StayHome DVD
rental library. We have access to a simple instance of their database model through the
“StayHome2002.mdb” file, an Access 2002 file. If you have copied this file into the same folder as
SQL Lab, this will be accessible as soon as you start the program.
StayHome is a simple database designed to support the business activities of an imaginary DVD
rental library as described in the Business Database Systems text book (Connolly et al., 2008). It
consists of 13 distinct tables. Each table only has a few records, so it is easy for you to keep track of
the contents and any changes you will make. The version you have is very similar to the example
used in the textbook (and lecture), although there are some minor structural and naming differences
in the tables and fields. Appendix A (at the end of this document) shows a diagram of all of the
tables, their fields and their relationships. The little key symbols denote the primary key in each case.
You’ll find it helpful to keep this diagram in view as you proceed with the exercises.
We can see the Staff table on the right. This table comprises six
distinct fields (columns). Notice in the SQL interface, there is a frame
entitled “Example Commands” containing two buttons. To get you
started, these buttons provide you with two ready-made commands
that interact with the Staff table.
2
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
This will retrieve the whole table (all records and fields). The DBMS knows to retrieve all fields
because of the asterisk (*) after SELECT. This is a shorthand equivalent of listing all fields like so:
If you only wanted to see some of the fields, you would simply remove the unwanted field names
from the command. Note the use of square brackets to delimit the ‘position’ field name. Square
brackets are normally used to delimit field names with spaces (a bad idea in itself). In this case, the
word ‘position’ is actually a reserved keyword to the MS Jet DB Engine. Rightly or wrongly the
creator of the DB decided to use the word as an attribute name, but it is useful for highlighting a
mistake that is easy to make as a beginner. Hence, remember that if you believe your command is
correct, but the system returns an error, try using square brackets around your SELECTed attribute
names.
Now click on “Execute SQL command”. You should see the output or result table which looks like
this:
The first row shows the field names, separated by vertical lines. Each subsequent row shows a
distinct record with values for each field in the columns. You’ll notice that in the field for
‘supervisorStaffNo’ the value is empty or ‘null’ for most records. This is because these records relate
to employees at managerial level who have no direct superior listed in the table. Two records (staff
members) do have supervisors listed in the table. One of these is Sally Adams:
SELECT query statements are very powerful, but retrieving data is not the only function of SQL. SQL
can also be used to modify the contents of the DB. The second example command uses UPDATE to
increase the salary of all managerial staff by 2%:
UPDATE Staff
Note the use of the WHERE clause to tell the DBMS to only change records that pertain to
managerial staff. Now execute this command. You will not see a results table for this operation, only
an instruction telling you to use a SELECT command to see the result. This is because SQL only
creates a result table after a SELECT query. To see the effect of the UPDATE you will need to re-enter
and execute the query you entered before. You should see the following table of data:
3
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
Suppose we have changed our mind and do not want to give the managers a raise anymore. How
would we change the salary data back to the original values? As a hint, you will need to modify the
SET part of the previous command.
Q2: How would you change the SET expression to in order to reverse the raise update?
If you have successfully completed this exercise, you are ready to start the next exercise where you
will examine the SELECT command in greater detail.
[WHERE condition]
[ORDER BY columnList]
These different sub-commands are very powerful and together enable precise control over the
query specification and format of the results table. Check the lecture slides and Chapter 3 of the
textbook now if you need to review their meaning and purpose – you will be using all of these over
the course of the following exercises.
SELECT…FROM…ORDER BY
SELECT...FROM…GROUP BY…WHERE
SELECT…FROM...HAVING
SELECT…FROM…GROUP BY…HAVING
4
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
Q4: Complete the following query so that the result table lists full details of all members recorded
in the StayHome database:
If you got it right you should see the following result table:
Q5: Complete the following query so that the result lists just member number, first name and last
name (in that order) of all members recorded in the DB:
SELECT DISTINCT
The queries applied so far have retrieved all records (rows) from the specified table. If you only want
to retrieve the set of distinct values for a particular attribute, you would use the DISTINCT keyword.
For instance, the Member table contains address details of all members. Let’s say you want to
retrieve a list of all cities in which members reside. You only want each unique city to be listed once.
Q6: Complete the following query to list the set of cities in which Distribution Centres are based:
Calculated fields
Another very useful feature of SELECT is the ability to dynamically derive new fields from existing
ones and present these in a results table. These are known as calculated fields and are derived using
a mathematical expression. Expressions may contain existing fields and literals joined by operators
(e.g. plus, minus etc). The example given in the lecture showed you how to specify a calculated field
to transform staff (annual) salary into monthly salary figures. See if you can modify this expression to
provide weekly salary values instead.
Q7: Write a SELECT query that lists the weekly salary of all staff members. How much does Sally
Adams earn per week?
5
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
Q8: Suppose we wanted to know how much staff members earn, per week, relative to Sally
Adams. Complete the following query to create a field, named sallyDiff, that represents the
difference in weekly earnings between each staff member and Sally.
Hint: check Sally’s annual salary from the earlier result table and incorporate it into your expression.
Q9: To the nearest cent, how much more does Robert Chin earn, per week, compared to Sally?
[$38.46]
We’ll start with a simple comparison. Remember that when performing comparisons with string
fields (values containing one or more non-numeric characters), you must encapsulate the literal
value in single quotes (e.g. B001 ‘B001’).
Q10: Complete the following query so that the result lists the name followed by monthly salary
(named monthlySalary) of all staff members that work at distribution centre B002:
Q11: Complete the following query to list all rows from the DVDOrderLine table where the order
quantity is less than 4:
Q12: Complete the following query so that the result lists the full details of all Staff members who
earn at least $30000 but less than $40000 per year:
SELECT * FROM Staff WHERE salary [?] 30000 [?] salary [?] [?];
Note SQL provides an alternative way of checking ranges in the form of the BETWEEN keyword:
This should return exactly the same result as your previous query, but is it expressing the same range
constraint? There is also a way to test for values that fall outside of a given range using a negated
form of BETWEEN. Check page 55 of the textbook to find out and try it.
6
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
Alternatively, SQL provides the IN keyword to allow the same test. This can be helpful if there are
many alternative categories, resulting in a more compact query. The textbook (p.55) explains how to
use this.
Q14: Using the IN keyword, complete the following query so that the result lists the full details of
all DVD copies (discs) held in the Portland and New York distribution centres:
Q15: Complete the following query so that the result lists the full details of all distribution centres
where the street address ends in “Avenue”:
Q16: What WHERE condition would allow you to match all rows of the Member table where the
member’s last name is exactly six characters long?
Q17: Complete the following query to show the title and rating of all films (DVD table) listed in
alphabetical order by title:
Modify the query so that titles are listed in reverse (Z-A) title order.
7
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
UPDATE
A common activity when using a DB is to make changes to existing records. This is achieved in SQL
using the UPDATE command. You have already performed one UPDATE in the earlier example where
you increased the salary of managerial staff by 2%. Review this example and then attempt this more
complex update:
Q18: Sally Adams (staff number = S0003) has been given a raise of $1000 per year. She has also
just got married and her surname has changed to Daniels. Complete the following UPDATE
command so that these changes are reflected in the database:
UPDATE Staff [?] name = [?], salary = salary + [?] WHERE [?] = ‘S0003’;
Note that, as before, no result table is returned after an update. You will need to perform an
appropriate SELECT command in order to see whether your UPDATE has taken appropriate effect.
INSERT
The facility to add a new record is also an important function of a DBMS. This is achieved using the
INSERT command. Review how to construct an INSERT
A new member has joined the library. His details are as follows:
memberNo - M166785
mfName - Richard
mlName - Head
mStreet – 2 Hope Street
mCity - Portland
mState - OR
mZipCode – 97233
This is not a complete row. The values for the member’s e-mail, password and membership type are
not yet known, so you will need to specify a field or column list after the table name, otherwise SQL
will be expecting values for all fields.
INSERT [?] [?] (memberNo, mfName, mlName, [?], mCity, mState, [?]) VALUES (‘M166785’,
‘Richard’, [?],’2 Hope Street’, ‘Portland’, ‘OR’, [?]);
Now check that the INSERT has taken place by performing an appropriate SELECT command.
DELETE
From time to time, it is also necessary to delete records from a DB. You have just discovered that the
new member record for Richard Head was entered in error. Review the DELETE command syntax
and construct a command to remove this record from the DB.
Q20: Complete the following query to remove Richard Head (M166785) from the member table of
the database:
8
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
Once again, use a SELECT to check that the change has taken place.
Further Reading
Connolly, T., Begg, C. & Holowczak, R (2008) Business Database Systems (Chapter 3).
9
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London
10