23
CS510 Laboratory Exercise Introduction The CS510 course covers one particular aspect of computer applications: information management with databases. The lectures cover some theory in this area and the CS510 laboratory exercises will build a complete working system over the duration of the course. The exercises involve the design and construction of a database. The exercises will be conducted using partially completeddatabase implementations devised around a case study. The case study is incremental, so that later exercises build on earlier ones. Some of the exercises are to be done individually and others in pairs of your choosing. The Case Study Orinocois a medium sized record producer offering music on CDs, Tape, and Vinyl . They have just brought a number of smaller recording companies and are rapidly expanding. There is a great deal of information in the brochures that Orinocoproduce alongwith an accompanying price guide. Some of the information is on computer but this is somewhat cumbersome as it is in separate systems that are incompatible, incomplete anddifficult to use (due to the recent takeovers). It is particularlydifficult to find music that matches a customers specific requests unless the brochure is browsed carefully. Orinocohave decided to computerise the information in their brochure, to include purchase information, and to sell directly over the web. They need to make it easier to: Gather specific information from customers and answer questions about products. Check the availability of specific products. Give costs of products. Keep information about artists, albums, and tracks. Keep information about the back catalogues of the companies recently taken over. Keep contract information about artist signings etc. For simplicity , you may assume that the system is stand-alone anddoes not have to integrate with any other . Note that many other simplifying assumptions will be made (e.g., that price information is fixed and is not flexible, and there are no sale items etc.). Y ou shouldbe sure to solve the problems as specified not as you imagine theywouldbe in the real world. 1

CS510 Laboratory Exercise - School of Computer …horrocks/Teaching/cs530/Lab/LabManual.pdfCS510 Laboratory Exercise ... Dia and SQL Plus tools. 3 short exercises will be provided

Embed Size (px)

Citation preview

CS510 Laboratory Exercise

Introduction

The CS510 course covers one particular aspect of computer applications: informationmanagement with databases. The lectures cover some theory in this area and the CS510laboratory exercises will build a complete working system over the duration of thecourse. The exercises involve the design and construction of a database. The exerciseswill be conducted using partially completed database implementations devised around acase study. The case study is incremental, so that later exercises build on earlier ones.Some of the exercises are to be done individually and others in pairs of your choosing.

The Case Study

‘Orinoco’ is a medium sized record producer offering music on CDs, Tape, and Vinyl.They have just brought a number of smaller recording companies and are rapidlyexpanding. There is a great deal of information in the brochures that ‘Orinoco’ producealong with an accompanying price guide. Some of the information is on computer butthis is somewhat cumbersome as it is in separate systems that are incompatible,incomplete and difficult to use (due to the recent takeovers). It is particularly difficult tofind music that matches a customer’s specific requests unless the brochure is browsedcarefully.

‘Orinoco’ have decided to computerise the information in their brochure, to includepurchase information, and to sell directly over the web. They need to make it easier to:

Gather specific information from customers and answer questions aboutproducts.Check the availability of specific products.Give costs of products.Keep information about artists, albums, and tracks.Keep information about the back catalogues of the companies recently takenover.Keep contract information about artist signings etc.

For simplicity, you may assume that the system is stand-alone and does not have tointegrate with any other. Note that many other simplifying assumptions will be made(e.g., that price information is fixed and is not flexible, and there are no sale items etc.).You should be sure to solve the problems as specified not as you imagine they would be“in the real world”.

1

The Exercises

Monday Exercise (1 session):Training on Systems - SQL Plus and Dia for ER Modeling Gaining experience withDia and SQL Plus tools. 3 short exercises will be provided for each. Part of the databasealready exists as a relational database implemented in the Oracle DatabaseManagementSystem. The exercise is to learn to access and manipulate this database in order tofamiliarise yourself with the query language, database environment, and design tools.This exercise is undertaken individually.

ER Diagramming - Extend a given Dia diagram to represent the problem given. Youwill be required to extend the EER diagram you have been given.This exercise is undertaken in individually.

Tuesday Exercise (1 session):Mapping the Relational Schema and SQL DB Creation - Youwill be asked to mapyour EER design extensions to a relational database design. Extend a relationaldatabase with your own ER design. The database used in this exercise was designedusing the Extended Entity Relationship (EER) data model. In this exercise you will alsobe given some of the design, asked to explain the meaning of the design in words andexplain to what extent the relational database is a true representation of the design. Thisexercise is undertaken individually.

Wednesday Exercise (1 session):Data Population and Simple SQL Querying - Populate the database with generic testdata. You may test your database model by executing a given query. You will berequired to discuss and review the quality of your design. Test data will be given inelectronic form. This exercise is undertaken in individually.

Thursday Exercise (1 session):Complex SQL Querying and Views and Triggers - Perform a number of queriesacross the database including joins and views and create triggers to maintain integrity.You may test your database model by executing a given query. You will be required todiscuss and review the quality of your design.This exercise is undertaken in individually.

Friday Exercise (1 session):PL-SQL - Wrap the SQL statements from the previous exercise in PL-SQL. You maytest your database integration by executing a given query. You will be required todiscuss and review the quality of your design.This exercise is undertaken in individually.

Oracle Documentation

There are three forms of documentation:

1. Essential material is embedded in the text of the exercises, in particular a tutorial inExercise 1 and a guide to loading data and controlling permissions in Exercise 4;

2. The Oracle 9i User Guide and Oracle 9i Integrity Constraints Guide will be madeavailable to you all;

2

3. The full Oracle manuals are online and can be accessed fromhttp://aardvark.cs.man.ac.uk:8899/9202doc/index.htm . Go to the Oracle9i manual.For the SQL language guide you need to select SQL Server manual pages. Thequick reference guide and the “Users Guide and Reference” are at:http://aardvark.cs.man.ac.uk:8899/index.shtml.

Pointers to all the above resources can be found athttp://www.cs.man.ac.uk/~horrocks/Teaching/CS510/

3

Monday Exercise (1 session)Exercise #1Marks: 10 marks availableEquipment required: Linux PCs using the Oracle DBMS. It should also be possible touse Windows PCs. Some of the following instructions may not apply in this case ofLinux PCs (e.g., references to the menu bar), and some script files (e.g., to repairdamaged databases) may not work on Linux machines.

To be done INDIVIDUALLY.

Purpose

1. To become familiar with Oracle2. To become familiar with Dia3. To understand and experience a data dictionary4. To become familiar with the data definition and manipulation language SQL.5. To understand referential integrity6. To explore the existing database for the Orinoco system.

By convention table names are written in uppercase, but Oracle is not case sensitive.

What you need to do this exercise

Previous knowledge of SQL and Dia is not assumed or required.You will need the Oracle 9i Guide and the Dia Manual.

Problem

This exercise has two parts; a tutorial followed by an exercise.

You are the owner of some tables for Orinoco that have been created for you already.They are:Manager(ID, name)ManPhone(ID, telephone)SoundEngineer(sound_eng_ID, name)Artist(artistic_name, genre, managedby)ContractInfo(contract_ID, date_from, date_to, duration)MasterTrack(track_ID, working_title, duration, recorded_by, edited_by)FinishedTrack(ft_ID, version ,released_title, final_duration)Album(album_ID, is_distributed_as, title, created_by)

Each Artist has an artistic name a musical genre and is managed by a manager who canhave a series of contact telephone numbers. Artists also have a contract with Orinoco,which has a date from and to, and the duration of the contract in days. An Artist recordsa number of master tracks which have IDs a working title and a duration; tracks areedited by a sound engineer, who has a name and ID. A finished track originates from amaster track and has a version number (a finished track may have a number of differentversions) a released title and a final duration. Albums group finished tracks into asequence or play list / order. Albums have a title, are created by an artist, and can bedistributed as a CD, on Vinyl, or as a Tape Cassette (denoted by ‘c’, ‘v’, and ‘t’respectively).

4

TutorialStarting SQL*Plus

Launch the program SQL Plus OnWindows machines:

Start/Programs/Oracle OraHome92/Application Development/SQL Plus

and on Linux machines:

/home/oracle/sbin/sqlplus

You will be prompted for your user name, Oracle password and host machine.The password is NOT the same as your UNIX one, and will have been allocatedto you. The “Host String” (Windows machines) is teach

Success should lead to one of the following windows:

Windows Login

Linux Console Window

5

If there is any problem or error message, call a demonstrator. The SQLprompt is:

SQL>

When you see the SQL prompt simply type in your SQL command, or pastecommands in from your favourite text editor (highly recommended).Separate words by spaces or tabs. Commands can appear in upper or lowercase. There are also special SQL*Plus commands for formatting, settingoptions and editing and storing SQL commands (see the Oracle 9 Guide).

Listing a Table DefinitionOne of the tables you own is MANAGER. Use the SQL*Plus commanddescribe to find out the definition of MANAGER, which is held in the DataDictionary.

SQL> describe manager

Produces output:Name Null? Type--------------------- -------- ---------------------ID NOT NULL NUMBER(38)NAME NOT NULL VARCHAR2(50)

Getting started with SQLSelecting the entire relation

To select all columns and all rows in theMANAGER table, use:

SQL> select * from manager;

Ending a SQL commandYou can end a SQL command in three ways but in general you will use asemicolon (;) at the end of the SQL command. This means that you want torun the command. Press return to activate the command. If you mistakenlypress return before typing a semicolon, just enter it on the next line.

Halting a CommandUse <ctrl-c> or menu bar option File | Cancel

SQL commands over more than one lineEnter the first line of the command to list the manager ID and name formanagers called ‘Freddy Glitter’:

SQL> select ID, name

If you make a mistake use delete to erase it and re-enter. Press return tomove to the next line. (You can type the whole query on one line and it willwrap but you won't be able to edit characters on the previous line).

SQL*Plus will display a '2', the prompt for the second line. Enter the secondline of the command.

6

2 from manager

SQL*Plus will display a '3', the prompt for the 3rd line. Enter the third lineof the command.

3 where name = 'Freddy Glitter';

Notice the single quotes ( ' ) around the string literal Freddy Glitter.The semicolon (;) means that this is the end of the command. Press return(note that if you are using a text editor you can enter the whole multi-linecommand with a single “paste” operation). SQL*Plus processes thecommand and displays the results on the screen.

ID NAME---------- -----------------------

1 Freddy Glitter

1 rows selected.

SQL>

After displaying the results and the number of records retrieved, SQL*Plusdisplays the command prompt again. SQL*Plus has syntax rules forcommands. If you break a syntax rule you will get an error and thecommand will not execute. Youcan divide your SQL command into separatelines at any point you wish, so long as the individual words are not splitacross lines. Don't leave any blank lines in your command because tworeturns is also counted as meaning 'end of command'.

Editing SQL commandsTypically you will enter an SQL query on several lines, execute it and thenwant to alter it and try again. The SQL command is in the command buffer,which can be edited (via the menu bar), but it is highly recommended thatyou edit your commands by using a text processing/editor application (e.g.Word, WordPad or NotePad). Type your commands into the text editor andthen just cut-and-paste. The line numbers may flash up and make the querylook a bit of a mess, but they don't affect its execution. This way you canalso maintain a history of different queries you have tried and edit/retrycomplex queries until you get the syntax right.

Remember to include the semicolon and return to complete the command!

Saving your queries for reportsAn easy option is to cut and paste the queries into a Word document as yougo along.Alternatively you can use menu bar option File | Save or SaveAs.

Saving the results of your queries for reportsAgain, an easy option is to cut and paste the answers into aWord documentas you go along. Alternatively you can use menu bar option File | Spool |Spool File to spool the query results to a file. Results will be spooled to thefile until you switch spooling off using menu bar option File | Spool | SpoolOff.

7

Sorting resultsTo sort the rows in a table in cascading ascending order (i.e. sort first by Xand then within that sort by Y, and then within that sort by Z) add the clauseORDER BY X,Y,Z. at the end of the select statement. e.g.

SQL> select *from managerorder by name;

This is described in your SQL notes.

Interpreting Error MessagesAn example: if you misspell the name of a table while entering a command,an error message will tell you that the table or view does not exist:

SQL> describe minager;

Object does not exist

If you need an explanation other than the message, do the following:

- If an error is a numbered error for the SQL*Plus, look up the message inAppendixA of the SQL*Plus Guide.

- If the error is unnumbered, look up the syntax for the command thatgenerated the error in Chapter 6 of the SQL*Plus Guide, or SQLLanguageManual.

- If the error is a numbered error beginning with the letters "ORA", thiswill have to be looked up in the ORACLE ERROR Messages and CodeManual or the ORACLE Installation and user's manuals for Unix. Youcan also use an Oracle program to look up information about errors. 'oerr'will give some details about a message. To use it type:oerr facility number

where facility is the three letter code at the start of the error message. Eg:ora, and number is the error number. Typing oerr on its own will givesome instructions. In other words, its bad news.

Getting the results to fit on the screenWhen the results get large two commands can be used to make the resultseasier to read.

SQL> set pagesize 25SQL> set linesize 150SQL> column <column_name> format a20

Sensible use of the above (possibly with different numeric values andcolumn names) can help to make your reports look neater. There are manysuch SQL*Plus commands that control the environment (as opposed to theSQL commands that are the query language).Choosing from menu bar Options | Environment, gets you to a whole bunchof environment variables that you can alter through the dialogue box.

8

The Oracle Catalog and Data DictionaryOracle has a data dictionary containing all the management information onthe objects (tables, views, indexes etc) in the database. You cannot alter thisdictionary directly, but you can look at it: the data is held as tables so theusual SQL commands work. The Oracle9 Server Administrator's Guide hasa list of all the Data Dictionary Views and the Oracle reserved words.

Listing the tables you ownThe data dictionary table (well actually its a view) USER_TABLES containsinformation on all the tables the user (i.e. you) own. As its just a table itselfyou can access the information using SQL statements. E.g.:

SQL> select table_name from user_tables;

Notice that the data strings in the dictionary are in upper case, so any 'where'clauses for matching values will have to be aware of this. Have a look atUSER_TABLES and see just how much metadata (data about data) a table has.

Listing the tables you have access toYou can grant permission for other users to access your tables and viceversa. You have been granted permission to select-only from Carole's tables,some of which are the same as the Orinoco database you have. Thedictionary table ALL_TABLES lists all the tables you can access.

SQL> select table_name from all_tableswhere owner = 'CAROLE';

Don't worry about the some of the table names being the same as yours—yours will always be accessed in preference.

Integrity Constraints in the Data DictionaryDescribe accesses information in the ORACLE data dictionary. Noticethat this doesn't tell us anything about keys or any integrity constraintsdefined on the table. We have to SELECT from the data dictionary to findout such information. To check out the integrity constraints on the MANAGER

table we need to look at two dictionary views:

USER_CONSTRAINTS constraints on the tablesUSER_CONS_COLUMNS constraints on columns in the tables

(There are equivalent views for tables not necessarily owned by you calledALL_CONSTRAINTS and ALL_CONS_COLUMNS. )

These views are pretty confusing to look at.

select constraint_name, constraint_type,table_name, r_constraint_name, delete_rule,

statusfrom user_constraintswhere table_name = 'MANAGER' or table_name = 'MANPHONE';

9

CONSTRAINT_NAME C TABLE_NAME R_CONSTRAINT_NA DELETE_RU STATUS--------------- - --------------- --------------- --------- -------SYS_C00190170 C MANAGER ENABLEDM_ID_PK P MANAGER ENABLEDMP_ID_PK P MANPHONE ENABLEDMP_ID_FK R MANPHONE M_ID_PK NO ACTION ENABLED

4 rows selected.

Notice that the literal values in the dictionary table are all in uppercase, sowhen they are queried for they must be in uppercase in the select statement.You might get a few more than those listed here...don't worry about it.

The constraint_type can be:

P Primary keyR Foreign Key (Referential integrity)C Constraint, (SQL expression such as 'not null' or 'check in ('cis','cs')')

Rows 1 and 3 state that the MANGER and MANPHONE have a primary keydefined and that it is enabled. The constraint has been named by the ownerwith a constraint_name.

Row 4 states thatMANPHONE has a foreign key targetted on a primary key. Sorow 4 says that MANPHONE has a foreign key trained on the primary keyconstraint M_ID_PK which we know is define on resort table because it saysso in row 2.

- delete_rule for referential integrity can be no action (which means restrict)or cascade.- status can be enabled or disabled.

The constraints named SYS_xxxxx are created by Oracle for unnamedconstraints.

SQL> select constraint_name, constraint_type,table_name, search_condition

from user_constraintswhere constraint_type = 'C';

CONSTRAINT_NAME C TABLE_NAME SEARCH_CONDITION--------------- - --------------- -----------------------SYS_C00190180 C ARTIST "GENRE" IS NOT NULLSYS_C00190181 C ARTIST "MANAGEDBY" IS NOT NULLSYS_C00190938 C CONTRACTINFO "DATE_FROM" IS NOT NULLSYS_C00190939 C CONTRACTINFO "DATE_TO" IS NOT NULLSYS_C00190170 C MANAGER "NAME" IS NOT NULLSYS_C00190174 C SOUNDENGINEER "NAME" IS NOT NULL

These tuples all have a constraint type = 'C'. This represents a checkconstraint - in this case to check that the attributes are NOT NULL.

USER_CONSTRAINTS just tells us that there are constraints on the tables, but notthe columns that the constraints act upon. To see this we have to look atview USER_CONS_COLUMNS.

10

SQL> select constraint_name, table_name, column_name,position

from user_cons_columnswhere table_name = 'MANAGER' or

table_name = 'MANPHONE';

CONSTRAINT_NAME TABLE_NAME COLUMN_NAME POSITION--------------- --------------- --------------- ----------MP_ID_FK MANPHONE ID 1MP_ID_PK MANPHONE ID 1MP_ID_PK MANPHONE TELEPHONE 2M_ID_PK MANAGER ID 1SYS_C00190170 MANAGER NAME5 rows selected.

This tells us that the constraint MP_ID_PK refers to column TELEPHONE inthe table MANPHONE. The name suggests that this is a primary key constraint.It also tells us that MP_ID_FK in the MANPHONE table refers to column ID,suggesting that this is a foreign key constraint referring to the MANAGER

table's primary key (identified by M_ID_PK). We can infer much of thisinformation from the constraint names—that is why it is a good idea to giveconstraints sensible names. (Note that POSITION refers to the position of acolumn in a composite key.)

Reloading the Tables when you've screwed upIf you've managed to delete or otherwise damage the data in the tables forthe Orinoco Exercise. The best thing to do is to drop all the Orinoco tablesand start again.An SQL command file has been created for you for this verypurpose, found on drive L. The procedure is as follows. First open the file:

http://www.cs.man.ac.uk/~horrocks/Teaching/CS510/Oracle/repair.txt

Copy the contents into SQL Plus and the database will be recreated.If you here a beep from SQL Plus it means your copy buffer has overflowed.Just copy the contents as normal but you may have to do this in stages toaccommodate this error.

Big HintThe main problems for new SQL programmers concern syntax errors thatare difficult to identify from the error messages. Therefore:

1) Break your queries into separate lines, and build queries up slowly, bit bybit.2) Use cut and paste from a text editor so you can edit complex commands.

Getting started with DiaDia is an application for creating technical diagrams. Its interface and features areloosely patterned after the Windows program Visio. Dia is a diagramming applicationmade for many people. Dia is easy enough to learn without much hassle and flexibleenough to make power users feel at home when compared with their commercial tools.

The first thing to do with Dia is to read the Dia manual supplied with the course notes.Then you should ‘play’with the tool and familiarise yourself with the application. Yourobjective is to create the second diagram from the sequence you see below (see Figure

11

1). You do not need to know what it means at this stage but you should be able to createit by using the Dia tool.

The first figure is a replica of the second, but to help you, each shape is labelled with itsgeneric type from the Dia Package. Remember it’s easier to create your shapes from theDia toolbox and then double click to edit their attributes.

Directions

1. Work your way through the tutorial. Make sure you know the tables that you own,the data in them and their definitions. List the primary, the foreign keys and theirtarget primary keys for each Orinoco Database table.

2. Using Dia replicate the diagrams as shown in Figure 1.1.

Report (to be handed in at the end of the course)

You must hand in the following:1. A listing of the structure of each table (3 marks).2. A listing of the primary and foreign keys of the Orinoco Database (2 marks).3. A listing of the data from each table in the database (2 marks).4. The Dia Chart of an EER diagram (as in Figure 1.1) (3 marks).

12

Figure 1.1: Sample EER Diagram Created Using Dia

Exercise #2Marks: 17 marks + 3 bonus marksEquipment required: Linux PCs using the Dia System. It should also be possible to useWindows PCs.To be done INDIVIDUALLY.

Purpose

1. To understand the part-completed Extended Entity Relationship schema for theOrinoco system (see Figure 2.1).

2. To be able to create and extend an EER from descriptions of user requirements.3. To practice data modelling.4. To extend the data model for the Orinoco system.

13

What you need to do this exercise

You will need to understand the EER model, the relational model, and referentialintegrity.ADia file has been created for you to extend and can be found at:

http://www.cs.man.ac.uk/~horrocks/Teaching/CS510/Oracle/basis.dia

Directions

Basis.dia represents a part-completed EER schema which, models some of theinformation implemented in the system, as a starting point for this exercise and futureLaboratory exercises.

1. Understanding the EER schema for the Orinoco system.

To demonstrate that you understand the information represented by the schema,explain using MANAGER, CONTRACTINFO, ARTIST, MASTER TRACK, FINISHEDTRACK, ALBUM, and SOUND ENGINEER as examples:

i) attributes, entities and relationshipsii) cardinality & participation constraints on relationships

You don’t need to explain the entities etc BUT you should explain question i andii using the schema you have been given to more easily explain youranswers. Don’twrite more than half a page to answer question 1.

2. Creating and Extending Entity Relationship Diagrams.

To demonstrate you can create entity relationship diagrams extend the EER asdescribed in Basis.dia by modelling new requirements as follows:

a) The system has an online catalogue, which stores a reference to an album.An album can have a number of entries in the catalogue determined by therelease date of the album (to account for re-releases). The catalogue alsostores the price of each entry and the number in stock (available).

b) A buyer can place an order.We use the buyers code to uniquely identify thebuyer with the order and so an entity for the buyer needs to be created (wealso store their name).

c) A buyer can place any number of orders, each of which has an order numberand a dispatch date. An order also composed of separate parts each of whichreferrers to a catalogue entry.

d) Create subclasses to extend Artist. Two different types of Artist exist: a Soloartist and a Group artist. A solo artist can be a member of more than onegroup and group is made up of one or more solo artists.

e) ExtendAlbum thus: an album comes in one of three types – Vinyl, Tape, andCD discriminated by ‘v’, ‘t’, and ‘c’ respectively.A vinyl album can come ina number of colours, a CD album can have a number of different pc extras,and a tape can have only one label type.

f) Now explain the category relationships: supertypes and subtypes that youhave just created.

14

3. Bonus Questions.

a) Explain the relationship ‘CreatedBy’.b) Explain the relationship ‘GroupedOn’.c) Is it possible for many artists to appear on one album?

Report (to be handed in at the end of the course)

You must hand in the following:1. Explanation of what the given EER diagram means (5 marks).2. Completion of the EER as per the specifications in the questions (10 marks).3. Good Report Style (2 marks).4. Bonus Questions (3 marks).

15

Tuesday Exercise (1 session)

Marks: 16 marks + 4 bonus marksEquipment required: Linux PCs using the Oracle DBMS. It should also be possible touseWindows PCs.To be done INDIVIDUALLY.

Purpose

1. To identify integrity constraints in the model.2. To understand the mapping of the EER model to a relational model, and explorethe consequences to the integrity constraints.

What you need to do this exercise

You will need to understand EER schemas, the relational model, and explicitintegrity constraints.

Directions1) Creating Relational Schema.

Fragment 3.1 represents a part-completed Relational Schema, which modelssome of the information implemented in the system, as a starting point for thisexercise. Extend this fragment to accurately represent the extensions to the EERdiagram you created in Laboratory 2.Remember:i. To model the ‘GroupedOn’Relationship.ii. To explain how your entities map to the relational schema, clearly

identifying the candidate, primary and foreign keys.

iii. To explain how the cardinality and participation constraints on yourrelationships, and how they could be implemented in the relationalmodel.

2) Creating Table Elements from the Relational Schema.

Fragment 3.2 shows 3 sample SQL statements. Complete and execute the createstatements for the extended elements from your relational schema. Oncecomplete, use the statements shown in Laboratory 1 to list each table and theattributes, keys, etc associated with it.

3) Bonus Question.

Explain what has been lost in the mapping from EER to relational schema, andof how the semantics could be recovered via integrity constraints for the Artist /Album relationships in the EER schema.

16

Report (to be handed in at the end of the course)

You must hand in the following:1. The EER from your last Exercise (Marks NotApplicable).2. Any Changes you made and why (Marks NotApplicable).3. Creation of the relational schema (8 marks).4. Identification of the candidate, primary and foreign keys (4 marks).5. Proof of table creation (create statements and Oracle table descriptions) (2 marks).6. Good Report Style (2 marks).7. Bonus Question (4 marks).

Manager(ID, name)ManPhone(ID[fk:Manager.ID], telephone)

SoundEngineer(sound_eng_ID, name)

Artist(artistic_name, genre, managedby [fk:Manager.ID])

ContractInfo(contract_ID {composite: has_contract[fk:Artist.artistic_name], date_from,date_to}, Duration{derived as date_to - date_from})

MasterTrack(track_ID, working_title, duration, recorded_by[fk:Artist.artistic_name],edited_by[fk:SoundEngineer. sound_eng_ID])

FinishedTrack(ft_ID {composite: originates_from[fk:MasterTrack.track_ID], version},released_title, final_duration)

Album(album_ID, is_distributed_as, title, created_by[fk:Artist.artistic_name])

Fragment 3.1: Part-Completed Relational Schema

CREATE TABLE Manager(ID INTEGER,name VARCHAR2(50) not null,CONSTRAINT m_id_pk PRIMARY KEY(ID));

CREATE TABLE ManPhone(ID INTEGER,telephone VARCHAR2(40),CONSTRAINT mp_id_pk PRIMARY KEY(ID, telephone),CONSTRAINT mp_id_fk FOREIGN KEY(ID) REFERENCES Manager(ID));

CREATE TABLE SoundEngineer(sound_eng_ID INTEGER,name VARCHAR2(50) not null,CONSTRAINT se_sound_eng_id_pk PRIMARY KEY(sound_eng_ID));

Fragment 3.2: Sample SQLCreate Statements

17

Wednesday Exercise (1 session)

Marks: 16 marks + 4 bonus marksEquipment required: Linux PCs using the Oracle DBMS. It should also be possible touseWindows PCs.To be done INDIVIDUALLY.

Purpose

1. To identify integrity constraints in the model.2. To understand the mapping of the EER model to a relational model, and explorethe consequences to the integrity constraints.

What you need to do this exercise

You will need to understand, the relational model, SQL update and insert syntax andindex creation concepts and SQL syntax. Youwill also need to know how to formsimple SQL Select queries.

Directions1. Populating the Newly Created Tables.

a) From the EER, Relational Schema, and Create Statements describe the meaningof:

INSERT INTO Artist VALUES (‘Goldfrat’, ‘Indie’, 1);

What do the values in the brackets ‘( )’ mean when describing theminformally.

b) Populate the GroupedOn table with the information at:http://www.cs.man.ac.uk/~horrocks/Teaching/CS530/groupedon.txt ; you mayneed to make changes to the file to allow you to fit the data into your tables.

c) Populate your tables using the following information.(a) The database already has 5 buyers signed up: ‘Simon Plant’; ‘JulieLast’; ‘Rina Blue’; ‘Kay Srabonian’; and ‘YosWillis’ and they havealready been assigned IDs 1-5 respectively. Create Records withinthe database for each.

(b) Of the artists already present in the ‘Artist’ table some are soloartists, some belong to groups, and some are solo artists that alsobelong to a group. The following is a complete list and you shouldcreate entries to represent each artist. Simon Palm’s real name is‘Fred Maynard’ he’s a solo artist but is also a member of both thegroups ‘Goldfrat’ and ‘Scandal’. John Cliff has no stage name he isknown just as ‘John Cliff’ he’s a solo artist but is also a member of‘Goldfrat’. Jay Blancard’s real name is ‘Mervin James’ he’s a soloartist and he also belongs to both ‘Goldfrat’ and he has his own groupcalled ‘Jay Blancard’ too. Palmer John is really called ‘SamanthaJules’ she’s a solo artist but is also a member of ‘Flut’ and ‘Scandal’,and she has her own group called ‘Palmer John’. JZ is really called‘Julie Zeb’ she’s a solo artist but is also a member of both ‘Flut’ and‘Scandal’. JK Rowl’s real name is ‘Marisa Jaher’ she’s a solo artist

18

but is also a member of both ‘Flut’ and ‘Zero7’. Finally, PJ Blox’sreal name is ‘Pandar Rahoux’ he’s a solo artist but is also a member‘Zero7’.

(c) ‘Goldfrat’ have recorded one album called ‘20 People in a Field’ andit has been released as a CD on vinyl and on tape. There are 2 CDreleases one with extra information on the ‘Web’ and another with anadditional ‘Video’. There are 3 vinyl releases one on ‘Red’ vinyl, oneon ‘Black’ and another on ‘Green’. The tape release has a ‘Fancy’label. ‘My Feet’ by ‘Flut’ is released on both CD and vinyl. There isone CD type that has an extra ‘Game’ and one other release on ‘Red’vinyl. Finally, Jay Blancard’s album ‘Debut’ is only released on CDbut has to versions one with extra ‘Video’ and another with an extra‘Game’.

(d) The online catalogue has been populated with entries for sale to thebuyers. Each of our albums has an entry. ‘20 People in a Field’ onCD is priced at £14.99 and has a stock of 2, On vinyl it is £12.99 andhas a stock of 5, and on tape it is £10.99 and there are 9 tapesavailable. ‘My Feet’ on CD is priced at $14.99 and there is 1 in stockwhile on vinyl it is 12.99 but there is no stock left. Finally, ‘Debut’by Jay Blancard is available on CD at a price of £14.99 and there isonly on CD available (choose your own dates).

(e) Three orders have been place. The first by Simon Plant on 10th Dec2001 has an order ID of 1 and has 2 parts. The first is for Goldfrat’s‘20 People in a Field’ on CD and the second for Jay Blancard’s‘Debut’. The second order was placed by Julie Last on the 15thMarch2002 again for Goldfrat’s ‘20 People in a Field’ but this time on tape.Finally, a third order has been placed again by Simon Plant on 10th

Jan 2003 for the vinyl album ‘My Feet’ by ‘Flut’.

2. Indexes and their purpose.

a. What is the purpose of an index?b. Our scenario requires fast searches on human readable information.Primary and foreign key indexes are typically not human readable.Therefore, which fields (attributes) do you think indexes should becreated on and why?

c. Create indexes on your tables and the attributes you have selected.

3. Integrity and Errors.

All the following statements would fail. For each list why.

INSERT INTO ManPhone VALUES (6, ‘09495849869’);INSERT INTO SoundEngineer VALUES (6, ‘’);INSERT INTO FinishedTrack VALUES (103, 3, ‘’, ‘3 mins’);

4. Simple Selection.

1. Select all columns / fields from each of the tables Manager; ManPhone;Artist; SoloArtist; GroupArtist, and Sound Engineer.

2. Select all columns / fields:From solo artists where their artistic name is ‘Palmer John’.

19

From groups called ‘Goldfrat’.From master tracks edited by ‘Max Spring’.

3. Select all columns / fields from master tracks and order by the working titleand then by working title in reverse order.

4. Select the columns recorded_by and working_title fromMasterTrack edited by ‘Max Spring’ ordered by working_title inreverse order.

5. Select all columns / fields from ContractInfo where:The date from starts on the 20th.

The date from is in October.The date from is in 2002.

5. Bonus Question.

The Orinoco database contains many opportunities for inconsistency:a. Can the dispatch date for and order occur before the release date ofan album?

b. What mechanism can be used to prevent inconsistencies (excludingreferential integrity)?

ReportYou must hand in the following:1. Your Table Creation Statements from your last Exercise (Marks NotApplicable).

2. Any Changes you made and why (Marks NotApplicable).3. Answer to Question 1a (1 mark).4. Create Statements from the population of the Database (4 marks).5. Create Statements from the creation of Indexes and answers to the indexquestion (3 marks).

6. Answers to the questions posed in the integrity and errors questions (2 marks).7. Results from the each of the selection statements and those statementsthemselves (4 marks).

8. Good Report Style (2 marks).9. Answers to the Bonus Question (4 marks).

20

Thursday Exercise (1 session)

Marks: 18 marks + 2 bonus marksEquipment required: Linux PCs using the Oracle DBMS. It should also be possible touseWindows PCs.To be done INDIVIDUALLY.

Purpose

1. To understand complex SQL select queries.2. To understand how to decompose scenarios into SQL queries.3. To understand Triggers and their use in enforcing integrity.

What you need to do this exercise

You will need to understand, the relational model, how to form complex SQL Selectqueries, and how to create and test triggers.

Directions1. Understanding Complex SQL Queries.

a) Select all columns / fields from master tracks and sound engineer joining thetwo based on the sound engineers ID and using an alias for each table.

b) Find all solo artists who are members of Goldfrat, only print the columns inthe solo artists table and use an alias for each table.

c) Display each phone number joined to its associated managers name (use andouter join for this).

d) Count the number of tracks in the master track table.e) Sum the track IDs in the master track table.f) What is the maximum stock of any one item held in the catalogue?g) What is the average price and stock held in the catalogue?h) Select the union of all members of Goldfrat and Scandal.i) Select the intersection of all members of Goldfrat and Scandal.j) Select the difference between members of Goldfrat and Scandal.k) Create a view selecting all the members of Scandal.l) Create a view selecting all the members of Goldfrat.m) Select the intersection between these two views.n) Create a Nested query to select the price of the catalogue entry with heighestamount of stock.

o) Create a Nested query to select all buyers that have placed an order.p) Create a view to return the album information for a CD entitled `20 Peoplein a Field’.

q) Now use this view as part of a nested query to select the sequence andfinished tracks release title.

21

2. Scenarios.

Often a buyer will wish to see a list of tracks on an album in the order of theplay list. One such buyer wants to see the play list for a CD called ‘My Feet’. Itis your job to fulfil this request but your manager only wants you to use joins toaccomplish it.

A buyer wishes to purchase a catalogue item but is only allowed to do so if thereis enough stock. At the same time the stock in the catalogue must be updated toreflect this purchase. You should create just one SQL statement to perform bothactivities only updating the catalogue if the item exits and there is enough stock.Use the CD `20 People in a Field’ as your test case.

3. Understanding Triggers.

a) The field duration in the ContractInfo table is derived (you can see this onthe EER and the relational schema). Create a trigger to derive the durationwhen an insertion occurs.

b) Create a new trigger to derive the duration when an update occurs.

c) Bonus Question.

Adding records is a complex activity and creating unique IDs is a task thatwhen performed manually can lead to inconsistencies. To solve this problemyou should create a trigger to add them automatically. You will need tocreate a sequence and then increment that sequence in a trigger. Create yourtrigger on the manager table and then add some records to show it working.

Report (to be handed in at the end of the course)

You must hand in the following:1. Results from the each of the selection statements and those statementsthemselves (7 marks).

2. Results from the each of the scenarios and those statements themselves (2marks).

3. Results from the each of the trigger statements when data is added or updatedand those statements themselves (5 marks).

4. Good Report Style (2 marks).5. Answers to the Bonus Question (4 marks).

22

Friday Exercise (1 session)

Marks: 20 marksEquipment required: Linux PCs using the Oracle DBMS. It should also be possible touseWindows PCs.To be done INDIVIDUALLY.

Purpose

1. To create complex PL-SQL programs.

What you need to do this exercise

You will need to understand, the relational model, how to form SQL Select queries,and how to create and PL-SQL statements.

Directions1. Creating Complex PL-SQL Programs.

i) Create a PL-SQL procedure to make sure the start and end dates of a newcontract are not between the start and end dates of a contract already presentbefore Inserting into ContractInfo. Remember to test that it workscorrectly.

ii) Create a PL-SQL procedure to modify (i) above to make sure the from andto dates are in the correct order. Remember to test that it works correctly.

iii) Create a PL-SQL procedure to wrap the Track list Scenario from Lab 5 in aseparate PL-SQL procedure with 2 input parameters one for the type c, v, ort; and one for the title. Remember to test that it works correctly.

iv) Create a PL-SQL procedure to print the album title too and let the usersearch on sub-strings using wildcards. Remember to test that it workscorrectly.

Report (to be handed in at the end of the course)You must hand in the following:1. Results from the each of the PL-SQL procedures and those proceduresthemselves (4 marks for each procedure).

2. Good Report Style (1 mark for each procedure).

23