Database Handbook

74
Semester B - 2013 School of Architecture, Computing and Engineering Module Title: Database Systems Module Code: SD2052 Level 2 Semester B Module Leader: Juliette Alfred-Lewars Email: [email protected] Tel: +44 (0)20 8223 2302 Room: EB G36

description

Database Handbook, Codes and PL SQL

Transcript of Database Handbook

Page 1: Database Handbook

Semester B - 2013

School of Architecture, Computing and Engineering

Module Title: Database Systems

Module Code: SD2052

Level 2 Semester B

Module Leader: Juliette Alfred-Lewars

Email: [email protected]

Tel: +44 (0)20 8223 2302

Room: EB G36

Page 2: Database Handbook

Semester B - 2013 2

Have your say! Help to shape UEL now and in

the future!

During the course of the year you will have opportunity to give feedback

about your course, campus and other aspects of your university

experience.

If you are a first or second-year undergraduate, or are on a taught

Master’s degree then you can take part in UEL’s Tell Us What You Think

Survey. This takes place in Semester A and aims to find out what you

think about your course and life at UEL.

If you are a final-year undergraduate you will be eligible for the National

Student Survey. Held annually between January and April, this is a

national survey covering all universities in the UK. You will receive

information about it once the survey has begun, and there will be plenty of

publicity around campus. It’s really important that you take part in this

survey; as it’s a chance to share your UEL experience, help potential

students in their choice of where to study and improve UEL for future

students.

Both surveys are really important as they help UEL to evolve and improve

the student experience for all our students.

Look out for the publicity around campus and have your say – your opinion counts!

Page 3: Database Handbook

Semester B - 2013 3

Keep in touch!

There are plenty of ways to keep in touch with what’s happening at UEL.

You can:

• follow us on Twitter twitter.com/UEL_News

• join our Facebook group facebook.com/universityofeastlondon

• your Universe, UEL’s own student e-zine uel.ac.uk/universe – your one stop shop

for new, events, opportunities, announcements, entertainment and more …

• UELDirect noticeboard – check regularly for news, events and opportunities

• UELSU – www.uelunion.org – for your representatives, societies and advice

The QR code below will take you to the Events page on the UEL website,

or you can go direct to uel.ac.uk/events

Page 4: Database Handbook

Semester B - 2013 4

Contents

1. MODULE SPECIFICATION .................................................................................... 5

2. INTRODUCTION .................................................................................................. 9

3. AIMS .................................................................................................................... 9

4. TEACHING AND LEARNING METHODS ............................................................... 9

4.1. LECTURES, TUTORIALS AND PRACTICALS ..................................................................... 9

5. ASSESSMENT ..................................................................................................... 10

6. LECTURE PLANS ............................................................................................... 10

6.1. SUMMARY ..................................................................................................................... 10 WEEK 1 – LECTURE: INTRODUCTION .................................................................................... 12 WEEK 2 – LECTURE: DATA MODELLING .............................................................................. 13 WEEK 3 AND 4 – LECTURE: RELATIONAL MODELLING ..................................................... 14 WEEK 5 – LECTURE: NORMALISATION ................................................................................. 15 WEEK 6 AND 7 – LECTURE: STRUCTURED QUERY LANGUAGE (SQL) ............................ 16 WEEK 8 – LECTURE: QUERY OPTIMISATION ....................................................................... 17 WEEK 9 – LECTURE: TRANSACTION, CONCURRENCY AND RECOVERY ........................... 18 WEEK 10 – LECTURE: SECURITY, INTEGRITY AND ETHICAL ISSUES ................................. 19 WEEK 11 – LECTURE: NETWORK AND DISTRIBUTED SYSTEMS ....................................... 20

7. TUTORIALS........................................................................................................ 22

WEEK 1 – TUTORIAL: INTRODUCTION .................................................................................. 22 WEEK 2 – TUTORIAL: DATA MODELLING ............................................................................. 23 WEEKS 3 – TUTORIAL: CASE STUDIES .................................................................................... 24 WEEKS 4 – TUTORIAL: CASE STUDY ....................................................................................... 26 WEEK 5 – TUTORIAL: NORMALISATION................................................................................. 27 WEEK 6 – TUTORIAL: SQL QUESTIONS ................................................................................. 29 WEEK 7 – TUTORIAL: ADVANCED SQL QUESTIONS ........................................................... 31 WEEK 8 – TUTORIAL: QUERY OPTIMISATION ...................................................................... 34 WEEK 9 – TUTORIAL: TRANSACTION, CONCURRENCY & RECOVERY .............................. 35 WEEK 10 – TUTORIAL: INTEGRITY AND SECURITY .............................................................. 36 WEEK 11 – TUTORIAL: DISTRIBUTED DATABASE ............................................................... 37

8. PRACTICALS ...................................................................................................... 39

WEEKS 1 – 3 PRACTICALS: INTRODUCTION TO ORACLE ............................................... 39 WEEKS 4 - 7 PRACTICALS: INTRODUCTION TO SQL ....................................................... 49 WEEKS 7 - 11 PRACTICALS: SQL QUESTIONS................................................................... 55

TOPIC 6 AND 7 – SQL SUPPORTING MATERIAL ........................................................ 58

STUDENT ACADEMIC CALENDAR FOR 2012/2013 ............................................................... 73

Page 5: Database Handbook

Semester B - 2013

1. Module Specification

Module Title: Database Systems

Module Code: SD2052 Level: 2 Credit: 20 ECTS credit:

Module Leader:

Juliette Alfred-Lewars Email: [email protected]

Co-Leader

Naveed Hamid Email: [email protected]

Pre-requisite: None Pre-cursor None

Co-requisite: None Excluded Combination: None

Skills module: No University-wide option: No

Location of delivery: UEL

Main Aim(s) of the Module:

To provide an understanding of methods of data organisation and retrieval

Main Topics of Study:

• Data system concepts

• Data modelling techniques (Entity Relational Modelling and Normalisation)

• Data organisation and retrieval techniques

• Managing organisation’s data

• Data administration and tools

• Security, integrity and ethical issues in DB design

• Integrity Constraints

• Structured Query Language

• Query optimisation

• Distributed database

• Transaction management

• Recovery management

Learning Outcomes for the Module At the end of this Module, students will be able to: Knowledge

1. Identify and implement database models 2. Contrast and compare a variety of database technologies 3. Cite relevant legislation relating to issues such as Data Protection, Privacy and

Copyright Thinking skills

4. Discuss and select a suitable data management system for managing an organisation’s data

Page 6: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 6

Subject-based practical skills

5. Identify and implement database models 6. Examine and design a data model for an organisation 7. Select and construct different methods of organising files to ensure efficient

storage and retrieval 8. Program and implement database solutions using basic SQL statements

Skills for life and work (general skills)

9. Demonstrate good time management as a team, in the application of problem solving techniques in relation to database management.

Teaching/ learning methods/strategies used to enable the achievement of learning outcomes: Lectures/tutorials/practical sessions/workshops Assessment methods which enable students to demonstrate the learning outcomes for the module: Design and implement a database system Examination (1hr 30 minutes)

Weighting: 50% 50%

Learning Outcomes demonstrated 1, 5-8 1-4

Indicative Reading for this Module: Core:

Peter Rob, Carlos Coronel, and Steven Morris, Keeley Crockett, (2013), Database Principles, Fundamentals of Design, Implementation & Management – 2nd Edition, Cengage Learning, ISBN: 13: 978-1-4080-4863-4

Peter Rob, Carlos Coronel and Steven Morris, 2013, Database Principles: Fundamentals of Design, Implementation, and Management, 10th Int. Ed., Cengage Course Technology Learning EMEA. ISBN: 978-1-133-31197-3 or ISBN: 1-133-31197-0

Bijoy Bordoloi and Douglas Bock, Oracle SQL, 2004, Pearsons Education LTD, Prentice Hall. ISBN: 0-13-101138-3 MATA-TOLEDO, R. A. AND CUSHMAN, P. K., 2000, Fundamentals of SQL Programming. Schaum’s Outlines Recommended

Thomas M. Connolly and Carolyn E. Begg, “Database Systems: A Practical Approach to Design, Implementation and Management”, 5/E, Pearson/Addison Wesley, 2010, ISBN-10: 0321523067 or ISBN-13: 9780321523068

Page 7: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 7

Page 8: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 8

Indicative Teaching and Learning Time (10 hrs per credit):

Activity

Student/Tutor Contact Time: 24 hours 24 hours 10 hours

Activity: (e.g. lectures/seminars/tutorials/workshops/studio work etc) Lectures (11*2 hours + 2 hr revision) Tutorials/practicals Workshops and student presentations assessment

Student Learning Time: 142 hours

Activity: (e.g. seminar reading and preparation/assignment preparation/ background reading/ group work/portfolio/diary etc ) Private study

Total hours:

200 hours

Page 9: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 9

2. Introduction

This is a 2

nd level Module within the School of Architecture, Computing and

Engineering subject area. It is a mandatory requirement for all undergraduate

Computing and Business Information Systems programmes.

This module complements the level 2 modules in the Modular Scheme and has

links with the Systems Analysis module. Where the Systems Analysis module

gives a broad sweep of systems analysis ideas and methodologies, the Database

Systems module focuses on the design, concepts, processing and implementation

issues of Database Management Systems.

3. Aims

To promote a knowledge and understanding of

• Database system terminology and the role of the database management

system

• Data Modelling

• Methods of organising files such that data can be stored and retrieved

efficiently

• The Relational Model

• Structured Query Language

• Tools and techniques employed by a Database Management System

such as Query Optimisation, Recovery, Concurrency and Security

4. Teaching and Learning Methods

4.1. Lectures, Tutorials and Practicals

There will be 2 hours of lectures per week at which the whole class attend, and 2

hours of tutorial/practical for each of the tutorial groups into which the class will

be divided. Students will be expected to take adequate notes from lecture

presentations.

Page 10: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 10

5. Assessment

The assessment for this module is in two parts.

Part 1: Groups of threes Practical Task (Coursework) = 50%

You will be required to form groups of THREEs only, to develop the case study

by implementing an agreed design in Oracle. Your group will be expected to

identify the management needs of the organisation, design and implement a

realistic database system and develop a range of SQL queries based on the case

study to be given using only ORACLE.

Part 2: 1 ½ hour written examination = 50%

There will be a One hour 30 minutes written examination at the end of the

module. The questions will be based on lecture topics.

6. Lecture Plans

6.1. SUMMARY

Week Starting

Lecture

Tutorial

Practical

Week 1

Introduction to DBMS: What is a database and database management system

Tutorial Questions Accessing Oracle - Creating tables

Week 2

Data Modelling the ER Model (continued) (Assignment handed

out)

Tutorial Questions and sample case studies

Accessing Oracle - Creating tables

Week 3

Design: Relational Model

Tutorial Questions and sample case studies

Accessing Oracle - Creating tables

Week 4

Design: Relational Model (continued)

Tutorial Questions and sample case studies

Accessing Oracle - Creating tables and Introduction to SQL (10 questions)

Week 5

Normalisation Tutorial Questions

Continue from previous week

Page 11: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 11

Week Starting

Lecture

Tutorial

Practical

Week 6

Structured Query Language (SQL)

Tutorial Questions 10 and 30 SQL questions

Week 7

Structured Query Language (SQL) Advanced (Assignment Part 1 submission during tutorial for feedback)

Tutorial Questions 30 SQL questions

Week 8

Query Optimisation Tutorial Questions

30 SQL questions

Week 9

Transaction, Concurrency and Recovery

Tutorial Questions

30 SQL questions and working on assignment

Week 10

Integrity, Security, Legal and ethical Requirements

Tutorial Questions

30 SQL questions and working on assignment

Week 11

Network and Distributed Database Systems

Tutorial Questions

30 SQL questions and working on assignment

Week 12

Revision Week

Week 13

Exams (Date to be advised)

Page 12: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 12

Week 1 – Lecture: Introduction

Topic 1

Subject INTRODUCTION

Aims To introduce the module.

To provide a broad introduction to the concepts of database

systems

Learning Objectives By the end of this topic the student should be able to:

* understand the structure of the module, the topics to be

covered and the course assessment criteria

* History of database Systems

* compare and contrast the integrated database

environment with the traditional file processing

environment

* describe briefly the functions of a DBMS

* be able to critically evaluate the types of DBMS

* give definitions and discuss terms such as:

file, record, field,

data languages,

intension and extension of a database

Note: The functions of a DBMS will be revisited at the end of

the course when the student has acquired further knowledge of

DBMSs

Tutorial Address any questions arising from the lecture

Essential/Required

Reading

Rob and Coronel Chapter 1, Chapter 2 (2.4)

Other Reading Date Chapters 1, 2, 3

Connolly and Begg Chapters 1, 9-11

Ritchie chapter 1

Page 13: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 13

Week 2 – Lecture: Data Modelling

Topic 2

Subject DATA MODEL

Aims To develop an in-depth understanding of what is meant by a

‘Relational Model’

Learning Objectives By the end of this topic the student should be able to:

* gain an understanding of the ideas underlying relational

systems

* describe the fundamental characteristics of relational

systems

* describe the characteristics of relation tables

* what business rules are and how they influence

database design

* how the major data models evolved

* gain an understanding of the evolution of databases

and the ideas underlying relational systems

* How data models can be classified by level of

abstraction

* describe Codd’s criteria for determining how

relational a DBMS is

Tutorial Evaluation of Codd’s rules

Essential/Required

Reading

Rob and Coronel Chapter 2

Other reading Ritchie Chapter 2, 3 and 4.

Ramakrishnan and Gehrke, Chapter 3

Date, Chapters 4 and 9

Connolly & Begg, Chapter 2

Page 14: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 14

Week 3 and 4 – Lecture: Relational Modelling

Topic 3 and 4

Subject RELATIONAL MODELLING

Aims To enable the student to model data requirements using Entity-

Relationship modelling

Learning Objectives By the end of this major topic, students should be able to

• explain the terms

tuple

cardinality

attribute

degree

primary, composite and foreign keys

domain

• represent entities, attributes and relationships on an

E-R diagram

• explain the meaning and purpose of entity and

referential integrity rules

• provide examples of one-to-one, one-to-many, and

many-to-many relationships

• understand optionality

Tutorial Exercises from Entity-Relationship Modelling

Essential/Required

Reading

Rob and Coronel Chapters 3 and 4

Other reading Ritchie, Chapter 2, 3 and 4.

Connolly & Begg, Chapters 3 and 4

Ramakrishnan and Gehrke, Chapter 2

Date, Chapters 3 and 5

Page 15: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 15

Week 5 – Lecture: Normalisation

Topic 5

Subject NORMALISATION

Aims To develop an in-depth understanding of why and how

relations should be normalised

Learning Objectives By the end of this topic the student should be able to:

* establish reasons why relations should be normalised

* define 1st Normal Form and explain how to achieve it

* understand the meaning of full functional dependency

* define 2nd Normal Form and explain how to achieve it

* understand the meaning of transitive dependency

* define 3rd Normal Form and explain how to achieve it

* define BCNF and explain how to achieve it

Tutorial Exercises on Normalisation

Essential/Required

Reading

Rob and Coronel Chapter 5

Other reading Ritchie, Chapter 5.

Ramakrishnan and Gehrke, Chapter 19

Connolly & Begg, Chapters 13

Date, Chapter 11

Page 16: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 16

Week 6 and 7 – Lecture: Structured Query Language (SQL)

Topic 6 and 7

Subject STRUCTURED QUERY LANGUAGE (SQL)

Aims To enable the student to create and maintain tables (DDL) and

formulate a variety of database queries using SQL constructs

(DML).

Learning Objectives By the end of this topic, students should be able to understand

and apply SQL constructs for:

* Placing integrity constraints

* creating and dropping tables

* retrieving data using the SELECT including:-

multiple conditions

asterisk notation

LIKE

BETWEEN

ALIASES

AGGREGATE FUNCTIONS

GROUP BY

HAVING

ORDER BY

JOINS

ANY and ALL

SUBQUERIES

* updating, deleting and inserting records

* setting up primary and foreign keys

* providing security using views, GRANT and

REVOKE

Tutorial SQL Exercises

Essential/Required

Reading

Colin Ritchie, Chapter 13

R.Sunderraman, Chapter 2

Ramakrishnan and Gehrke, Chapter 5

http://sqlcourse.com/intro.html

Page 17: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 17

Week 8 – Lecture: Query Optimisation

Topic 8

Subject QUERY OPTIMISATION

Aims To introduce the student to the reasons for optimisation and the

techniques used for achieving efficient system performance.

Learning Objectives By the end of this topic, students should be able to:

* understand the need for query optimisation and what an

optimiser is

* construct Query trees to represent relational algebra

expressions involving SELECT, PROJECT and JOIN

* identify equivalent algebraic and SQL expressions

* contrast the efficiency of queries in which SELECT

operations are performed early

* explain why the joins should be performed on the

smallest tables

* identify some cost factors involved in selecting the

optimum execution plan

Tutorial Exercises on Query Optimisation

Essential/Required

Reading

Rob and Coronel chapter 10, pages 490-492

Other reading Connolly & Begg, Chapter 20

Date, Chapter 17

Page 18: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 18

Week 9 – Lecture: Transaction, concurrency and recovery

Topic 9

Subject TRANSACTION, CONCURRENCY and RECOVERY

Aims To develop the students’ understanding of the need for and

methods of:

(a) restoring a database following a ‘fault’

(b) controlling multi-user access to databases

Learning Objectives By the end of this topic, students should be able to:

• understand the notion of a transaction

• define recovery and the need for it

• describe the steps in recovery

• explain checkpoints, log files, updates

• define concurrency and the need for it

• explain the need for shared and exclusive locks

• explain how deadlocks are detected and broken using

wait-for graphs

• describe levels of locking

Tutorial Exercises on Concurrency and Recovery

Essential Reading Rob and Coronel chapter 9, pages 437-464

Other reading Colin Ritchie pages 160 - 170

Connolly & Begg, Chapter 19

Date, Chapters 14 and 15

Page 19: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 19

Week 10 – Lecture: Security, integrity and ethical issues

Topic 10

Subject SECURITY and INTEGRITY

Aims To expose students to the need for and the methods of achieving

database security.

To further develop an understanding of the importance of

integrity constraints

Learning Objectives By the end of this topic, the student should be able to:

* distinguish between security and integrity

* provide examples of deliberate and accidental threats

to databases

* describe methods of providing security

* further describe how views provide security

* explain what type of views are updatable

* describe what and how integrity constraints could be

expressed and enforced

* Ethical and legal issues in design of database systems

Tutorial/Practical Exercises on Security and Integrity

Essential/Required

Reading

Handbook for topic 10

Other reading Connolly & Begg 2nd

ed, Chapter 16

Page 20: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 20

Week 11 – Lecture: Network and Distributed Systems

Topic 11

Subject Network & Distributed Systems

Aims To understand networked and distributed systems:

The use of networked databases and specifically, techniques for

distributing a database over several computers.

Learning Objectives By the end of this major topic, the student should be able to:

* Client-Server systems

* Distributed databases

* Advantages and disadvantages of distributed databases

* Other network technologies

* ODBC

* JDBC

* Database4s on the Web

Tutorial Exercises on Network and Distributed Databases

Practical Work on 2nd

assignment

Essential/Required

Reading

Page 21: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 21

Page 22: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 22

7. Tutorials

Week 1 – Tutorial: Introduction

Tutorial Week 1 – Review Lecture and demonstration of Oracle Practical (Oracle 9i)

A. Review lecture content

1. Understand the structure of the module, the topics to be covered and the course assessment criteria.

2. Discuss what a database is, the different types of databases, and

why they are valuable assets for decision making.

3. Why database design is important.

4. Describe briefly the functions of a Database Management System (DBMS)

5. Give definitions and discuss terms such as:

• What is redundancy and inconsistency?

• file, record, field, data languages

B. Tutor - class demonstration on how to use Oracle (preparation for the practical session - to follow the demonstration, turn to page 29).

** Talk with students on the implications of late and early submission of assignments? **

Page 23: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 23

Week 2 – Tutorial: Data Modelling

WEEK 2: DATA MODELLING 1. What is an Entity Relationship Model (ERM), what are the three main

components and why is it important in database design?

2. What are business rules and why is it important in respect of data modelling?

3. How would you translate business rules into data model components?

4. Write the business rules for the relationships depicted in the UML ERM below.

5. Create a UML ERD for the following scenario. (Note: The word many

merely means “more than one” in the database modelling environment.)

“A customer can rent many videotapes from the UEL Video store. Each of the videotapes can be rented to many customers during that period of time.”

6. What is a Relation with regards to Relational database and what are its

basic constructs?

7. What is the “Relational Oath” and why is it important?

8. Discuss the different types of database architecture.

9. Evaluate and explain Codd’s twelve rules for determining how relational database management system (DBMS) is.

Page 24: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 24

Weeks 3 – Tutorial: Case Studies

Working in groups of 4s (based on size of tutorial class could be more) please do the following:

A. Discuss the following questions:

1. Name the relational keys and describe their functions in Relational databases?

2. List and discuss the importance of the properties of Relations?

3. What is Data Integrity? List and discuss the integrity rules in relational

database?

--------------------------------------------------------------------

B. Design a UML Entity Relationship

From the case study below, draw a UML Entity Relationship Model, identify all entities, relationships, multiplicity, primary and foreign keys and list some

attributes for the following case study. Present your ER solution to the class.

SCENARIO 1

FORD Cars

Ford is an organization that makes many models of cars, where a model

is characterised by a name and a suffix (such as GL or XL which

indicates the degree of luxury) and an engine size.

Page 25: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 25

Each model is made up of many parts and each part type may be used in

the manufacture of more than one model. Each part has a description

and an ID code. Each model of car is produced at just one of the firm’s

factories, which are located in London, Birmingham, Bristol,

Wolverhampton and Manchester - one in each city. A factory produces

many models of car and many types of parts although each type of part is

produced at one factory only.

Page 26: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 26

Weeks 4 – Tutorial: Case Study

Working in groups of 4s (based on size of tutorial class could be more) from the case study below, draw a UML Entity Relationship Model, identify all entities, relationships, multiplicity, primary and foreign keys and list some attributes for

the following case study. Present your ER solution to the class.

SCENARIO 2

UNIVERSITY OF DAGENHAM

The University of Dagenham consists of several branches. Within each

branch there are several departments. Each department may run a

number of courses. All teaching staff is attached to departments, each

staff member belonging to a unique department. (Note: see if you can

see the ambiguity in the last clause). Every course is composed of sub-

courses. Some sub-courses are part of more than one course. Staff

may teach on many sub-courses and each sub-course may be taught by

a number of staff.

Page 27: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 27

Week 5 – Tutorial: Normalisation

Week 5: NORMALISATION

Objectives of Normalization

• To act as a ‘bottom-up’ alternative to E-R modelling

• To act as a check on the results obtained by E-R modelling.

• To act as a more precise method of resolving data modelling problems.

• To depend less on intuition than E-R modelling.

• To be useful when it is required to redesign existing ‘problem’ files.

• To eliminate or control data redundancy.

• To eliminate insertion, deletion and update anomalies.

In a normalized database or file collection, every table or file contains data facts about just one entity type; every record or row contains data facts about one entity.

1. Describe with examples, the steps in reducing a data set to third normal

form.

2. The table below show some occurrences for the entity PATIENT. Normalise

the data showing clearly each step involved.

a. When normalising keep the following assumption in mind: “A given consultant is only available on certain dates”. You can also state any other assumptions, indicate the key fields and functional dependencies.

Page 28: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 28

Patient number

Patient name

Patient age

G.P. number

G.P. name

Date of Hospital Treatment

Const ID

Consultant name

Consultant Room number

Sample required

P1 D Adams 20 G1 T Wolfe 03.06.06 05.06.06 10.10.06

C3 C3 C1

A Willis A Willis T Brown

1053 1053 1070

Blood None Urine

P2 G Green 37 G2 L Peach 03.06.06 10.06.06

C3 C10

A Willis T Brown

1053 1070

Sputum Blood

P3 P Orton 29 G3 V Green 09.10.06 C2 J Keen 1067 Blood P4 V William 83 G2 L Peach 09.06.06 C2 J Keen 1067 Urine P5 N Dean 102 G3 V Green 10.06.90 C10 T Brown 1070 Sputum

Page 29: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 29

Week 6 – Tutorial: SQL Questions

Week 6: Structured Query Language (SQL)

What would be the required SQL for the following queries? 1. List all the employees whose salary is between 1000 and 2000. Show employee name, department number and salary. Example answers given below for questions 1 and 2.

ENAME DEPTNO SAL

ALLEN 30 1600

WARD 30 1250

MARTIN 30 1250

TURNER 30 1500

ADAMS 20 1100

MILLER 10 1300

2. Display all the different types of occupations. Example answer below.

JOB

ANALYST

CLERK

MANAGER

PRESIDENT

SALESMAN

3. List details of employees in departments 10 and 30. 4. Display all employees who were recruited during 1983, giving their name,

department and hire-date. 5. List the names and jobs of all clerks in department 20. 6. List the employees whose names have TH or LL in them.

Page 30: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 30

7. List the department numbers, name and the location in department name order.

8. Find the name and salary of employees in Dallas. 9. List in order of department number, the department number, employee

name and salary increased by 15% and expressed as a final whole figure. 10.a List all employees and their managers numbers. 10.b The hard bit. As above but list their managers' names as well as their

numbers. 10.c List the employee's name and salary and manager's name and salary for all employees who earn more than their managers.

Page 31: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 31

Week 7 – Tutorial: Advanced SQL Questions

Week 7: Advanced Structured Query Language (SQL)

What would be the required SQL for the following queries? 1.

Select everything from the Dept table.

2.

Select the employees in name order.

3.

Select all the employees who work in department 20.

4. List name and salary of all the salesmen.

5. Find all the employees earning more than £1500.

6. Find all the employees earning £1500 or more.

7. Find all the employees whose commission is greater than their salary.

8. List all the salesmen that earn more than £1500

9. List all the salesmen in department 30 who earn £1500 or more.

10. List the president and managers.

Page 32: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 32

11. List all the managers who are not in

department 30.

12. List every manager and the clerks in department 10.

13. List the managers and clerks that work in department 10.

14. Find everyone who is neither a manager nor a clerk, but is in department 10

15. List all the other emps who do not earn between £1000 and £2000

16. List all the clerks, salesmen and analysts.

17. List all the employees who are not the above.

18. List all employees who do not receive commission.

19. List all employees who receive commission.

20. List all the employees and their departments names.

Page 33: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 33

21. List all the departments and their employees names.

22. Find Jones job.

23. List the name and job of employees with the same job as Jones.

24. Find the employees that earn more than ANY employees in department 30.

25. Find the employees that earn more than ALL employees in department 30.

26. Find all the employees in Dept 10 that have a job that is the same as anyone in department 30.

27. List the name, job and salary of employees who have the same job and salary as Ford.

28. List the name, job and department of employees who have the same job as Jones or a salary greater than or equal to Ford.

29. Give a count of the number of employees by department number.

30. Give a count of the number of employees by department number which have more than 4 employees

Page 34: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 34

Week 8 – Tutorial: Query Optimisation

Week 8: Query Optimisation

1 What is database performance tuning and what is its importance in

respect of client interaction with the database?

2 Why is the subject of query optimisation very important in Relational

Databases?

3 The database processes queries in three phases. What are those

phases, and what is accomplished in each phase?

4 State the two main query optimisation approaches and describe them.

5 State the order of execution of a query and describe how queries are

translated and executed by the DBMS?

6 What is a query tree? Draw a normal “un-optimised/fully equivalent”

query tree for the following SQL statement:

SELECT StudentNo, Name FROM Student, Course WHERE Student.StudentNo = Course.StudentNo and Course.Description = ‘Java’ and Student.Name in ‘% A’; Assuming there is a One to Many relationship between Student and Course entities.

Draw an “optimised/more efficient” query tree for the above SQL statement.

Page 35: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 35

Week 9 – Tutorial: Transaction, Concurrency & Recovery

Week 9: Transaction, Concurrency and Recovery

1. What is a transaction with regards to Relational Database?

2. List and describe the set of instructions that are executed by a database

transaction

3. What are the two generic operations used by the DBMS to manage a

transaction?

4. List and describe the States and outcomes of a transaction.

5. Describe and explain the ACID properties of a transaction

6. Concurrency is an important feature of transaction processing, what is it and

why is it necessary?

7. Discuss with examples, some of the problems associated with concurrency.

8. Describe the major technique used in concurrency control.

9. Explain given examples the difference between:

a. Implicit and explicit locks

b. Shared and Exclusive locks

10. What is a dead-lock? How is it detected and how is it resolved?

11. What is recovery in database management? List and discuss the type of

failures that may necessitate recovery.

12. What is the purpose of a log file. Explain how the log file can assist in

maintaining a consistent database in the event of a failure.

Page 36: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 36

Week 10 – Tutorial: Integrity and Security

Week 10: Integrity and Security 1. The DBA creates rules know as integrity constraints. Referential integrity

constraints insist that a value appearing as a foreign key in one table must be matched by values in a primary key of another table. What about NULL values, we know that a null value cannot exist in a primary key, but what do we want to say about NULLs existing as foreign keys.

2. What are the differences and similarities between Integrity and Security of a

database system? 3. What threats exist that could consider the database to be inconsistent as

well as insecure? 4. What security methods are put in place to protect the database, give

examples and state your reasons? 5. Design an ER diagram to model students attending courses, each student

on one course. Add on your diagram the primary and foreign keys, then answer the following questions.

1. How would you impose the constraint that every student has a unique

student ID? 2. A student can be registered for at most one course? 3. How would you ensure all student addresses were valid? 4. How do we change a student from one course to another and what

must we check first? 5. If we decided to delete a student would we have to make the same

check? 6. What would we have to do if we decided to change a course ID? 7. What would we have to do if we decided to delete a course? 8. If we made the foreign key NOT NULL what would this mean? 9. If another user needs access to the table but only to query the table

how can this be achieved? 10. Create an access matrix for 3 users with varying rights on the student

table.

Page 37: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 37

Week 11 – Tutorial: Distributed Database

Week 11: Network and Distributed Database 1. Describe the evolution from centralised DBMS to distributed DBMs. 2. List and discuss some of the factors that influenced the evolution of the

DDBMS. 3. When would you use a DDBMs? 4. What are the advantages of the DDBMS? 5. What are the disadvantages of DDBMS? 6. Explain the difference between distributed databases and distributed

processing. Draw a diagram to give emphasis to your answer. 7. What is a fully distributed database management system? 8. What are the components of a DDBMS? 9. What is fragmentation in a DDBMS, give examples.

Page 38: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 38

Page 39: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 39

8. Practicals

Weeks 1 – 3 PRACTICALS: Introduction to Oracle

For the next three weeks you will be practicing using Oracle to develop a simple database system. This will include learning the syntax for changing some of the defaults of the page settings, creating tables, inserting rows and simple SQL statements. It is advised that you first try to type directly in Oracle, so that you will recognise the difficulty in correcting mistakes, etc. Once, you have completed that exercise, then, use Notepad to type the syntax, then copy and paste at the SQL> prompt in Oracle. Remember to save your notepad document on your home drive (H) for ease of reference and review. Follow the steps below to log into Oracle.

1. Log into UEL network account. 2. To start Oracle:

• Click on Start

• Click on Programs

• Click on Local Programming

• Click on Oracle Client - Oracle81

• Click on Application Development

• Click on SQL Plus 3. Log into Oracle:

• In the Log On Box, type your Oracle user name (this will be your student number), eg, U1234567 (remember to include the “U”)

• Your password will be your date of birth in the format of ddmmyy so enter numbers, for example, if your birthday is 1 January 1989, then type 010189

• The Host String is SCTORA

Once you have logged in you will see the SQL> prompt.

Page 40: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 40

4. If your password does not work you can try and reset it:

• Click on: Start/Departmental Menu/Computing/Change Oracle Password

For further information check UELplus, under Practicals, select “Change Oracle password”

At the SQL> prompt you can enter your SQL syntax for your practical sessions.

5. Explanation of some of the keywords/commands in the demobuild sample database below:

• Drop – keyword command for deleting a table from the database

• Create – keyword for creating a table, index, objects etc.

• Not null – is a constraint used to ensure that a column must always have a value.

• Comer – used as separation of columns/field/headings

• Semi-colon – to end a statement

• Insert into – inserting values in table

Creating Sample Database (Demobuild)

Please note, if this is the first time you are using Oracle at the University, none of the tables below would be on your Oracle server. Therefore, when you type “Drop table Emp;” Oracle will display “table does not exist”. Do not worry. Start typing from CREATE, to create the tables.

DROP TABLE EMP;

DROP TABLE DEPT;

DROP TABLE BONUS;

DROP TABLE SALGRADE;

DROP TABLE DUMMY;

CREATE TABLE EMP

(EMPNO NUMBER(4) NOT NULL,

ENAME VARCHAR2(10),

JOB VARCHAR2(9),

MGR NUMBER(4),

HIREDATE DATE,

SAL NUMBER(7,2),

COMM NUMBER(7,2),

DEPTNO NUMBER(2));

Page 41: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 41

Once you have finished typing the above syntax to create the EMP table, you can display a description of the table, eg, the column headings and data type, by typing DDEESSCC EEMMPP;; then press the enter key.. To add rows in the tables, use the keyword/command “IINNSSEERRTT IINNTTOO”. Notice, when entering a number, you do not use quotation marks. Do so, only for text. Also, the values must be typed in the same order as the column headings.

INSERT INTO EMP VALUES

(7369,'SMITH','CLERK',7902,'17-DEC-80',800,NULL,20);

INSERT INTO EMP VALUES

(7499,'ALLEN','SALESMAN',7698,'20-FEB-81',1600,300,30);

INSERT INTO EMP VALUES

(7521,'WARD','SALESMAN',7698,'22-FEB-81',1250,500,30);

INSERT INTO EMP VALUES

(7566,'JONES','MANAGER',7839,'2-APR-81',2975,NULL,20);

INSERT INTO EMP VALUES

(7654,'MARTIN','SALESMAN',7698,'28-SEP-81',1250,1400,30);

INSERT INTO EMP VALUES

(7698,'BLAKE','MANAGER',7839,'1-MAY-81',2850,NULL,30);

INSERT INTO EMP VALUES

(7782,'CLARK','MANAGER',7839,'9-JUN-81',2450,NULL,10);

INSERT INTO EMP VALUES

(7788,'SCOTT','ANALYST',7566,'09-DEC-82',3000,NULL,20);

INSERT INTO EMP VALUES

(7839,'KING','PRESIDENT',NULL,'17-NOV-81',5000,NULL,10);

INSERT INTO EMP VALUES

(7844,'TURNER','SALESMAN',7698,'8-SEP-81',1500,0,30);

INSERT INTO EMP VALUES

(7876,'ADAMS','CLERK',7788,'12-JAN-83',1100,NULL,20);

INSERT INTO EMP VALUES

(7900,'JAMES','CLERK',7698,'3-DEC-81',950,NULL,30);

INSERT INTO EMP VALUES

(7902,'FORD','ANALYST',7566,'3-DEC-81',3000,NULL,20);

INSERT INTO EMP VALUES

(7934,'MILLER','CLERK',7782,'23-JAN-82',1300,NULL,10);

Once you have inserted the rows for the Emp table, you can view the table, by typing SSEELLEECCTT ** FFRROOMM EEMMPP;; You will notice that the columns are wrapping over – type SSEETT NNUUMM 77;; this will reduce the numeric columns and make the display more readable.

Now, either type the slash key / and press the ENTER key, to repeat the last statement,

or type SSEELLEECCTT ** FFRROOMM EEMMPP;; again to see the difference. To select specific attributes from the EMP table, eg, if you want to know the names of the employee and their salary. Type the following statement: SELECT ENAME, SAL FROM EMP;

Page 42: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 42

Continue creating the tables for the database and try the sample SQL statements. CREATE TABLE DEPT

(DEPTNO NUMBER(2),

DNAME VARCHAR2(14),

LOC VARCHAR2(13) );

INSERT INTO DEPT VALUES

(10,'ACCOUNTING','NEW YORK');

INSERT INTO DEPT VALUES (20,'RESEARCH','DALLAS');

INSERT INTO DEPT VALUES

(30,'SALES','CHICAGO');

INSERT INTO DEPT VALUES

(40,'OPERATIONS','BOSTON');

Now type the SQL statement to view a description of the DEPT table.

CREATE TABLE BONUS

(

ENAME VARCHAR2(10),

JOB VARCHAR2(9),

SAL NUMBER,

COMM NUMBER

);

CREATE TABLE SALGRADE

( GRADE NUMBER,

LOSAL NUMBER,

HISAL NUMBER );

INSERT INTO SALGRADE VALUES (1,700,1200);

INSERT INTO SALGRADE VALUES (2,1201,1400);

INSERT INTO SALGRADE VALUES (3,1401,2000);

INSERT INTO SALGRADE VALUES (4,2001,3000);

INSERT INTO SALGRADE VALUES (5,3001,9999);

CREATE TABLE DUMMY

( DUMMY NUMBER );

INSERT INTO DUMMY VALUES (0);

COMMIT;

Once you have completed typing the sample database, try the following simple SQL statement:

1. Select * from TAB: This will display all available tables in (your) database.

Page 43: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 43

TIPS WHEN CREATING A DATABASE

CREATING TABLES To create tables, you need to know:

1. Table name 2. The attributes 3. Attribute/data types eg, number, date, char or varchar(2) 4. Column size

Based on this simple ER diagram let’s create a database.

Patient T_Session Consultant

Doctor

P_ID D_ID

D_ID

TS_ID D_ID C_ID C_ID

Patient T_Session Consultant

Doctor

P_ID D_ID

D_ID

TS_ID P_ID C_ID C_ID

Patient T_Session Consultant

Doctor

P_ID D_ID

D_ID

TS_ID D_ID C_ID C_ID

Patient T_Session Consultant

Doctor

P_ID D_ID

D_ID

TS_ID P_ID C_ID C_ID

TABLE NAMES AND ATTRIBUTES PATIENT (P_ID, D_ID, P_Name, P_Add, P_Age) CONSULTANT (C_ID, C_Name, C_Room) T_SESSION(TS_ID, P_ID, C_ID, Date_treat, sample) DOCTOR (D_ID, D_Name, D_Number, D_Add) ATTRIBUTE/DATA TYPES: CHAR: stores fixed-length alphanumeric data up to 2,000 characters. Default size is one character. VARCHAR2: stores variable-length alphanumeric data up to 4,000 characters. You MUST specify the maximum size of a column. Eg, VARCHAR2(10), therefore the maximum column size would not be more than 10 characters and you can use both numeric and alpha data. DATE: use the standard format of ‘12-MAY-03’. DD-MON-YY.

Page 44: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 44

NUMBER: stores integer, fixed-point numeric values. Eg, NUMBER(5) therefore the maximum column size would not be more than 5 numeric numbers. You can also specify decimal point, eg, NUMBER(9,2), used mainly for currency purposes. CREATING TABLES: TIP: When creating tables it is always good practice to create the tables without any foreign keys first, then the ones with the least foreign keys. Just in case you decide to get rid of/drop a table for any reason, eg, not required in the database or editing/altering data in that table is too much. Dropping a table that has foreign keys with data that is already linked with the original table is very difficult. You would have to remove the link first then drop the unwanted table – not very easy! TO CREATE A TABLE Type the following to create a DOCTOR table: A reminder of the table name and attributes: DOCTOR (D_ID, D_Name, D_Number, D_Add) CREATE TABLE DOCTOR ( D_ID VARCHAR2(4) PRIMARY KEY NOT NULL, D_NAME VARCHAR2(15), D_NUMBER NUMBER(12), D_ADD VARCHAR2(20)); Notice the constraint on the primary key. You can also omit “not null” since Oracle will recognise that a primary key cannot have a null value. ENTERING VALUES To Insert Values into a table use the following syntax: “INSERT INTO {table name}VALUES” To be repeated for every row/record you want to enter into the table. INSERT INTO DOCTOR VALUES (‘D01’, ‘JOSEPH’, 0798543901, ‘CHELMSFORD’); INSERT INTO DOCTOR VALUES (‘D02’, ‘JULIE’, 02085448888, ‘LIVERPOOL’); INSERT INTO DOCTOR VALUES (‘D03’, ‘PHIL’, 0798566678, ‘WHITECHAPLE’); INSERT INTO DOCTOR VALUES (‘D04’, ‘JANET’, 02072235000, ‘CHELMSFORD’);

Page 45: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 45

Notice that there are no quotes for numbers! Now continue creating the following tables and inserting values Type the following to create a CONSULTANT table: A reminder of the table name and attributes: CONSULTANT (C_ID, C_Name, C_Room) CREATE TABLE CONSULTANT ( C_ID VARCHAR2(4) PRIMARY KEY NOT NULL, C_NAME VARCHAR2(15), C_ROOM NUMBER(4)); INSERT INTO CONSULTANT VALUES (‘C01’, ‘NAVEED’, 007); INSERT INTO CONSULTANT VALUES (‘C02’, ‘CHRIS’, 010); INSERT INTO CONSULTANT VALUES (‘C03’, ‘RACHEL’, 001); INSERT INTO CONSULTANT VALUES (‘C04’, ‘NAOMI’, 103); INSERT INTO CONSULTANT VALUES (‘C05’, ‘STUART’, 105); Type the following to create a PATIENT table: A reminder of the table name and attributes: PATIENT (P_ID, D_ID, P_Name, P_Add, P_Age) CREATE TABLE PATIENT ( P_ID NUMBER(4) PRIMARY KEY NOT NULL, D_ID VARCHAR2(4),

P_NAME VARCHAR2(10), P_ADD VARCHAR2(15), P_AGE NUMBER(3), FOREIGN KEY (D_ID) REFERENCES DOCTOR(D_ID)); Notice the referencing for the foreign key. Always use the same attribute/data type from the original/primary table. You can also type “foreign key” after the character type referring that the attribute, eg, D-ID is a foreign key. INSERT INTO PATIENT VALUES (001, ‘D02’, ‘MARY’, ‘LEYTON’, 25); INSERT INTO PATIENT VALUES (002, ‘D02’, ‘MARTIN’, ‘ILFORD’, 10);

Page 46: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 46

INSERT INTO PATIENT VALUES (003, ‘D01’, ‘LUCY’, ‘DAGENHAM’, 25); INSERT INTO PATIENT VALUES (004, ‘D03’, ‘JOHN’, ‘STRATFORD’, 80); INSERT INTO PATIENT VALUES (005, ‘D04’, ‘RICHARD’, ‘RUISLIP’, 80); Notice the repeating foreign key values. Type the following to create a T_SESSION table: A reminder of the table name and attributes: T_SESSION(TS_ID, P_ID, C_ID, Date_treat, sample) CREATE TABLE T_SESSION ( TS_SESSION VARCHAR2(4) PRIMARY KEY NOT NULL,

P_ID NUMBER(4), C_ID VARCHAR2(4), DATE_TREAT DATE, SAMPLE VARCHAR2(15), FOREIGN KEY (P_ID) REFERENCES PATIENT (P_ID), FOREIGN KEY (C_ID) REFERENCES CONSULTANT (C_ID)); INSERT INTO T_SESSION VALUES (‘T001’, 001, ‘C02’,’27-JUL-03’, ‘BLOOD’); INSERT INTO T_SESSION VALUES (‘T002’, 004, ‘C02’,’17-JUL-03’, ‘URINE’); INSERT INTO T_SESSION VALUES (‘T003’, 001, ‘C03’,’01-AUG-03’, ‘NON’); INSERT INTO T_SESSION VALUES (‘T004’, 004, ‘C05’,’30-OCT-03’, ‘BLOOD’); INSERT INTO T_SESSION VALUES (‘T005’, 003, ‘C01’,’15-JUN-03’, ‘SPUTUM’); INSERT INTO T_SESSION VALUES (‘T006’, 002, ‘C03’,’18-MAY-03’, ‘SPUTUM’);

Page 47: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 47

ADDITIONAL SYNTAX

EXAMPLES To view all attributes and data types in a table DESC tablename;

DESC PATIENT;

To view whole table: SELECT * FROM tablename;

SELECT * FROM PATIENT;

To drop a table DROP TABLE tablename;

DROP TABLE PATIENT;

To delete the values in a table but retain the attributes and data types: DELETE FROM tablename;

DELETE FROM PATIENT;

To delete a specify row in a table: DELETE FROM tablename WHERE searchCondition;

DELETE FROM PATIENT WHERE ENAME = ‘FRED’;

To alter a table: (ie, adding, and changing columns not the values in a table – only the table structure) ALTER TABLE tablename ADD column-name dataType; (ie, to change a column’s data type) ALTER TABLE tablename MODIFY column-name new data-type; NOTE: If you modify you can only increase the column width, not smaller, unless there is no data in the table.

ALTER TABLE PATIENT ADD ADDRESS VARCHAR2(20)); ALTER TABLE PATIENT MODIFY ADDRESS VARCHAR2(25));

Page 48: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 48

To update values in individual columns of selected rows): (ie, the Update keyword changes the data in the table, not the structure of the table) UPDATE tablename SET columnName = expression WHERE searchCondition;

UPDATE PATIENT SET P_ADD = ‘EASTCOTE’, P_NAME = ‘JULIAN’ WHERE P_ID = 002; Not specifying a WHERE clause will automatically change every value to the columns specified. Repeat complete statement for each row you want to update.

To create a view: (ie, creating a temporary table from an existing table in the database to store specific information) CREATE VIEW NewTableName (NewColumn, NewColumn, etc) AS SELECT ColumnName, ColumnName, ColumnName from tablename; From the AS SELECT statement, Oracle will extract these columns from the existing table and create a view with the new columns. Views provide security by hiding sensitive or irrelevant parts of the database. You can restrict access to certain parts of the database to just the information you want the user to see.

CREATE VIEW Employees (Employee_No,Employee_Name,Employee_Dept) AS SELECT Empno, Ename, Deptno FROM EMP;

Page 49: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 49

Weeks 4 - 7 PRACTICALS: Introduction to SQL

Week 4 to 7: Introduction to writing SQL SQL stands for Structured Query Language It is a data definition / manipulation language (DDL/DML) which is the standard query language used to access data. With databases such as Ingres and Oracle it can be used in application programs, embedded in a host language ( eg 'C' ) or used interactively to access data.

A Couple of Web pages which will help with your SQL.

Introduction to SQL

http://w3.one.net/~jhoffman/sqltut.htm SQL Interperter Tutorial with live practice database. http://sqlcourse.com/

SQL Commands. Note brackets ( ) are part of the command, { } identify optional repeating items, [ ] optional clauses. Creating a new version of an existing table. The create table...as... command create table tablename create table overpaid [(columname {,columname})] as select * as select... from emp where sal > 3000

Page 50: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 50

Global Insert The insert...select.... command insert into tablename insert into overpaid [(columname {,columname})] select * from emp select... where sal between 2000 and 3000 Inserting single rows The insert...values... command insert into tablename insert into dept (columname {,columname}) (deptno, dname, loc) values (expression {,expression}) values (50, 'MARKETING', 'LONDON')

Updating Existing Data The update... command update tablename update emp set sal = 6000, set columname=expression {,columname=expression} hiredate = ‘sysdate’ [where search_condition] where job = 'PRESIDENT' Deleting Rows The delete... command delete from tablename delete from overpaid [ where search_condition ] where job = 'CLERK' Creating Views The create view... command create view view_name create view logical_view [(columname {,columname})] as select * from emp as select... where sal > 3000 Removing Tables and Views The drop... command drop table tablename {,tablename} drop table overpaid drop view viewname {,viewname} drop view logical_view

Page 51: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 51

Select Commands Retrieve all rows select * from tablename Retrieve particular columns select columnname { ,columnname} from tablename Sorting data select ... from ... order by columnname [asc|desc]{ ,columnname [asc|desc]} Grouping data select deptno, count(*) from emp group by deptno Finding specific groups select deptno, count(*) from emp group by deptno having count(*) > 5 Retrieving unique occurrences select distinct columnname ... from ...

The Where clause The where clause is used to restrict the set of data retrieved to those records matching particular requirements. For example: Qualifying data for retrieval select ... from ... where search_condition Find out what Fred's salary is select salary from emp where name = 'FRED' Comparison operators select salary, name = > < >= <= from emp <> != (means not equal) where salary > 2000 Logical Operators select name and or not from emp where jobs = 'CLERK' and salary > 1000

Page 52: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 52

Compound logical operators select name from emp ( what do you get if you where ( job = 'CLERK or job = 'ANALYST') remove the brackets? ) and salary < 1500 Range searching select name from emp where salary between 3000 and 5000 Pattern matching select name from emp where name like 'A%' Special NULL value select comm from emp where comm is not null (or the opposite, is null ) Joining Tables To retrieve data from more than one table we must specify how the table are to be joined. We are actually specifying what the relationship between one table and another is, so referring to your ER diagram will help you identify what fields should be joined between two tables. With the relationship between dept and emp being; each department can have many employees and each employee works in one department, the join is between the key field deptno in dept and the foreign key deptno in emp. Therefore to retrieve the dept name select dname, ename and the employee in that dept the from dept, emp two tables must be joined. where dept.deptno = emp.deptno ( specify the join ) Adding further restriction as before and dept.dname = 'RESEARCH'

Page 53: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 53

When two or more table are being join, if the fieldname has been used in both tables the name must be prefixed by the name of the table, ie dept.deptno. It is usual practise to use an alias in the from clause for simplicity. ie the from clause becomes from dept d, emp e so d and e are aliases then the where clause can use these as where d.deptno = e.deptno in the select portion as there is no ambiguity you need not use the alias but it is good practice to do so. So our query becomes select d.dname, e.ename from dept d, emp e where d.deptno = e.deptno and d.dname = 'RESEARCH'

Now attempt to answer the following questions using SQL

What would be the required SQL for the following queries? 1. List all the employees whose salary is between 1000 and 2000. Show employee name, department number and salary. Example answers given below for questions 1 and 2.

ENAME DEPTNO SAL

ALLEN 30 1600

WARD 30 1250

MARTIN 30 1250

TURNER 30 1500

ADAMS 20 1100

MILLER 10 1300

2. Display all the different types of occupations. Example answer below.

JOB

ANALYST

CLERK

MANAGER

PRESIDENT

SALESMAN

Page 54: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 54

3. List details of employees in departments 10 and 30. 4. Display all employees who were recruited during 1983, giving their name,

department and hire-date. 5. List the names and jobs of all clerks in department 20. 6. List the employees whose names have TH or LL in them. 7. List the department numbers, name and the location in department name

order. 8. Find the name and salary of employees in Dallas. 9. List in order of department number, the department number, employee

name and salary increased by 15% and expressed as a final whole figure. 10.a List all employees and their managers numbers. 10.b The hard bit. As above but list their managers' names as well as their

numbers. 10.c List the employee's name and salary and manager's name and salary for

all employees who earn more than their managers.

Page 55: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 55

Weeks 7 - 11 PRACTICALS: SQL Questions

Week 7 to 11: 30 SQL Questions (plus working on assignment)

SQL Questions 1.

Select everything from the Dept table.

2.

Select the employees in name order.

3.

Select all the employees who work in department 20.

4. List name and salary of all the salesmen.

5. Find all the employees earning more than £1500.

6. Find all the employees earning £1500 or more.

7. Find all the employees whose commission is greater than their salary.

8. List all the salesmen that earn more than £1500

9. List all the salesmen in department 30 who earn £1500 or more.

10. List the president and managers.

Page 56: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 56

11. List all the managers who are not in

department 30.

12. List every manager and the clerks in department 10.

13. List the managers and clerks that work in department 10.

14. Find everyone who is neither a manager nor a clerk, but is in department 10

15. List all the other emps who do not earn between £1000 and £2000

16. List all the clerks, salesmen and analysts.

17. List all the employees who are not the above.

18. List all employees who do not receive commission.

19. List all employees who receive commission.

20. List all the employees and their departments names.

21. List all the departments and their employees names.

22. Find Jones job.

23. List the name and job of employees with the same job as Jones.

Page 57: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 57

24. Find the employees that earn more than

ANY employees in department 30.

25. Find the employees that earn more than ALL employees in department 30.

26. Find all the employees in Dept 10 that have a job that is the same as anyone in department 30.

27. List the name, job and salary of employees who have the same job and salary as Ford.

28. List the name, job and department of employees who have the same job as Jones or a salary greater than or equal to Ford.

29. Give a count of the number of employees by department number.

30. Give a count of the number of employees by department number which have more than 4 employees

Page 58: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 58

Topic 6 and 7 – SQL Supporting Material

SQL stands for "Structured Query Language". It is used to communicate with a database and is

used to ask complex questions of a database. This type of query is part of the Data Manipulation

Language (DML).

1.1.1.1.Data Manipulation Language (DML)

SQL is a database query language that was adopted as an industry standard in 1986. Many

database products support SQL, this means that if you learn how to use SQL you can apply this

knowledge to MS Access or SQL Server or to Oracle or Ingres and countless other databases.

DML examples:-

All of these queries are very simple and contain no WHERE clause. Note that arithmetic

can be performed in the SELECT line.

SELECT...FROM clause

SELECT * FROM CUS;

SELECT C_NO, AMOUNT FROM INVOICE;

SELECT DISTINCT C_NO FROM INVOICE;

SELECT PROD_NO, DESCR, 100 * (QIS - MINQ) / MINQ FROM PRODUCT;

Illustrating simple usage of the WHERE clause to restrict the rows that are output.

WHERE clause

SELECT PROD_NO, DESCR FROM PRODUCT WHERE PRICE > 5;

SELECT INITS, SNAME FROM CUS WHERE SNAME < ‘K’;

SELECT * FROM INVOICE WHERE DATE < ‘1-jan-91’;

SELECT * FROM CUS WHERE CITY < > ‘London’;

SELECT * FROM CUS WHERE BALANCE > CRED_LIM;

The LIKE option can be used to perform fuzzy matching.

LIKE Clause

SELECT & FROM CUS WHERE SNAME LIKE ‘Dz%’;

Page 59: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 59

SELECT * FROM CUS WHERE SNAME LIKE ‘_z%’;

SELECT SNAME, STREET FROM CUS WHERE POSTC LIKE ‘MK2 6EF’;

SELECT SNAME, STREET FROM CUS WHERE POSTC LIKE ‘MK2 6_’;

SELECT SNAME, STREET FROM CUS WHERE POSTC LIKE ‘MK2 %’;

SELECT * FROM CUS WHERE TITLE LIKE ‘%s’;

The BETWEEN option allows a range of numeric or textual data to be SELECTed.

IN gives a way of matching a column with one of a set of values.

IN Clause

SELECT * FROM INVOICE

WHERE INV_DATE BETWEEN

‘1-dec-90’ AND ‘13-jan-91’;

SELECT * FROM CUS

WHERE SNAME

BETWEEN

‘E’ AND ‘M’;

SELECT * FROM CUS

WHERE SNAME

BETWEEN

‘E’ AND ‘Lzz’;

SELECT * FROM DELIVERY

WHERE PROD_NO

IN (1,3,5);

SELECT DISTINCT C_NO

FROM DELIVERY

WHERE PROD_NO

NOT IN (2,4,5);

SELECT * FROM CUS

WHERE TITLE IN (Miss, Ms, Mrs);

AND, OR and NOT can be used in combination to realize more complex conditions. Take care with

your logic.

AND, OR, NOT

SELECT * FROM CUS

WHERE BALANCE > CRED_LIM

AND CITY = ‘London’;

Page 60: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 60

SELECT * FROM CUS

WHERE BALANCE > CRED_LIM

OR CITY = ‘London’;

SELECT * FROM CUS

WHERE (BALANCE>CRED_LIM

OR CITY = ‘London’)

AND NOT (BALANCE > CRED_LIM

AND CITY = ‘London’);

SELECT * FROM CUS

WHERE CRED_LIM IS NULL;

SELECT C_NO, BALANCE FROM CUS

WHERE CRED_LIM !=500

OR CRED_LIM IS NULL;

Aggregate functions include AVG, COUNT MAX, MIN, SUM.

Simple use of GROUP BY is also shown.

AGGREGATE FUNCTIONS

SELECT SUM (BALANCE) FROM CUS;

SELECT COUNT(*) HIGH_BALANCE FROM CUS

WHERE BALANCE > 400;

SELECT COUNT (DISTINCT CITY) FROM CUS;

HAVING is used to perform a filtering effect similar to WHERE, after the GROUP BY. Non-output

agg. functions can be performed by a HAVING clause.

GROUP BY Clause

SELECT DEPARTMENT, AVG(AGE)

FROM EMPLOYEE

GROUP BY DEPARTMENT;

SELECT EMP_NO, AVG(AGE)

FROM EMPLOYEE

GROUP BY DEPARTMENT;

SELECT MAX(SUM(BALANCE))

FROM CUS

GROUP BY CITY;

The ORDER BY clause is used to determine the order that the output appears in. DESC indicates

descending order. You can order on more than 1 col.

HAVING Clause

SELECT DEPARTMENT, AVG(AGE)

Page 61: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 61

FROM EMPLOYEE

GROUP BY DEPARTMENT

HAVING AVG(AGE) < 27;

SELECT TERM, GROUP_NO

FROM GROUPS

GROUP BY TERM, GROUP_NO

HAVING COUNT(*) > 2;

SELECT DEPARTMENT, COUNT(*), AVG(AGE)

FROM EMPLOYEE

GROUP BY DEPARTMENT

HAVING COUNT(*) > 3

AND AVG(AGE) > 27;

SELECT DEPARTMENT, AVG(AGE)

FROM EMPLOYEE

GROUP BY DEPARTMENT

HAVING COUNT(*) > 1;

A join may involve one (self-join) or more tables. The join criteria often but not always involve

foreign keys. The OUTER JOIN is implemented using a (+) near one col. name.

Note that alternative syntax is used in SQL92

ORDER BY Clause

SELECT &

FROM CUS

ORDER BY SNAME;

SELECT *

FROM EMPLOYEE

WHERE DEPT_NO = 3

ORDER BY SALARY DESC;

SELECT *

FROM EMPLOYEE

ORDER BY JOB, SALARY, DESC;

SELECT SNAME, COMM/SAL

FROM EMPLOYEE

ORDER BY COMM/SAL;

A join may involve one (self-join) or more tables. The join criteria often but not always involve

foreign keys. The OUTER JOIN is implemented using a (+) near one col. name.

Note that alternative syntax is used in SQL92

Queries Using Joined Tables (1)

SELECT SNAME, STREET, CITY, POSTC,

INV_NO, INV_DATE, AMOUNT

FROM CUS, INVOICE

Page 62: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 62

WHERE CUS.C_NO - INVOICE.C_NO;

SELECT A.C_NO, NAME, INV_NO

FROM CUS A, INV B

WHERE A.C_NO = B.C_NO;

SELECT *

FROM EMPLOYEE A, EMPLOYEE B

WHERE B.SALARY > A.SALARY;

SELECT A.C_NO, B.INV_NO, C.AMOUNT

FROM CUS A, INV B, PMT C

WHERE A.C_NO = B.C_NO

AND B.INV_NO = C.INV_NO;

SELECT DEPT_NAME, EMP_NAME

FROM DEPARTMENT A, EMPLOYEE B

WHERE A.DEPT_NO = B.DEPT_NO (+);

The subquery delivers one or more values which can be used in the WHERE clause of the outer

query. Note that values returned by the subquery cannot be output.

Subqueries (1)

SELECT NAME

FROM EMPLOYEE

WHERE DEPARTMENT =

(SELECT DEPARTMENT

FROM EMPLOYEE

WHERE NAME = ‘Karen’);

SELECT *

FROM PRODUCT

WHERE PROD_NO IN

(SELECT PROD_NO

FROM DELIVERY);

SELECT *

FROM PRODUCT

WHERE PROD_NO NOT IN

(SELECT PROD_NO

FROM DELIVERY);

Take great care when using ANY and ALL. ‘< ANY’ means less that at least one. ‘!= ANY’ means

not equal to at least one. This might not be what you would expect.

Subqueries (2)

SELECT *

FROM EMPLOYEE

WHERE SALARY < ANY

(SELECT SALARY

FROM EMPLOYEE);

Page 63: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 63

SELECT *

FROM EMPLOYEE

WHERE SALARY != ANY

(SELECT SALARY

FROM EMPLOYEE);

SELECT *

FROM EMPLOYEE

WHERE SALARY >= ALL

(SELECT SALARY

FROM EMPLOYEE);

SELECT *

FROM EMPLOYEE

WHERE SALARY =

(SELECT MAX(SALARY)

FROM EMPLOYEE);

The first query contains a correlated subquery, which means that for every row in the outer query,

(every employee), all rows in the subquery have to be inspected. Correlated subqueries may be

identified as such by the presence in the subquery of a tables alias (A.) from the outer query.

Subqueries (3)

SELECT *

FROM EMPLOYEE A

WHERE SALARY > ALL

(SELECT SALARY

FROM EMPLOYEE B

WHERE B.EMP_NO != A.EMP_NO);

SELECT CITY, SUM(BALANCE)

FROM CUS

GROUP BY CITY

HAVING SUM(BALANCE) =

(SELECT MAX(SUM(BALANCE))

FROM CUS

GROUP BY CITY);

The set operations UNION, INTERSECT and MINUS are usually applied to separate tables

although they can also be applied to the results of subquerires. UNION has the effect of appending,

INTERSECT delivers rows which are in both sets, and MINUS rows in one but not the other.

UNION, INTERSECT, MINUS

SELECT * FROM VIOLINISTS

UNION SELECT * FROM PIANISTS;

SELECT * FROM PIANO

UNION (SELECT * FROM VIOLIN

Page 64: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 64

INTERSECT SELECT STUD_NO, NAME, AGE

FROM CELL0);

SELECT * FROM VIOLINISTS

MINUS SELECT * FROM PIANISTS

Unlike IN, EXISTS does not require a value to be passed from the outer query to subqueries. The

third query reads ‘Who has bought all products?’

EXISTS and NOT EXISTS

SELECT *

FROM CUST

WHERE EXISTS (SELECT *

FROM PURCHASE B

WHERE CUST.CNO=B.CNO);

SELECT *

FROM CUST

WHERE NOT EXISTS (SELECT *

FROM PURCHASE B

WHERE CUST.C_NO=B.C_NO);

SELECT * FROM CUST A

WHERE NOT EXISTS (SELECT * FROM PROD B

WHERE NOT EXISTS (SELECT * FROM PURCHASE C

WHERE A.CNO=B.CNO

AND B.PRNO=C.PRNO);

1.1.1.2. Data Definition Language (DDL)

SQL also provides a means of creating databases. This part of the SQL is called the Data

Definition Language (DDL). Statements included in DDL are:-

DDL examples:-

create table <tablename> (col1, col2, col3,…..col99);

alter table <tablename> add ( col1 char(12), col2 date);

alter table <tablename> modify ( col3 number(6,2));

drop table <tablename>;

index

create view <viewname> as <select statement>

Page 65: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 65

drop view <viewname>

Temporary tables are sometimes necessary to aid in breaking a complex query into manageable

parts. Views collect frequently-combined data.

Creating Tables and Views

CREATE TABLE PRODUCT

(PROD_NO NUMBER (2),

DESCR CHAR(10),

START_DATE DATE);

CREATE TABLE LOND_CUS AS

(SELECT * FROM CUS

WHERE CITY = ‘London’);

CREATE VIEW STATEMENT AS

(SELECT A.C_NO, NAME, ADDR,

B.INV_NO, INV_DATE, INV_AMT,

PMT_DATE, PMT_AMT

FROM CUSA, INV B, PMT C

WHERE A.C_NO = B.C_NO

AND B.INV_NO = C.INV_NO (+));

DROP TABLE LOND_CUS;

DROP VIEW STATEMENT;

VIEW (oracle)

GRANT SELECT ON EMP2

Granting

privileges on a

view

Here, a view is being used to restrict the columns of the EMPLOYEE tables that public can see. They can

select (not update, insert etc.)

Views (2)

CREATE VIEW EMP3 AS

SELECT *

FROM EMPLOYEE

WHERE DEPT_NO =

(SELECT DEPTNO

FROM EMPLOYEE

WHERE ENAME = USER

AND JOB = ‘MANAGER’;

CREATE VIEW EMP2 AS SELECT E_NO, NAME FROM EMPLOYEE;

Page 66: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 66

GRANT SELECT ON EMP3

TO PUBLIC;

The VIEW emp3 is defined to allow a manager to see only the records of the department of which he is a

manager.

Views (3)

VIEWs can:

• restrict rows

• restrict columns

• restrict rows and columns

• calculate summary data

• group by

• join

• subquery

The idea of a view is to give the user a restricted subset of data involving one or more base tables for

security reasons or because the user wants to take a particular view of the data.

Views (4)

CREATE VIEW LONCUS AS

SELECT * FROM CUS

WHERE CITY = ‘London’;

CREATE VIEW LONSHORT1 AS

SELECT C_NO, CRED_LIM, BALANCE

FROM LONCUS

SELECT *

FROM VIEWS

WHERE VIEWNAME LIKE ‘LON%’;

Views can be used to restrict the rows and/or columns that the view user will be able to access. One view

can be built on another. It is possible to have a view of a join but not to join views. The DD contains

useful data on views that exist.

(Defining one view in terms of another)

Restrict columns

Page 67: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 67

Views (5)

CREATE VIEW SUMMARY1 AS

SELECT CITY, SUM(CRED_LIM)

MAX_RISK, SUM(BALANCE) DEBT

FROM CUS

GROUP BY CITY;

SELECT * FROM SUMMARY;

gives:

city max_risk debt

Dover 600 561

Leeds 500 510

London 2500 490

This view gives a useful summary by city of the total of credit limits and the total of current debts. When a

base table is updated, all the views based on it are also updated.

Views (6)

Updating Views (1)

UPDATE CUS

SET BALANCE = BALANCE + 100

WHERE C_NO = 5;

SELECT C_NO, BALANCE

FROM LONCUS

WHERE C_NO = 5;

Here, the base table has been updated.

The value of the balance field in one row of CUS has been added to. Since LONCUS is based on CUS and

customer no.5 is a London customer, the SELECT will show the new value of balance. The new value

shows through into the view.

Views (7)

Updating Views (2)

UPDATE LONCUS

SET BALANCE = BALANCE + 100

WHERE C_NO = 5;

SELECT C_NO, BALANCE

FROM CUS

WHERE C_NO = 5;

Here, the view LONCUS has been updated. The new value shows through into the base table CUS. There

are some rather severe restrictions on updates via views, as the next slide shows.

Page 68: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 68

Views (8)

Updating Views (3)

Restrictions on View Updates

DELETE

• view is based on one table only

• view must contain no GROUP BY

• view must contain no DISTINCT

UPDATE

• as above

• view must contain no ‘column expressions’

INSERT

• as above

• all the ‘non null’ columns from the base table are in the view

There are severe restrictions on updating via views. Note that only the SQL SELECT can access views

based on more than one table inserts, updates and deletes cannot.

Views (9)

Views of more than one table

CREATE VIEW STATEMENT

(NAME, ADDRESS, DATE, INVOICE, AMOUNT, PAYMENT) AS

SELECT TITLE, SNAME, STREET, CITY, POSTC,

INV_DATE,B.INV_NO,B.AMOUNT, C.AMOUNT

FROM CUS A,INVOICE B, PAYMENT C

WHERE A.C_NO = B.C_NO

AND B.INV_NO = C.INV_NO(+));

This view is used for printing statements at the end of each month. It will always reflect the latest state of

the base tables.

Note that this view cannot be updated since there is more than one base table.

GRANT statement

• Database security in SQL is vested in the GRANT command

• This command is used mostly by the DBA (DataBase Administrator)

• There are two main forms of the GRANT command:

• First form: priveleges w.r.t. users

• Second form: privileges w.r.t. tabels and views.

The first form of GRANT is used to register new users and the second form is to give users access to tables

and views.

Page 69: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 69

GRANT Command: First form (1)

Purpose:

• Create User Ids

• Assign passwords

• Grant database privileges

Privileges:

• CONNECT log onto database

• RESOURCE create tables

• DBA DBA-only commands

User names and passwords are held in a catalog table on the database.

GRANT Command: First Form (2)

Syntax:

GRANT {CONNECT | RESOURCE | DBA}

TO <username>

[IDENTIFIED BY <password>]

The GRANTER grants privileges (his own or lower) to others. Only a DBA can grant DBA privileges for

example Passwords are optional.

GRANT Command: First form (3)

User-id

GRANT CONNECT TO JOHN1

IDENTIFIED BY SECRET1

Password

Creates a new user who can just log on

GRANT CONNECT, RESOURCE

TO JOHN2 IDENTIFIED BY

SECRET2

Creates a new user who can create tables

GRANT CONNECT TO JOHN3,

JOHN4

Can log on without password

Page 70: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 70

All forms of GRANT may be used only by those with DBA privileges, except GRANT CONNECT TO to

change your own password.

GRANT Command: Second form (2)

• Grants privileges w.r.t. tables or views

• Privileges may be:

• ALTER change table structure

• DELETE delete records

• INDEX create and drop indexes

• INSERT insert records

• SELECT permission to select

• UPDATE update records

• ALL all the granter’s privileges

In the second form of the GRANT command, users are granted privileges with respect to individual tables

or views. With a VIEW, ALTER, INDEX and ALL are not allowed.

GRANT Command: Second form (2)

Syntax:

GRANT {privilege, ...|ALL} ON

<table-or-view>

TO {user|PUBLIC}

[WITH GRANT OPTION];

Authorizes grantee to grant all or

part of his privileges in turn to others

The privileges can be any combination of SELECT, INSERT, DELETE, UPDATE, ALTER and INDEX

for a table and just the first four for a view ALL grants all of the privileges possessed by the granter.

UPDATE may be followed by a list of columns, limiting the grantee to updating just those columns in the

table or view.

Page 71: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 71

Table Definitions

CUS

C_NO TITLE SNAME INITS STREET CITY POSTC CRED_LIM BALANCE

1 Mr Sallaway GR 12 Fax Rd London WC1 1000 42.56

2 Miss Lauri P 5 Dux St London N1 500 200

3 Mr Jackson R 2 Lux Ave Leeds LE1 2AB 500 510

4 Mr Dziduch M 31 Low St Dover DO2 9CD 100 149.23

5 Ms Woods SQ 17 Nax Rd London E18 4WW 1000 250.1

6 Mrs Williams C 41 Cax St Dover DO2 8WD 412.21

INVOICE PAYMENT

INV_NO C_NO INV_DATE AMOUNT INV_NO PMT_NO PMT_DATE AMOUNT

940 1 5-DEC-90 26.2 940 2 12-DEC-90 13

1002 4 12-JAN-91 149.23 1005 1 14-JAN-91 510

1003 1 12-JAN-91 16.26 1017 1 30-JAN-91 100

1004 2 14-JAN-91 200 940 3 19-JAN-91 10

1005 3 20-JAN-91 510

1006 5 21-JAN-91 250.1

1017 6 22-JAN-91 412.21

PRODUCT DELIVERY

PROD_NO DESCR QIS MINQ REORDQ PRICE C_NO PROD_NO QTY DEL_DATE

1 Bat 10 5 10 12 3 2 2 3-NOV-90

2 Ball 5 5 20 2 3 1 3 3-NOV-90

3 Hoop 3 5 10 3 1 4 6 7-NOV-90

4 Net 2 5 10 20 5 3 4 12-NOV-90

5 Rope 1 10 10 6 3 3 1 12-NOV-90

VIOLIN

PIANO CELLO

STU_NO NAME AGE STUD_NO NAME AGE STUD_NO NAME AGE

1 Fred 10 2 Jane 12 4 David 10

2 Sally 11 4 David 10 6 Josey 11

4 David 10 5 Zena 11

FLUTE

STU_NO NAME AGE

7 Ashfak 12

Page 72: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 72

CUST

PURCHASE

PROD

CNO NAME CNO PRNO PRNO DESCR

1 Alan 1 a a Apple

2 Bill 1 b b Ball

3 Charles 2 a

GROUPS

TERM GROUP_NO MEMBER

1 1 1

1 1 2

1 1 3

1 2 4

1 2 5

1 2 6

2 10 3

2 10 2

2 1 5

2 1 7

CANDIDATE CAND_NO NAME CONS_NO PARTY NO_OF_VOTES

1 Fred 1 Labour 100

2 Jim 1 Cons 120

3 Peter 1 Liberal 50

4 John 2 Labour 150

5 Mike 2 SLD 50

6 Jane 2 Cons 100

9 Sue 1 SDP 160

7 Mary 2 Green 150

8 Ulrike 1 Indep 150

10 U Li 3 Red Guards 150

21 Rosa 3 Simbianese 30

29 Patty 3 Simbianese 12

41 Astrid 3 Liberal 3

50 Gordon 3 Labour 160

52 Ben 1 Green 70

Page 73: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 73

Student Academic Calendar for 2012/2013

Easter Monday = 1st April 2013

Week Start. Week No.

17-Sep-12 1 INDUCTION

24-Sep-12 2 TEACHING

01-Oct-12 3 TEACHING

08-Oct-12 4 TEACHING

15-Oct-12 5 TEACHING

22-Oct-12 6 TEACHING

29-Oct-12 7 TEACHING

05-Nov-12 8 TEACHING

12-Nov-12 9 TEACHING

19-Nov-12 10 TEACHING

26- Nov-12 11 TEACHING

03-Dec-12 12 TEACHING

10-Dec-12 13 TEACHING

17-Dec-12 STUD VAC

24-Dec-12 STUD VAC

31-Dec-12 STUD VAC

07-Jan-13 14 EXAMS

14-Jan-13 15 EXAMS/MARKING

21-Jan-13 16 MARKING

28-Jan-13 17 INDUCTION/FB

04-Feb-13 18 TEACHING/AB

11-Feb-13 19 TEACHING

18-Feb-13 20 TEACHING

25-Feb-13 21 TEACHING

04-Mar-13 22 TEACHING

11-Mar-13 23 TEACHING

Page 74: Database Handbook

SD2052 - DATABASE SYSTEMS

Semester B: 2013 74

18-Mar-13 24 TEACHING

25-Mar-13 STUD VAC

01-Apr-13 STUD VAC

08-Apr-13 25 TEACHING

15-Apr-13 26 TEACHING

22-Apr-13 27 Assignment One Submission on Moodle TEACHING

29-Apr-13 28 TEACHING

06-May-13 29 TEACHING

13-May-13 30 REVISION

20-May-13 31 EXAMS

27-May-13 32 EXAMS/MARKING

03-Jun-13 33 MARKING

10-Jun-13 34 FB

17-Jun-13 35 AB/COUNSELLING

24-Jun-13 STUD VAC

01-Jul-13 STUD VAC

08-Jul-13 STUD VAC

15-Jul-13 STUD VAC

22-Jul-13 STUD VAC

29-Jul-13 STUD VAC

05-Aug-13 STUD VAC

12-Aug-13 STUD VAC

19-Aug-13 36 STUD VAC/EXAMS

26-Aug-13 37 STUD VAC/MARKING

02-Sep-13 38 STUD VAC/FB/AB

09-Sep-13 STUD VAC

16-Sep-13 1 INDUCTION