Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
34 views

Lab2-1 - SQL

This document provides an overview of a laboratory tutorial on SQL. It introduces the SQL Lab interface and database and gives exercises on constructing basic SELECT, UPDATE, INSERT, and DELETE statements to retrieve and modify data in the database tables. The exercises cover selecting specific fields and records, updating data, and reversing an update.

Uploaded by

Alan Serrano
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Lab2-1 - SQL

This document provides an overview of a laboratory tutorial on SQL. It introduces the SQL Lab interface and database and gives exercises on constructing basic SELECT, UPDATE, INSERT, and DELETE statements to retrieve and modify data in the database tables. The exercises cover selecting specific fields and records, updating data, and reversing an update.

Uploaded by

Alan Serrano
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 10

CS1703(1805): Data and Information (2015/16)

Dr Timothy Cribbin, Brunel University London

Laboratory Tutorial 2-1: SQL


In this laboratory tutorial you will:

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.

Exercise 1: Getting started with the SQL interface


You can download the SQL Lab tool (SQLLab_2013.exe) from the Laboratory  Resources folder.
This should run ‘out of the box’ as long as the DB file you want to access is placed in the same folder.
The DB file you’ll be using in this tutorial is called “StayHome2002.mdb” and can also be downloaded
from Resources.

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.

The first is a SELECT command:

2
CS1703(1805): Data and Information (2015/16)
Dr Timothy Cribbin, Brunel University London

SELECT * FROM Staff;

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:

SELECT staffNo, name, [position], salary, dCenterNo,


supervisorStaffNo FROM Staff;

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:

Q1: Who is Sally Adams’ supervisor?

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

SET salary = salary * 1.02

WHERE position = 'Manager';

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.

Exercise 2: Further simple SELECT commands


Remember from the lecture that a SELECT command can consist of several different sub-commands
or clauses. Here is a reminder of the general syntax structure of a SELECT command:

SELECT [DISTINCT | ALL] {* | [columnExprn [AS newName]] [,...] }

FROM TableName [alias] [, ...]

[WHERE condition]

[GROUP BY columnList] [HAVING 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.

Q3: Determine which of the following command sequences is correct:

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

SELECT all fields


The simplest SELECT statement is one where all fields and all records are to be retrieved from a
single table. You have already tried this with the earlier example.

Q4: Complete the following query so that the result table lists full details of all members recorded
in the StayHome database:

SELECT * [?] [?]

If you got it right you should see the following result table:

SELECT specific fields


It is often only be necessary to view a subset of all available fields in the result table. To see which
fields are associated with each table, check the table definitions in Appendix A (end of this
document).

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 [?], mfName, [?] [?] Member;

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:

SELECT [?] [?] FROM [?];

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.

SELECT name, ([salary] – [30000]) / [52] [AS] sallyDiff FROM Staff;

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]

WHERE simple comparison


In most situations, you will only want to retrieve records that match some specific criteria, rather
than the entire table (which may contain thousands or millions of records!). To filter records in this
way we use the WHERE clause. The lecture outlined five main types of search condition that can be
used with WHERE: Comparison, range, set membership, pattern match and null.

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:

SELECT [?], salary / 12 AS [?] FROM Staff [?] dCenterNo = [?];

Q11: Complete the following query to list all rows from the DVDOrderLine table where the order
quantity is less than 4:

SELECT * FROM DVDOrderLine WHERE [?] [?] 4;

WHERE range comparison


We can combine two simple comparisons, with a logical operator, to form a range query, where
minimum and maximum limits are specified.

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 [?] [?];

Q13: How many records were returned?

Note SQL provides an alternative way of checking ranges in the form of the BETWEEN keyword:

SELECT * FROM Staff WHERE salary BETWEEN 30000 AND 40000;

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

WHERE set membership


Often it is necessary to retrieve records that belong to one of a range of valid categories. To specify
this, you could join valid categories together using the OR keyword as follows:

WHERE field = ‘cat1’ OR field = ‘cat2’

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:

SELECT * FROM DVDCopy WHERE [?] [?] ( [?][?]'B003');

WHERE pattern matching


Pattern matching is used when want to find records with a field that contains a particular character
or string of characters. For example, you might want to find all staff members whose name begins
with “A” or ends in “Smith”. SQL allows you to perform this test with the LIKE keyword. Once again,
check the slides or textbook if you cannot remember how to construct pattern matching expressions
using the LIKE keyword.

Q15: Complete the following query so that the result lists the full details of all distribution centres
where the street address ends in “Avenue”:

SELECT * FROM DistributionCenter WHERE dStreet [?] [?];

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?

Sorting result tables


Records are generally returned in an arbitrary order. Often it is easier to read a result table if records
are sorted in some way. To achieve this with SQL, use the ORDER BY clause.

Q17: Complete the following query to show the title and rating of all films (DVD table) listed in
alphabetical order by title:

SELECT title, [?] FROM DVD [?] title [?];

Modify the query so that titles are listed in reverse (Z-A) title order.

Exercise 3: Modifying data


Another important function of SQL is to allow users to modify data. The three main commands are
UPDATE, INSERT and DELETE.

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.

Q19: Complete the following query to add this new member:

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

DELETE [?] [?] WHERE memberNo = [?];

Once again, use a SELECT to check that the change has taken place.

Summary and further work


In this tutorial you have learned how to perform simple SELECT queries to retrieve existing data in
the form of result tables. You have also learned how to modify the contents of tables using UPDATE,
INSERT and DELETE commands. In the next tutorial you will examine more advanced SELECT
commands including aggregate functions, grouping results, and multiple table queries (joins). These
have all been outlined in the SQL lecture and are discussed in the textbook, so feel free to ‘look
ahead’ and attempt the examples provided.

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

Appendix A: Entity Relationship Model for StayHome

10

You might also like