26
PRACTICAL 5 Topic Preview/Review 1. What is a view? Discuss the difference between a view and a base relation. 2. Discuss the differences between candidate and primary keys. Create some sample relations to illustrate. 3. a. Define the term 'foreign key'. b. Draw two sample table instances to illustrate the concept of a foreign key. 4. What is the difference between a procedural and a nonprocedural language? How would you classify the relational algebra and relational calculus? 5. The 5 basic relational algebra operations are: selection, Cartesian product, union, projection and set difference. Classify each of these as either unary or binary. Practical Questions 6. Tutors please discuss briefly the use of SQL INSERT statement, as those in the slides for lecture 5 (Introduction to SQL), and the use of SELECT statement, as those in the slides for lecture 6 (SQL - Data Manipulation Language). This week the INSERT SQL data manipulation statement will be explored. 7. During last week's prac session tables were created using the CREATE TABLE SQL statement. You may list all the tables you currently have by clicking the Tables folder on the Object Explorer window, or simply via the following SQL statement SELECT * FROM INFORMATION_SCHEMA.TABLES; 8. The EmployeeDept table created last week contains a column/attribute departmentName of type NVARCHAR(30) which is meant to contain the full department name. This was meant for the simplicity of our initial exercise, and the basic database theory will immediately tell us that this design is not ideal as the field departmentName will be duplicated among many records and data inconsistency may be incurred. The standard way (the process of normalisation which we will cover systematically much later) to solve this problem is to take the (duplicated) attribute departmentName into a separate table. In other words, the table EmployeeDept is decomposed into 2 "linked" tables Department( depId, depName) and Employee( empId, lName, fName, depId * ) via CREATE TABLE Department ( depId char(1) PRIMARY KEY, depName varchar(30) ); CREATE TABLE Employee ( empId nvarchar(6) PRIMARY KEY, lName nvarchar(20), fName nvarchar(20), depId char(1) REFERENCES Department );

PRACTICAL 5 - staff.cdms.westernsydney.edu.au

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

PRACTICAL 5  

Topic Preview/Review1. What is a view? Discuss the difference between a view and a base relation.2. Discuss the differences between candidate and primary keys. Create some sample relations to

illustrate.3.

a. Define the term 'foreign key'.b. Draw two sample table instances to illustrate the concept of a foreign key.

4. What is the difference between a procedural and a nonprocedural language? How would you classifythe relational algebra and relational calculus?

5. The 5 basic relational algebra operations are: selection, Cartesian product, union, projection and setdifference. Classify each of these as either unary or binary.

Practical Questions6. Tutors please discuss briefly the use of SQL INSERT statement, as those in the slides for lecture 5

(Introduction to SQL), and the use of SELECT statement, as those in the slides for lecture 6 (SQL -Data Manipulation Language). This week the INSERT SQL data manipulation statement will beexplored.

7. During last week's prac session tables were created using the CREATE TABLE SQL statement. Youmay list all the tables you currently have by clicking the Tables folder on the Object Explorerwindow, or simply via the following SQL statement

SELECT * FROM INFORMATION_SCHEMA.TABLES;

8. The EmployeeDept table created last week contains a column/attribute departmentName of typeNVARCHAR(30) which is meant to contain the full department name. This was meant for thesimplicity of our initial exercise, and the basic database theory will immediately tell us that this designis not ideal as the field departmentName will be duplicated among many records and datainconsistency may be incurred.

The standard way (the process of normalisation which we will cover systematically much later) tosolve this problem is to take the (duplicated) attribute departmentName into a separate table. In otherwords, the table EmployeeDept is decomposed into 2 "linked" tables Department(depId,depName) and Employee(empId, lName, fName, depId*) via

CREATE TABLE Department ( depId char(1) PRIMARY KEY, depName varchar(30) );

CREATE TABLE Employee ( empId nvarchar(6) PRIMARY KEY, lName nvarchar(20), fName nvarchar(20), depId char(1) REFERENCES Department );

Page 2: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

The attribute depId (marked by *) in Employee serves as a foreign key to table Department(therefore must be a primary key there). The values of depId will still be duplicated among some of therecords but they are the necessary keys and are thus not counted as the data duplication.

9. One can also create the above 2 tables using explicit constraint names.10. We now enter some records to the tables. The INSERT statement is used to add records to tables.

Because the Employee contains a foreign key referencing the table Department, we need to first adddata to table Department

INSERT INTO Department VALUES ('G', 'general'); INSERT INTO Department VALUES ('H', 'hardware');

We then add a few records to Employee as follows.

INSERT INTO Employee VALUES (101, 'News', 'John', 'G'); INSERT INTO Employee VALUES (102, 'Senior', 'David', 'H');

11. The SELECT statement is used to retrieve records from tables. The general syntax of the SELECTstatement is described on page 197 (or 189 for the 5th edition) of the textbook. Referring to the generalform of this statement in the textbook, create a SELECT statement to display all records in theEmployee table.

SELECT * FROM Employee;

12. Your turn to finish filling the tables so that

a. Add 3 more records to the Employee table using the fName 'David' for at least one record.

INSERT INTO Employee VALUES (111, 'First Extra', 'David', 'G'); INSERT INTO Employee VALUES (112, 'Second Extra', 'David', 'H'); INSERT INTO Employee VALUES (113, 'Third Extra', 'David', 'G');

b. Retrieve the fName and lName for all records for those employees with an fName value of'David', refer to page 199 (or 191 for the 5th edition) of the textbook for an example.

Page 3: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

SELECT fname, lname FROM Employee WHERE fname = 'David';

13. Use the INSERT statement to add the following record to the Employee table:

INSERT INTO Employee VALUES (102, 'Senior', 'Sally', 'H');

What happens when you try to add this record? Why?14. Optional: Alternative examples on the creation of foreign keys and the insertion of records in SQL

are also available in the next week's practical for the data preparation of a Hotel database (availableafter the prac for the next week is done). This question therefore should better be considered as arevision question.

15. Optional: SQL Server Visual Track 2 - Keys and SQL of GUI actions (note: students may jumpto complete the additional exercises first if they wish)

In this part we will "visually" re-create 2 linked tables Department and Employee on MicrosoftSQL Server, link them together via the foreign key, and export the SQL statements that would achievethe same results of these GUI activities.

a. If you have already created tables Department and Employee, let us remove themfirst via GUI (instead of using the DROP command in SQL). Because Employeereferences Department, we have to remove Employee before removing Department.Otherwise the removal requests will fail.

Page 4: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

If you tried to remove Department table first, you would see a dependency tree comingout of Department, and that dependency tree is the reason of the removal failure

b. Now we visually create tables Department and Employee. Similar to the reasons onhaving to remove Employee before Department, we have to create Department beforecreating Employee (the opposite order). We thus first create table Departmentfollowing the procedure (to create Hotel) in visual track 1 and then create tableEmployee likewise, see

Page 5: PRACTICAL 5 - staff.cdms.westernsydney.edu.au
Page 6: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

bearing in mind that the foreign key (Employee.depId) is not set yet.

c. To set the foreign key, right click on the keys icon under the table on the Object Explorerpane, select New Foreign Key...

Page 7: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

to reach

Noticing that the foreign key was incorrectly set to empId, we click the "..." button toreach

Page 8: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

which will be changed to

to reflect the fact that depId is the foreign key. Click OK and then Close. Then SaveEmployee (from e.g. the File menu item). You will be prompted with

Page 9: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

Clicking Yes completes the job.

d. To confirm the foreign key, Refresh the View to observe the foreign key entry

Alternatively, right click Database Diagram as in

Page 10: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

select New Database Diagram and then select the 2 tables as in

Clicking Add and then Close will take us to the diagram

Page 11: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

This diagram illustrates the presence of a foreign key.

e. Again similar to the procedure (to enter records into Hotel) in visual track 1, we firstenter the records into Department, and then enter the initial records and the additionalrecords into Employee.

f. To view the records of table Department, right click the table name in Object Explorerpane on the left, select Select Top 1000 Rows to display the records directly

Page 12: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

or select Script Table as then SELECT To then New Query Editor Window, i.e.

to get

Page 13: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

Further clicking the ! Execute icon gets

which displays all the records for the Department table.

Page 14: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

g. Likewise table Employee can be shown to contain the following records

h. Suppose you have already created tables and enter records into those tables via thegraphical user interface, how can you "reverse-engineer" and find the SQL statementswhich would achieve exactly the same you did in GUI?

First we export the SQL statements which can be used to create the table Departmentby going through Script Table as then CREATE To then New Query Editor Window, i.e.

Page 15: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

to obtain

where essentially the highlighted part (plus a closing round bracket) does the main jobfor the table creation while the rest of the code is largely house-keeping.

Page 16: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

i. Do the same for Employee we get

We observe that a separate ALTER statement was used to create the foreign key, see thehighlighted part.

j. Now we want to export the records for the tables. On the Object Explorer pane on theleft, right click the database name (here zhuhan is the name of my database and you willhave yours). Select Tasks then Generate Scripts...

Page 17: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

to reach

Page 18: PRACTICAL 5 - staff.cdms.westernsydney.edu.au
Page 19: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

k. Click Next to continue and select explicitly the tables you want to export in SQL

Page 20: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

l. Click Next to reach the next screen and select Save to new query window for convenience

Click also Advanced to configure Types of data to script to Schema and data (or Dataonly if you prefer)

Page 21: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

Then click OK to move back, and click Next to reach the summary

Page 22: PRACTICAL 5 - staff.cdms.westernsydney.edu.au
Page 23: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

m. Click Next and wait for the whole process to complete with the screen

n. Click Finish to finish the job. The generated script is now contained in a new querywindow

o. The generated schema and data (for 2008 R2) or that for 2012 SSMS can be used tocreate the same tables elsewhere. If I had chosen Data only for the Types of data to scriptearlier on, I would get only the table data (for 2008 R2) or that for 2012 SSMS.

Page 24: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

Please note that the format of the generated SQL will typically look somewhat differentfrom how a human would write, because the auto-generated code often supply manydefault parameters explicitly.

16. Create, or just read to understand, the tables for the DreamHome schemas at page 197 (or 189 for the5th edition), filled with the data at page 160 (or 152 for the 5th edition)

Schemas adapted from the textbook (page 159 or 197 for the 6th edition and page 151 or 189 for the5th) for DreamHome:Branch(branchNo,street,city,postcode) Staff(staffNo,fName,lName,position,sex,DOB,salary,branchNo) PropertyForRent(propertyNo,street,city,postcode,type,rooms, rent,ownerNo,staffNo,branchNo) Client(clientNo,fName,lName,telNo,prefType,maxRent,eMail) PrivateOwner(ownerNo,fName,lName,address,telNo,eMail,password) Viewing(clientNo,propertyNo,viewDate,comment)

ConstraintsConstraints are rules that restrict the data values that you can enter into a field in a database table.

There are 2 types of constraints:

1. Integrity Constraints, which define primary and foreign keys2. Value Constraints, which define specific data values or ranges that can be entered into fields.

Value constraints also indicate if a field can contain a null value or if it must be unique.

There are 2 levels of constraints:

1. Table constraints, these limit the field values with respect to other values in the table eg. aprimary key constraint is a table level constraint because a field value must be unique and cannot appear in this field in more than one table record.

2. Field constraints, limits the value that can be used in a field regardless of that field existingin another table record. Eg. a GENDER field may have a constraint that indicates only M and Fare acceptable values.

Constraints can be placed at the end of the CREATE TABLE statement or the constraint can beplaced in the field definition, immediately following the field declaration.

PRIMARY KEY CONSTRAINT

The general syntax for defining a primary constraint within a field declaration is:

CONSTRAINT constraint_name PRIMARY KEY

The general syntax for defining a primary constraint at the end of the CREATE TABLE command is:

CONSTRAINT constraint_name PRIMARY KEY (fieldname)

Every constraint in the user schema must have a unique constraint name.

FOREIGN KEY CONSTRAINT

Foreign keys can be defined within the field definition or at the end of the CREATE TABLEstatement.

Page 25: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

The general syntax for specifying at the end of the CREATE TABLE command is:

CONSTRAINT constraint_name FOREIGN KEY (fieldname) REFERENCES primary_key_table_name (primary_key_field_name)

The general syntax for specifying in the field definition is:

CONSTRAINT constraint_name REFERENCES primary_key_table_name (primary_key_field_name)

Read through sections 7.2.3 and 7.2.4 of the textbook for more details

Additional Exercises

α. Describe briefly a database application case of your choice and represent your data in terms of 3linked (via foreign key/s) tables. List their respective primary key and foreign key/s if any. Yourdatabase application case should be different from those already covered in the lectures orpracticals. Hint: You may re-examine the ER diagram in Q.α of the additional questions in theprevious practical. Insert proper primary keys and foreign keys in your previous ERD if they werenot all there yet. Then your own case and ERD for the current question could be pretty much verysimilar, albeit with a somewhat different business scenario.

β. For the database case in the Additional Exercises of the previous practical, complete the properconstruction of all the relevant tables in SQL, building all the pertinent primary and foreign keysthere.

a. Enter records to ensure that each of the 3 tables Book, User and Borrows contains atleast 3 records. At least one of the records for each table is entered via the INSERTstatement in SQL.

b. Write the SQL script that would generate the above 3 tables.

c. If a table has a foreign key, at least 1 record there should have no null values for theforeign key. Use SQL or GUI to display all the records for all the 3 tables, and get theircorresponding screen shots. All screen shots need to contain the user name to prove thatthey are yours, similar to the part in the red circle in this example of the previous practical.

Hints: Compare User, Borrows, and Book with Client, Viewing andPropertyForRent in the DreamHome example in this prac. Compare also with Vocalist,Performs and Song in Practical 3, and see how their corresponding tables are generated.

Page 26: PRACTICAL 5 - staff.cdms.westernsydney.edu.au

ACKNOWLEDGEMENT: This document may have included excerpts from the prescribed textbook by Thomas Connolly and Carolyn Begg, and isalso based on an earlier delivery some years back at WSU by Dr Eshan Vossough who may have in turn made use of other contributors' work.

Compiled and typeset by Zhuhan Jiang @2021.