0% found this document useful (2 votes)
509 views79 pages

380 Notes Fa2016

380_Notes_Fa2016

Uploaded by

Sally Tran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (2 votes)
509 views79 pages

380 Notes Fa2016

380_Notes_Fa2016

Uploaded by

Sally Tran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

IS 380.

Database

Lecture Notes

Fall 2016

C. Sophie Lee Ph.D.

Professor
Department of Information Systems
College of Business Administration
California State University, Long Beach

Copyrighted Material

1
Topic 1. Relational Database Management
Systems
Database System: Nothing more than an electronic record keeping system.

Basic Database Operations


STUDENT RECORD

SNUM: 103 STUDENT RECORD


Name: Cindy STUDENTS
Major: FIN SNUM: 102 STUDENT RECORD
GPA: 3.1 Name: Betty SNUM SNAME MAJOR GPA
. Major: MKT SNUM: 101
. GPA: 2.8 Name: Andy
. Major: IS 101 Andy IS 2.5
. GPA: 2.5 102 Betty MKT 2.8
. 103 Cindy FIN 3.1
. 104 David FIN 2.4
105 Ellen MKT 3.8
106 Frank IS 3.8
.... .... .... ....

Data
Record:
Field or Attribute:
Table:

Data Management
Insert:
Update:
Delete:
Data Retrieval or Query:
Ad-hoc Query:

Flat File vs. Relational Database Systems


Conventional File System:

(1) Data Redundancy

(2) Data Inconsistency (i.e., lack of Data Integrity)

(3) Data Anomalies

(i) Insertion anomalies

(ii) Modification Anomalies

(iii) Deletion Anomalies

2
Relational Database Model
Background: E. F. Codd (of IBM)
Current industry standard
Basic structure
- Table (= relation)
- Tuples (= rows) and attributes (= columns)
- Database:
- Key: "unique identifier"
- Integrated information is gathered through the linking of common fields in different tables.
Database Models: Method of data storage so the database can be maintained (ie, insertion, modification,
and deletion) and queried correctly and efficiently.

Database Management Systems (DBMS)


Database Management System (DBMS): The computer system that helps you to build, maintain, and
query a database with ease.

Relational Database Management Systems:


Computer systems that are designed to support relational database model.
Structured Query Language (SQL), or fourth-generation language (4GL) enables ad-hoc queries
Data Definition Language (DDL) and Data Manipulation Language (DML)
Enforce relational database model rules.
Advantages
Complex internal "engine", but well hidden from the end users.
Accompanied by other utilities such as report generation and data dictionary.
Disadvantages
- Substantial hardware/software support

Exercise 1.1
ENROLLMENTS
SNum Sname Address Phone Status CNum Ctitle CrHr Grade
101 Andy 123 Main 617-111-1111 Freshman 380 Database 3 A
102 Betty 321 Main 617-222-2222 Freshman 380 Database 3 B
103 Cindy 789 Main 617-333-3333 Sophomore 385 System Analysis and Design 3 A
104 Debby 987 Main 617-444-4444 Senior 385 System Analysis and Mgmt 3 A
102 Betty 999 Joy St 508-324-4956 Freshman 385 System Analysis and Design 3 C
104 Debra 987 Main 617-444-4444 Senior 300 Intro to MIS 3 A

According to the above ENROLLMENTS file.

1. How many records are there in this table?

2. How many fields are there in this table?

Apparently, there are many design problems with this table. Please identify problems in the following areas:

4. Data Redundancy: Which data are redundant? Name all that you can find.

5. Data Inconsistency: Which data are inconsistent? Name all that you can find.

3
6. The above design induces insertion anomalies. Give me an example of how such an anomaly may occur.

7. The above design induces modification anomalies. Give me an example of how such an anomaly may occur.

8. The above design induces deletion anomalies. Give me an example of how such an anomaly may occur.

Exercise 1.2
A better design of the above table is the following structure.

Students
SNum Sname Address Phone Status

Courses Enrollments
CNum Ctitle CrHr SNum CNum Grade

1) Fill in the data value from Exercise 1.1.


2) How would this structure reduce
Insertion anomaly
Modification anomaly
Deletion anomaly

Exercise 1.3
SalesOrders
SO# SODate CustNum CustName CustZip CustType P# PName Price Qty
101 8/1/2015 101 Andy 90211 Basic P1 Paper $2.00 10
102 8/3/2015 102 Betty 90212 Premium P1 Paper $2.00 5
103 8/3/2015 103 Cindy 90213 Premium P1 Paper $2.00 10
104 8/6/2015 101 Andrew 90211 Basic P2 Pen $1.50 10
105 8/7/2015 103 Cindy 90218 Premium P2 Pencil $1.50 10
106 8/7/2015 104 David 90214 Basic P4 Printer $99.99 5

According to the above SalesOrders file.

1. How many records are there in this table?


4
2. How many fields are there in this table?

Apparently, there are many design problems with this table. Please identify problems in the following areas:

4. Data Redundancy: Which data are redundant? Name all that you can find.

5. Data Inconsistency: Which data are inconsistent? Name all that you can find.

6. The above design induces insertion anomalies. Give me an example of how such an anomaly may occur.

7. The above design induces modification anomalies. Give me an example of how such an anomaly may occur.

8. The above design induces deletion anomalies. Give me an example of how such an anomaly may occur.

Exercise 1.4
A better design of the above table is the following structure.

Customers Products
CustNum CustName CustZip CustType P# Pname Price

SalesOrders
SO# SODate CustNum P# Qty

1) Fill in the data value from Exercise 1.3.


2) How would this structure reduce
Insertion anomaly
Modification anomaly
Deletion anomaly

5
Relational Database Concepts
Entity, instance, and Attributes
Entity (some call it entity set)
- A conceptual collection of things, such as .

Instance (some call it entity instance)


- A specific existence of/in the entity, such as .

Attributes
- Each entity has certain characteristics (attributes), such as __________________.

Table
Table (Relation): a logical unit of the relational database.
Table: an entity
Tuple: an instance
Attributes: characteristics of the entity
- Selection/Design of attributes

Characteristics of a Table
1. It's a two-dimensional structure
2. Row
A single entity instance
Each row carries information describing an entity's attributes.
3. Column
entity's attribute
Each column has a distinct name
All the values in a column match the entity's row characteristics.
Colume's range of permissible values is know as the domain.
4. Each row/column intersection contains only one single data value.
- numeric,
- character,
- date,
- logical.
5. The order of rows and columns are immaterial to the user.

Keys and Functional Dependency


Key: an attribute(s) that acts as a unique identifier of the record.
- Composite key: a key composed of multiple attributes.

Exercise 1.5
Students Courses
Snum LastName FirstName Major GPA Dept CNum Title CrHr
101 Jones Andy IS 2.5 IS 300 Intro to MIS 3
102 Jones Betty IS 2.8 IS 310 Statistics 3
103 Lee Cindy FIN 3.1 IS 380 Database 3
104 Johnson David FIN 2.4 MKT 300 Intro Marketing 3
105 Smith Ellen MKT 3.8 MKT 310 Marketing Research 3
106 Smith Frank IS 3.8 CS 220 Database 3

1) What is the unique identifier to the STUDENTS table?


2) What is the unique identifier to the COURSES table?

3) Is LastName+FirstName a unique identifier to the STUDENTS table?


6
4) Is CNum a unique identifier to the COURSES table?

5) Is SNum+LastName a unique identifier of the STUDENTS table?

Exercise 1.6
Identify possible unique identifiers of the SchClasses table

SchClasses
CallNum Dept Code Section Year Semester Day Time Room Instructor
10001 IS 300 1 2013 Fall M 4-7 CBA 112 Lee
10002 IS 300 2 2013 Fall W 4-7 CBA 108 Lee
10003 IS 300 3 2013 Fall W 4-7 CBA 118 Johnson
10008 IS 310 1 2013 Fall Tu 7-10 CBA 111 Jones
10009 IS 310 2 2013 Fall F 1-4 CBA 111 Jones
10045 FIN 300 1 2013 Fall M 4-7 CBA 111 Smith
10046 FIN 300 2 2013 Fall W 4-7 CBA 237A Smith
10241 IS 300 1 2014 Spring M 4-7 CBA 218 Lee
10242 IS 300 2 2014 Spring W 4-7 CBA 111 Jones
10255 FIN 300 1 2014 Spring M 1-4 CBA 123 Smith
10256 FIN 300 2 2014 Spring W 7-10 CBA 123 Smith

==

Functional Dependency (FD)


Attribute B is functionally dependent on attribute A if each value (cell) in attribute A determines (identifies) one
and only one value in column B. It can also read "Attribute A functionally determines attribute B." Also written as:
A B
reads: A functionally determines B
(or) B is functionally dependent on A

Example: SSN FirstName


Note!! The word "determine" means "identify"
Also, A B, C means A B and A C
A+B C means A and B together identifies C
Question: Does SNum+Lastname Firstname?

Fully Functional Dependency (FFD)


Attribute B is fully functionally dependent on attribute A if B is FD on a composite key of A but not on any sub set
of the composite key.

==
Superkey: unique identifier
- Any key that uniquely identifies each entity instance.
- Allow "redundancy" within the key.
- SNum + LastName is a superkey! (LastName is redundant since SNum alone can do the job).
- i.e., "A is a superkey of table T" means "A functionally determines values of other columns in table T".

Candidate key: non-reducible unique identifier


- A super key without the redundancy, or, a "minimal" superkey.
- There can be several candidate keys in one table.
- i.e., "A is a candidate key of table T" means "A fully functionally determines values of other columns in
table T".

Primary key (PK)

7
- a candidate key selected (by the database designer, a human) to uniquely identify other attribute values for
any given row.
- A table should have one and only one primary key.
- Selection/Design of Primary Key

Entity Integrity Rule:


A table has entity integrity if
(1) the chosen primary key can UNIQUEly identify each row, AND
(2) there is NO NULL value in the primary key column(s).

Foreign key (FK)


- An attribute(s) in one table whose value references another table's candidate key.
- Referential Diagram
- Where does foreign key come from?
- A table can have 0~N foreign keys, depending on the circumstances.

Referential Integrity Rule:


A table has referential integrity if every value in the foreign key EITHER
(1) finds a MATCH in the referenced table, OR
(2) is NULL.
(In other words, we do not want to reference something that does not exist.)

Questions:
(1) To have referential integrity, every value in the foreign key must match the value in the referenced table. Is the
reverse true?

(2) Within one table, is there any definite relationship between its primary key and foreign key?

(3) In one table, can there be multiple foreign keys?

Secondary key
- An attribute(s) used strictly for data retrieval purposes, such as searching by DateOfBirth.

Exercise 1.7
The following are sample data of CSULB students. Each student has a social security number (SSN) and a CSULB
student ID.

Students
SSN CSULB_ID LastName FirstName DOB Major GPA
454-13-1001 000011121 Jones Andy 1/1/1992 IS 2.5
454-13-1002 000011122 Jones Andy 1/1/1992 IS 2.8
454-13-1003 000011123 Lee Cindy 3/1/1992 FIN 3.1
454-67-0394 000011124 Johnson David 3/1/1993 FIN 2.4
454-98-3342 000011125 Smith Ellen 4/1/1990 MKT 3.8
454-22-3566 000011126 Smith Frank 1/1/1990 IS 3.8

Identify
4 super keys
all candidate keys
a primary key
of the STUDENTS table.

Exercise 1.8
8
For the following table, specify
(a) 2 superkeys
(b) all candidate keys
(c) a primary key

SchClasses
CallNum Dept Code Section Year Semester Day Time Room Instructor
10001 IS 300 1 2013 Fall M 4-7 CBA 112 Lee
10002 IS 300 2 2013 Fall W 4-7 CBA 108 Lee
10003 IS 300 3 2013 Fall W 4-7 CBA 118 Johnson
10008 IS 310 1 2013 Fall Tu 7-10 CBA 111 Jones
10009 IS 310 2 2013 Fall F 1-4 CBA 111 Jones
10045 FIN 300 1 2013 Fall M 4-7 CBA 111 Smith
10046 FIN 300 2 2013 Fall W 4-7 CBA 237A Smith
10241 IS 300 1 2014 Spring M 4-7 CBA 218 Lee
10242 IS 300 2 2014 Spring W 4-7 CBA 111 Jones
10255 FIN 300 1 2014 Spring M 1-4 CBA 123 Smith
10256 FIN 300 2 2014 Spring W 7-10 CBA 123 Smith

Exercise 1.9
Identify primary key and foreign key of each table.

Students Enrollments
Snum Sname Major GPA Snum CallNum Grade
101 Andy IS 2.5 101 10001 A
102 Betty IS 2.8 101 10009 B
103 Cindy FIN 3.1 101 10045 C
104 David FIN 2.4 102 10001 D
105 Ellen MKT 3.8 106 10001 A
106 Frank IS 3.8 102 10241
103 10241
SchClasses
CallNum Dept Code Section Year Semester Day Time Room Instructor
10001 IS 300 1 2013 Fall M 4-7 CBA 112 Lee
10002 IS 300 2 2013 Fall W 4-7 CBA 108 Lee
10003 IS 300 3 2013 Fall W 4-7 CBA 118 Johnson
10008 IS 310 1 2013 Fall Tu 7-10 CBA 111 Jones
10009 IS 310 2 2013 Fall F 1-4 CBA 111 Jones

Exercise 1.10
STUDENTS ADVISORS
SNum SName Address Phone AdvNum AdvNum ADVNAME ADVOFFICE
101 Andy 123 Main 562-985-1001 99 77 Lee CBA 100
102 Betty 321 Main 562-985-1002 88 88 Lee CBA 100
103 Cindy 789 Main 562-985-1003 99 Lee CBA 233
104 David 987 Main 562-985-1004 88

The following keys are identified:

STUDENTS ADVISORS
Primary Key: SNum AdvNum
Foreign Key: AdvNum, references Advisors.AdvNum None

Answer the following questions:


(1) Does the STUDNETS table have entity integrity? Why or why not?
(2) Does the STUDENTS table have referential integrity? Why or why not?
(3) Does the ADVISORS table have entity integrity? Why or why not?
(4) Does the ADVISORS table have referential integrity? Why or why not?

Exercise 1.11
9
SUPPLIERS
SNUM SNAME STATUS CITY
S1 Smith 20 London Primary Key: SNUM
S2 Jones 10 Paris
S3 Blake 30 Paris Foreign Key: none
S4 Clark 20 London
S5 Adams 30 Athens

PARTS
PNUM PNAME COLOR WEIGHT CITY
P1 Nut Red 12 London Primary Key: PNUM
P2 Bolt Green 17 Paris
P3 Screw Blue 17 Rome Foreign Key: none
P4 Screw London
P5 Cam Blue 12 Paris
P6 Cog Green 19 London

PROJECTS
JNUM JNAME CITY
J1 Sorter Paris Primary Key: JNUM
J2 Display Rome
J3 OCR Foreign Key: none
J4 Console Athens

SPJ
SNUM PNUM JNUM QUANTITY
S1 P1 J1 300
S1 P2 J4 200 Primary Key: SNUM+PNUM+JNUM
S1 P3 J1 400
S1 P4 J2 200 Foreign Keys:
S1 P1 J1 300 1. SNUM, references SUPPLIERS.SNUM
S1 P8 J2 100 2. PNUM, references PARTSS.PNUM
S2 P1 J1 300 3. JNUM, references PROJECTS.JNUM
S2 P2 J2 400
S3 P2 J3 200
S4 P2 J1 200
S4 P4 J2 300
S4 P5 J3 400

1. Does each of the tables have Entity Integrity? Why or Why not?

SUPPLIERS

PARTS

PROJECTS

SPJ

2. Does each of the tables have Referential Integrity? Why or Why not?

SUPPLIERS

PARTS

PROJECTS

SPJ

10
Exercise 1.12
Identify the primary key(s) and foreign key(s) of the following tables.

COURSES
CNum TITLE
IS 233 MS Office
IS 300 Intro to MIS Primary Key:
IS 301 Business Communications
IS 310 Statistics Foreign Key:
IS 340 Programming
IS 380 Database
IS 385 System Analysis and Design
IS 480 Advanced Database

PREREQ
CNum PrereqCNum
IS 300 IS 233
IS 340 IS 300 Primary Key:
IS 340 IS 310
IS 380 IS 300 Foreign Key:
IS 380 IS 310
IS 385 IS 340
IS 385 IS 380
IS 480 IS 380

Exercise 1.13
Identify primary key and foreign key(s) of each table.

COURSES Enrollments
Dept CNum Title SNum CallNum Grade
IS 300 Intro to MIS 101 10001 A
IS 301 Bus Comm 103 10001 B
IS 310 Statistics 104 10001 A
IS 380 Database 101 10004 A
IS 385 Systems 102 10001 B
IS 355 Telecomm 102 10004 C

PREREQ INSTRUCTORS
Dept CNum Pre_Dept Pre_CNum INum IName Office
IS 380 IS 300 91 Lee CBA 428
IS 380 IS 301 92 Smith CBA 422
IS 355 IS 300 93 Jones CBA 435
IS 385 IS 380

SchClasses STUDENTS
CallNum Dept CNum Section Room INum SNum SName Major
10001 IS 300 1 117 91 101 Andy IS
10002 IS 300 2 108 91 102 Betty ACC
10003 IS 300 3 121 92 103 Cindy
10004 IS 310 1 121 92 104 David IS
10005 IS 310 2 122 93 105 Ellen FIN
10006 IS 380 1 117 91

Exercise 1.14
The following is a database about employees and their job description and benefit plan. Note that each employee
may have multiple benefit plans.
1) For each table, identify its primary key and foreign key(s).
2) For each table, explain whether it has Entity Integrity? Why or Why not?
3) For each table, explain whether it has Referential Integrity? Why or Why not?

11
EMPLOYEES BENEFITS
EMP_CODE EMP_LNAME JOB_CODE EMP_CODE PLAN_CODE
14 Rudell 2 15 2
15 McDade 1 15 3
16 Ruellardo 1 16 1
17 Smith 3 17 1
20 Smith 2 17 3
17 4
20 3

JOBS PLANS
JOB_CODE JOB_DESCRIPTION PLAN_CODE PLAN_DESCRIPTION
1 Clerical 1 Term Life
2 Technical 2 Stock Option
3 Managerial 3 Long-Term Disability
4 Dental

Exercise 1.15
DCode DName ENum EName JCode HourlyRate WeekNum HoursWorked EPhone
MKT Marketing 101 John D. Newson RA $15.00 1 15 653-234-3245
MKT Marketing 101 John D. Newson RA $15.00 2 18 653-234-3245
MKT Marketing 110 Anne R. Ramoras TA $12.00 1 20 615-233-5568
IS Info Systems 108 June H. Sattlemeir RA $15.00 2 19 905-554-7812
IS Info Systems 108 June H. Sattlemeir RA $15.00 3 17 905-554-7812
IS Info Systems 101 John D. Newson RA $15.00 1 20 653-234-3245
FIN Finance 105 David F. Schwann TA $12.00 1 11 615-233-5568
FIN Finance 105 David F. Schwann TA $12.00 3 23 615-233-5568

DCode: Department Code; DName: Department Name


ENum: Employee Number; EName: Employee Name; EPhone: Employee Phone
JCode: Job Code; RA=Research Assistant, TA=Teaching Assistant, PT=Part Time helper
WeekNum: Week Number: 1 for week 1, 2 for week 2, etc.
HoursWorked: The number of hours this employee has worked during this week

Assumptions:
* Each employee has one name and one phone number. Also, each employee can only have one job code.
* Each job code pays the same hourly rate; that is, RA is always paid $15 an hour and TA is always
$12/hour.
* Each employee can work for different department; each with an "HoursWorked" per week.

Apparently, there are many potential problems with this table design. A better design of the database consists of the
following 4 tables:

DEPT(DCode, DName)
EMP(ENum, EName, JCode, EPhone)
JOBS(JCode, HourlyRate)
WORK(DCode, ENum, WeekNum, HoursWorked)

1) Re-write the data values of these 4 tables.

2) For each table, identify the primary key and foreign key(s).

Homework 1. Relational Concept


Due date:

12
Topic 2. Relational Database Operators
Relational Algebra: Algebra performed on tables.

1. UNION
Combine two tables that have identical attributes
The two tables must be union compatible

2. INTERSECT
Produce a list that contains rows that appear in both tables.
The two tables must be union compatible

3. DIFFERENCE -
Table1 DIFFERENCE Table2 yields all rows found in TABLE1 but not TABLE2.
The two tables must be union compatible
Oracle calls this minus

4. PRODUCT
TABLE1 PRODUCT TABLE2 yields a list with all possible pairs of rows from two tables.
If TABLE1 has x attributes and TABLE2 has y attributes, the resulting table has _______ attributes.
If TABLE1 has m rows and TABLE2 has n rows, the resulting table has ________ rows.

5. SELECT
- SELECT TABLE1 [Condition] yields a list contains rows in TABLE1 that satisfy the Condition (i.e., a
horizontal subset of the table).
- You can use the following operators: =, <>, !=, >=, <=, >, <, and, or, not

6. PROJECT
- PROJECT TABLE1 [Column1, Column2,...] yields a list contains [Column1, Column2,...] (i.e., a
vertical subset of the table).

7. JOIN
- Combine information from two tables. The common column is called the "join column".

13
Exercise 2.1
Business Engineering
SNum SName Phone Status SNUM SNAME PHONE STATUS
101 Andy 562-985-1001 Senior 104 David 562-985-1004 Junior
102 Betty 562-985-1002 Junior 105 Ellen 562-985-1005 Senior
103 Cindy 562-985-1003 Senior 106 Frank 562-985-1006 Freshman
104 David 562-985-1004 Junior 107 George 562-985-1007 Junior
105 Ellen 562-985-1005 Senior

Enrollments
SNUM COURSE SEMESTER GRADE
101 IS 380 2013 Sp A
105 CE 249 2013 Sp B
101 CE 249 2013 Fa A
103 IS 480 2013 Fa C

What will the followings display?

1. Business UNION Engineering

2. Business INTERSECT Engineering

3. Business DIFFERENCE Engineering

4. Business PRODUCT Engineering

5. SELECT from ENROLLMENTS where grade = 'A'

6. PROJECT snum, course from ENROLLMENTS

7. Show step by step algebra to retrieve names of all students who are Junior.

14
Exercise 2.2
STUDENTS ENROLLMENTS
SNum SNAME STATUS Major Zip GPA SSN CNUM Semester Grade
101 Andy Junior IS 91101 3.1 101 380 2012 Sp A
102 Betty Senior MKT 91102 2.8 101 355 2012 Sp B
103 Cindy Freshman ACC 91101 2.5 102 380 2012 Sp F
104 David Junior 91103 3.4 102 380 2012 Fa
105 Ellen Sophomore MKT 91104 3.2 101 480 2012 Fa
103 355 2012 Fa B
102 385 2012 Fa A

1. Show step-by-step algebra to find name of students who are IS major.

2. Show step-by-step algebra to find SNum and name of students who are IS major and has GPA higher than 3.0.

3. Show step-by-step algebra to find SNum and name of students whose GPA is between (and including) 3.0 and 3.3.

4. Show step-by-step algebra to find SNum of students who do not live in zip code 91101.

5. Show step-by-step algebra to find SNum and name of students who are already junior or senior, but who do not
have a major.

6. Show step-by-step algebra to display SNum of students who have never enrolled in any class.

7. Show step-by-step algebra to display SNum of students who took both 380 and 355.

8. Show step by step algebra to find students who have never received an A. (three pepper question hot hot hot!!)

15
Exercise 2.3
Students Enrollments Courses
SNum Sname Major SNum CNum Grade CNum Ctitle Instr
101 Andy IS 101 IS380 B IS380 Database Lee
102 Betty FIN 101 IS385 A IS385 Systems Smith
103 Cindy IS 102 IS380 A IS355 Telecomm Lee
103 IS355 B

(for your reference...)


Students X Enrollments
S# Sname Major S# C# Grade
101 Andy IS 101 IS380 B
101 Andy IS 101 IS385 A
101 Andy IS 102 IS380 A
101 Andy IS 103 IS355 B
102 Betty FIN 101 IS380 B
102 Betty FIN 101 IS385 A
102 Betty FIN 102 IS380 A
102 Betty FIN 103 IS355 B
103 Cindy IS 101 IS380 B
103 Cindy IS 101 IS385 A
103 Cindy IS 102 IS380 A
103 Cindy IS 103 IS355 B

Write step by step algebra to...


1. Display CNum and Grade of courses Andy took.

2. Display SNum and SName of students who took IS 380.

3. Display SNum and SName of students who took IS 380 and received an 'A'.

4. Display SNum and SName of students who are IS major and took IS380.

6. Display SNum and SName of students who took IS380 but not an IS major.

7. Display SNum of students who took the Telecomm course.

16
8. Display SNum of students who received an A from any of Lees class.

9. Display CNum and CTitle of courses that Andy took.

10. Display SNum and SName of students who are in the Telecomm class.

11. Display SNum and SName of students who have Lee as an instructor.

Homework 2. Relational Algebra


Due on

Instructions: Hand-written answers are acceptable. Be clear and to the point.

According to the four tables in the following, use appropriate relational algebra to derive the answers.

(1) Write step-by-step relational algebra retrieve the ECode of employees whose last name is "Smith" .

(2) Write step-by-step relational algebra to retrieve last name of employees whose job description is "Clerical".

(3) Write step-by-step relational algebra to retrieve last name of employees who has Stock Option benefit.

(4) Write step-by-step relational algebra to retrieve name of employee whose job description is Technical and who
has Stock Option benefit.

(5) Write step-by-step relational algebra to retrieve ECode of employees who do not have any benefit plans.

EMPLOYEES BENEFITS
ECode EName JCode ECode PCode
14 Rudell 2 15 2
15 McDade 1 15 3
16 Ruellardo 1 16 1
17 Smith 3 17 1
20 Smith 2 17 3
17 4
20 3
JOBS PLANS
JCode JDesc PCode PDesc
1 Clerical 1 Term Life
2 Technical 2 Stock Option
3 Managerial 3 Long-Term Disability
4 Dental

17
Topic 3. Structured Query Language (SQL)
For a complete reference, refer to
Textbook Chapter 3. An Introduction to Structured Query Language
Oracle Chapter 3. The Basic Parts of Speech in SQL
Oracle Chapter 14. Changing Data: Insert, Updates, and Delete
Oracle Chapter 17. Creating, Dropping, and Altering Tables and Views

Fourth generation language (4GL):


Users specify "what" must be done without specifying "how" to do it.

Most query language used by the relational database management system is structured query language (SQL).

SQL can do
1. Data definition
2. Data management
3. Data query

Data Definition Language (DDL)


Create a database
Create a table
- Columns names, data types
Delete a table
Modify a table structure
- Add a column(s)
- Modify the column's data type

Data management Language (DML)


Insert new records
Update existing records
Delete records

Query
Asking database questions or view the table from different perspective/criterion without modifying the content.

1. Basic relational algebra


Display certain columns from one table
Display records based on certain conditions
Join two or more tables
Union, Intersection, Minus
Combinations of above operations
2. Group by different levels
3. View and Report

18
Topic 4. Basic SQL
Data Definition Language (DDL)
Creating a Table
create table t
(fd_name1 fd_type,
fd_name2 fd_type, ...);

create table students


(ssn char(9),
LastName varchar2(30),
FirstName varchar2(30),
DateofBirth date,
EntranceDate date,
GPA number(3,2));

* field types: char(n)


varchar2(n)
date
number(x,n)

Dropping a Table (deleting a table)


drop table t;
drop table customer;

truncate table t;
truncate table customer;
/* delete all records in the table but not the field definitions */

Add Column(s)
alter table t add (fx fd_type, fy fd_type);
alter table students add (zip char(5), phone char(10));

Modify Column Definition


alter table table_name modify (f1 new_type, f2 new_type, ...);
alter table students modify (LastName varchar2(50));
/* Certain restrictions apply. See Oracle reference */

Display Table Structure


To see the columns and column definitions of the table
describe t;
describe students;

Display Tables in Your Account


select table_name from user_tables;

Writing comments
You can write comments in the program.

1) Line comments: use --, it only works for one line


-- This is my first oracle program

2) Block comments: use /* and */ to block the comments. It can be multiple lines.
/* Program Name: Split Orders

19
Purpose: Split sales orders by warehouse code
Approved by: Jill Smith */

Note! you need to include at least one space after /* and the actual comments. Otherwise, you may have
unexpected results when running the program!!

Data Management Language (DML)


Insert Records
insert into t values (f1value, f2value,...);
insert into t (f1, f2,...) values (f1value, f2value,...);

Note: For character fields, the data value is enclosed in single quotation mark, such as 'John'.
For numeric fields, no quotation mark is necessary, such as 673.25.
For date fields, the default format is 'dd-mon-yy', such as '27-jan-05'.

Delete Records
delete from t
where [conditions];

Update Records
update t
set f1=newvalue1,
f2=newvalue2,
f3=newvalue3
where [conditions];

Save and Undo prior insert/update/deletes


commit;
rollback; /* Undo, save to the last "commit" status */
Note: rollback only works on DML commands. DDL commands are automatically commited.
Note: What is the difference between
Truncate table t;
and
Delete from t;

Data Query
Display Records
select [columns]
from [table]
where [conditions];

select ssn, sname from students


where major='IS';

select ssn, sname from students


where major='IS'
and gpa > 3;

select ssn, sname from students;

select * from students


where major='IS';

select * from students;

20
Conditions
Mathematical and Logical operators
=, <>, !=, >, <, >=, <=, and, or, not
ex: ... where price > 10;
ex: ... where price > 10 and code <> 1234;

Wild Card command: like


Compares to similar character string
% represents any group of characters
_ represents one character

ex: ... where name like 'J%';


... where name like '__y;

in
select sname from stu where major in (IS,Finance,Marketing);
select sname from stu where major not in (IS,Finance,Marketing);

null
select sname from stu where major is not null;
select sname from stu where major is null;
select sname from stu where major=null; /* This does NOT work */

update students set major = null where snum=111;

Sorting
Order by
default is ascending.
... order by f1;
add DESC for descending
... order by f1 desc;

Exercise 4.1
Write the SQL code for the following operations

1. Create a table named STU with the following columns


SSN varchar2(9)
Name varchar2(10)
Major varchar2(10)

2. Insert a student record into the STU table. Students SSN is 111, name is Andy, and major is IS.

3. Insert another student record into the STU table. Students SSN is 222, name is Betty, and major is Finance.

4. Save the records to the STU table.

5. Display all records of the STU table.

6. Display the name column of the STU table.

7. Display the name of student whose major is IS.

21
8. Delete the student record whose SSN is 222.

9. Undo the deletion of problem 8.

10. Add a new column to the STU table. The column name is GPA, and data type is number(3,2).

11. Andys GPA is 3.52. Update this data into the STU table.

12. Bettys GPA is 2.81. Update this data into the STU table.

13. Display the name of student whose GPA is greater than 3.0 and who is IS major.

14. Display all records of the STU with descending order of GPA (that is, the student of highest GPA will be
displayed at first, the second highest at second, etc.)

22
Topic 5. Introduction to ORACLE
Step 1. Log in to ORACLE

Open SQL: Start Programs Oracle . SQL Plus

Log in: A log in screen appears. Log in to ORACLE by (not case sensitive):

Username
Password
Host

If you are using the computer labs at CBA --


Your username and password will be announced in class.

If you plan to install Oracle 11g on your home computer


the username/password are specified during the installation; they are not related to school.

You should see the SQL> prompt now.

Log off: To log-off from Oracle, type exit at the prompt. Another way to exit is to close the window. Make sure
you exit Oracle properly.

Step 2. Write SQL commands in a Notepad file

Open Notepad: Choose Start - Programs Accessories Notepad


(Note: I personally like a small editor called EditPad. It is compact and can display multiple files. You can do a
search on google and get free download.)

At the Notepad file, enter the following commands:

choose File Save.

File Extension: Always name your Oracle program with the .sql extension. Since Notepad automatically adds a .txt
extension to all file names, make sure you select All files under Save as type:
23
Under Save as type, select All Files. Under File name, enter myprog1.sql . Save this file to your local drive;
preferably under a folder. (Note! Do not have any spaces in your folder name. Your life will be a lot easier!!)

Oracle Commands:
set echo on this tells Oracle to display your commands when running it.
spool f:myprog1.txt this tells Oracle to record screen output to the file myprog1.txt on your local drive.
The recording stops when the program comes to the spool off command. It is common practice to call your SQL
program files .sql and output (spool) file .txt.
drop table stu; This is the common practice to delete old, existing tables before your create table...
command. Since your account is brand new, this will result in a Table or View Not Exist... error message the first time
you run it -- which is alright. You will see the benefit once you run your program again later.

Step 3. Run the Program

Go back to the Oracle SQL*Plus window (by clicking anywhere on that window).

To run your program, the keyword is start. At the SQL prompt, enter

SQL> start a:myprog1.sql

press [enter]. The program will be executed.

Your output should look something like this:

24
SQL> spool a:myprog1.txt
SQL>
SQL> drop table stu;
drop table stu
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL>
SQL> create table stu (
2 ssn char(9),
3 name char(10),
4 major char(10));

Table created.

SQL>
SQL> insert into stu values ('111','Andy','IS');

1 row created.

SQL> insert into stu values ('222','Betty','finance');

1 row created.

SQL>
SQL> select * from stu;

SSN NAME MAJOR


--------- ---------- ----------
111 Andy IS
222 Betty finance

SQL>
spool off

Your execution should look similar to this. Scroll the window up or [PageUp] to check your execution. If you do not
see any problems, thats great! You can go directly to Step 5. Otherwise, you need to debug your program. Go to
Step 4.

Step 4. Debug the Program

If there is any unintended error message (which is quite normal), you can edit your program file and run it again (this
process is called debugging). Go to the Notepad window and check if there is any typos. Repeat Step 3 to run it
again. Do this until there is no error.

Step 5. View and Print your spool file

with the spool a:myprog1.txt command, your screen output is now captured in the file a:myprog1.txt.

To view it, go to Notepad and choose File Open ..., and open a:myprog1.txt.

You will see the screen output of your a:myprog1.sql program.

If you want to print it, choose File Print.

** This is the way that you will turn in most of the homework!

Step 6. Write and Run another program

Lets write another Oracle program which would query the STU table that you just created.
25
Go to Notepad and choose File New.

At the Notepad file, enter the following commands:

/* Program 2. Query the STU table */

set echo on

spool a:myprog2.txt

select * from stu;


select name from stu where major='IS';
insert into stu values ('333','Cindy','IS');
commit;
select name from stu where major='IS';

spool off

now choose File - Save. Specify the new file name to be a:myprog2.sql.

Go back to Oracle SQL*Plus.

To run your program, at the SQL prompt, enter

SQL> start a:myprog2.sql

press [enter], and see what happens.

with the spool a:myprog2.txt command, your screen output is now captured in the file a:myprog2.txt.

To view it, go to Notepad and choose File Open ..., and open a:myprog2.txt.

You will see the screen output of your a:myprog2.sql program.

If you want to print it, choose FilePrint.

Step 7. Write Commands Directly at the SQL> Prompt

You can also write commands directly at the SQL> prompt.

At the SQL> prompt, write

SQL> select * from stu;

Press [Enter], and see the command being executed.

Note: Usually people write commands in a text file so they can be executed together. The program is sometimes
called a "script". If you have several commands that you are likely to rerun them in your future, it is better to write
them in a script file so you do not have to type them over and over again. However, if you just want to check
something quickly, you can enter the command directly at the SQL> prompt.

Exercise 5.1
Make sure you can do the following without any problem.

1. Write the following SQL codes in a myprog3.sql file. Make sure you have set echo on in the beginning of the
file. Also, spool your output to a file named myprog3.txt.

select * from stu;


26
select * from stu where ssn=333;
select ssn, name from stu where ssn=333;

2. Run myprog3.sql until there is no error.


3. View the content of myprog3.txt.

Homework 3. SQL
Due on

Instructions:
Write the following SQL commands in a hw3.sql file. Make sure you have set echo on in the beginning of the file.
Also, spool your output to hw3.txt. Run hw3.sql until there is no error. Turn in a print out of the hw3.txt.
You are encouraged to use comments to clearly label each question.
You should start by writing, saving, and running a few commands, then gradually add more commands to your
program.

===
1. Write an SQL command to delete a table named STUDENTS.
2. Write an SQL command to create the STUDENTS table, with the following columns:
SSN char(9)
Lastname char(10)
Firstname char(10)
Major char(10)
GPA number(3,2)
DOB date

3. Write SQL commands to insert the following 4 student records into the STUDENT table.
SSN Lastname Firstname Major GPA DOB
101 Smith Johnny IS 3.41 5/18/92
102 Smith Jack FIN 3.25 3/11/90
103 Meyer Jim HRM 2.82 10/11/91
104 Brown Jenny IS 2.78 4/4/91

4. Write an SQL command to display all records of the STUDENTS table.


5. Write an SQL command to insert a new student record. This students SSN is 105. Her last name is Lee and first
name is Jamie. Her birthday is April 1, 1983. We have no information of her major and GPA, so leave them
blank.
6. Write an SQL command to save all records.
7. Write an SQL command to display only the last name and first name of all students.
8. Write an SQL command to display the last name and first name of all students whose GPA is higher than 3.
9. Write an SQL command to display all columns of students whose major is not IS.
10. Write an SQL command to display students whose first name start with the letter J and last name start with the
letter S.
11. Write an SQL command to change student 101s major to FIN.
12. Write an SQL command to undo the change of 101s major (that is, student 101s major is still IS.)
13. Write one SQL code to change student 102s major to MKT and GPA to 3.3.
14. Write an SQL command to add a new column to the STUDENTS table. The new columns name is ASSOCIATION
and its data type is varchar2(15).
15. Write an SQL command to enter the Association to be ISSA for all IS major students.
16. Write an SQL command to delete student 103s record.
17. Write an SQL code to display student records with descending order of GPA (student with the highest GPA is
displayed first).
18. Write an SQL command to display students who do not have a major (major code is null).
27
19. 101 wants to become undeclared. Write an SQL command to make his major null.
20. Write a SQL command to save all changes.

28
Topic 6. JOIN
Join is done by product, select, and project in one SELECT statement

SELECT [columns]
FROM [tables]
WHERE [conditions];

SQL> select * from students;

SNUM SNAME STANDING MAJOR GPA ADVNUM


---- ------ ---------- -------- ----- ------
101 Andy Junior IS 3.50 91
102 Betty Senior MKT 3.20 93
103 Cindy Sophomore IS 2.80 92
104 David Junior ACC 3.10 92

SQL> select * from advisors;

ADVNUM ADVNAME ADVOFFICE


------ --------------- ---------
91 Lee 9859001
92 Jones 9859002
93 Smith 9859003

SQL> -- select both tables is a "product"


SQL> select * from students, advisors;

SNUM SNAME STANDING MAJOR GPA ADVNUM ADVNUM ADVNAME ADVOFFICE


---- ------ ---------- -------- ----- ------ ------ --------------- ---------
101 Andy Junior IS 3.50 91 91 Lee 9859001
102 Betty Senior MKT 3.20 93 91 Lee 9859001
103 Cindy Sophomore IS 2.80 92 91 Lee 9859001
104 David Junior ACC 3.10 92 91 Lee 9859001
101 Andy Junior IS 3.50 91 92 Jones 9859002
102 Betty Senior MKT 3.20 93 92 Jones 9859002
103 Cindy Sophomore IS 2.80 92 92 Jones 9859002
104 David Junior ACC 3.10 92 92 Jones 9859002
101 Andy Junior IS 3.50 91 93 Smith 9859003
102 Betty Senior MKT 3.20 93 93 Smith 9859003
103 Cindy Sophomore IS 2.80 92 93 Smith 9859003
104 David Junior ACC 3.10 92 93 Smith 9859003

12 rows selected.

SQL> -- specify the condition for join


SQL> select * from students, advisors
where students.advnum=advisors.advnum;

SNUM SNAME STANDING MAJOR GPA ADVNUM ADVNUM ADVNAME ADVOFFICE


---- ------ ---------- -------- ----- ------ ------ --------------- ---------
101 Andy Junior IS 3.50 91 91 Lee 9859001
102 Betty Senior MKT 3.20 93 93 Smith 9859003
103 Cindy Sophomore IS 2.80 92 92 Jones 9859002
104 David Junior ACC 3.10 92 92 Jones 9859002

SQL> -- Display name, major, and gpa of student whose advisor is 'Jones'
SQL> select sname, major, gpa
from students, advisors
where advname='Jones'
and students.advnum=advisors.advnum;

SNAME MAJOR GPA


------ -------- -----
Cindy IS 2.80
David ACC 3.10

29
S P SP
S# SName Status CITY P# PNAME COLOR WEIGHT CITY S# P# QTY
S1 Smith 20 London P1 Nut Red 12 London S1 P1 300
S2 Jones 10 Paris P2 Bolt Green 17 Paris S1 P2 200
S3 Blake 30 Paris P3 Screw Blue 17 Rome S1 P3 400
S4 Clark 20 London P4 Screw Red 14 London S1 P4 200
S5 Adams 30 Athens P5 Cam Blue 12 Paris S1 P5 100
P6 Cog Red 19 London S1 P6 100
S2 P1 300
S2 P2 400
S3 P2 200
S4 P2 200
S4 P4 300
S4 P5 400
Exercise 6.1
Write the SQL code to ...

1. Display the names of the suppliers who supply product number P1.

2. Display the name and weight of parts which are supplied by supplier S3.

3. Display the quantity of part "Blue Screw" supplied by supplier S1.

4. Display the quantity of part Green Bolt supplied by supplier Smith.

5. Display s# and sname of suppliers who supply Red Nut.

6. Display p# and names of parts which are supplied by Blake.

7. Display names of all parts which are supplied by suppliers whose status is higher than 25.

8. Display s#, p# pairs of which the supplier and the part are from the same city and the supplier has supplied that
part. (You need to use the SP table).

30
Exercise 6.2
Departments
DCODE DNAME FID
FIN Finance 035
MKT Marketing 029
MGT Management 047
IS Information Systems 087

Faculty
FID FNAME DCODE
023 Lee IS
029 Smith MKT
035 Sun FIN
044 Godfrey MGT
047 Johnson MGT
067 King MGT
087 Stroll IS

Courses
DCODE CNUM TITLE FID
IS 380 Database 047
IS 480 Advanced Database 087
IS 485 Systems Analysis 023
MGT 380 Human Resource 067
FIN 380 Financial Analysis 035
MGT 480 Management Concepts 044

Write SQL to display...

1. Department code and its chairpersons name.


2. Department name and its chairpersons name.
3. Department name and all its facultys name.
4. Name of IS departments chairperson.
5. Name of faculty who belongs to the IS department.
6. Title of courses offered by the IS department.
7. Title of course taught by the IS faculty.
8. Title of course taught by the chairperson of the IS department.
9. Name of faculty who teaches IS 380 class.
10. Title of all 400 level courses.
11. Title of IS 400 level courses.
12. Name of faculty who teach IS 400 level courses.
13. Name of department that offers 400 level courses.
15. Title of course taught by IS faculty.
16. Title of course taught by the chairperson of the IS department.
17. Name of chairperson who teaches at least one course.
19. Name of faculty who teaches outside of his/her department.
20. Title of course that is taught by faculty who is outside of that department.

14. Name of department that does not offer any 400 level course.
18. Name of chairperson who does not teach any course.

31
Topic 7. Data Integrity Commands
Primary Key Commands
Declare when creating the table:
-- f1 is the primary key of the t1 table
create table t1 (
f1 char(2),
f2 char(2),
primary key (f1) );
or
create table t1 (
f1 char(2) primary key,
f2 char(2), );
Note: This only works when the primary consists of 1 field; it doesnt work for composite primary key.

-- f1+f2 is the primary key of the t2 table


create table t2 (
f1 char(2),
f2 char(2),
f3 char(2),...,
primary key (f1, f2));

Alter constraints of an existing table:


ADD new constraints:
alter table t2 add primary key (f1,f2);

DROP constraints:
alter table t2 drop primary key (f1,f2);

Foreign Key Commands


Declare when creating the table:
-- table PARENT has a primary key f1 (already created)
-- table CHILD has a foreign key f1 that references PARENTs f1
-- creating a foreign key by the name of fk1 (you can certainly find a better name!)

create table CHILD (


f1 char(2),
f2 char(2),
constraint fk1 foreign key (f1) references PARENT(f1),
....);

-- table PARENT has a primary key f1+f2 (already created)


-- table CHILD has a foreign key f1+f2 that references PARENTs f1+f2
-- creating a foreign key by the name of fk_2.

create table CHILD (


f1 char(2),
f2 char(2),...,
constraint fk2 foreign key (f1,f2) references PARENT(f1,f2),
... );

Alter constraints of an existing table:


1. ADD new constraints:
alter table child add constraint fk1
foreign key (f1,f2) references parent(f1,f2));

32
2. DROP constraints:
alter table child drop constraint fk1;

Important Notes regarding fk declaration:


1. Two conditions must exist for the above commands to work.
(1) The parent table must already exist, and
(2) The parent column(s) being references by the child must be declared as the primary key of parent.
2. After the fk are set up, if you want to drop tables, you must drop child first, then the parent.
3. If you want to insert/update/delete records to either the child or the parent tables, the foreign key rules are
enforced.
4. In your entire database, each constraint has a unique name, just like each table has a unique name.

To find out the constraint names (Details refer to your Oracle book)
select constraint_name from user_constraints
where table_name='T1' and constraint_type='P';

Constraint_type=
'P': Primary key
'R': Foreign key
'U': Unique
'C': Not null

Exercise 7.1
Write SQL to create the above table structure with appropriate primary key and foreign key declaration.
COURSES INSTRUCTORS
DEPT CODE TITLE CREDITS SSN NAME
IS 380 Database 3 111-11 Andy
IS 385 System Analysis 3 222-22 Betty
IS 480 Advanced Database 3
IS 485 IS Project 3

SchClasses
CALLNUM DEPT CODE SEC# I_SSN
11110 IS 380 1 111-11
11115 IS 380 2 111-11
11120 IS 380 3 222-22
11125 IS 485 1 222-22
11130 IS 485 2 111-11

Write SQL to create the above table structure with appropriate primary key and foreign key declaration.
create table courses
(dept char(4),
code char(3),
title char(10),
credits number(1),
primary key (dept,code));

create table instructors


(ssn char(9),
name char(10),
primary key (ssn) );

create table SchClasses


(Callnum number,
dept char(4),
code char(3),
sec# char(2),
i_ssn char(9),
primary key (Callnum),
constraint fk_SchClasses_SSN foreign key (i_ssn) references instructors(ssn),
constraint fk_SchClasses_DeptCode foreign key (dept,code) references courses(dept,code));

Exercise 7.2
33
Refer to the tables of Exercise 6.1.
1. Identify the primary key and foreign key for each of the table.
2. Write the SQL code to create the three tables in sequence, with proper primary key and foreign key rules
declared.
3. Drop the 3 tables in sequence.

Exercise 7.3
Refer to the tables of Exercise 6.2.
1. Identify the primary key and foreign key for each of the table.
2. Write the SQL code to create the three tables in sequence, with proper primary key and foreign key rules
declared.
3. Drop the 3 tables in sequence.

Exercise 7.4
Refer to the tables of Exercise 2.3.
1. Identify the primary key and foreign key for each of the table.
2. Write the SQL code to create the three tables in sequence, with proper primary key and foreign key rules
declared.
3. Drop the 3 tables in sequence.

Homework 4 - SQL: Join, Integrity Rules


1. Create a file create.sql where you create the following tables and insert all test records. Make sure you have set
echo on in the beginning of the file. Spool your output to create.txt. Run create.sql until there is no error. Turn in a
print out of the create.txt file.

Students Enrollments Courses


SNum Sname Major GPA SNum CNum Grade CNum Ctitle Instr
101 Andy IS 3.2 101 IS380 B IS380 Database Lee
102 Betty FIN 1.8 101 IS385 A IS385 Systems Smith
103 Cindy IS 3.8 102 IS380 A IS355 Telecomm Lee
103 IS355 B

Field definitions:
SNum varchar2(3)
SName varchar2(25)
Major varchar2(20)
GPA Number(3,2)
CNum varchar2(8)
Grade varchar2(1)
CTitle varchar(25)
Instr varchar2(25)

Note:
a) The tables must have appropriate primary key and foreign key declaration.
b) Since It is likely that you will run create.sql many times and you will run into the following problem. The first
time you run it, Oracle creates the S, C, and G tables. The second time you run it, Oracle will not let you create the
tables again since the tables are already in place. It is a common practice to drop the tables at first before you create
them, like this:

drop table enrollments;


drop table courses;
drop table students;
create table students ;
create table Courses ;
create table Enrollments ;

2. Create a file query.sql where you write SQL code of questions _____________________. Please label the
question number clearly with comments. Make sure you have set echo on in the beginning of the file and spool to
query.txt. Run query.sql file until there is no error. Turn in a print out of the query.txt file.

34
1. Display CNum, title and Grade of courses Andy took.
2. Display SNum and SName of students who took IS380.
3. Display SNum and SName of students who took IS380 and received an 'A'.
4. Display SNum and SName of students who are IS major and took IS380.
5. Display Snum and Sname of IS student who received an A in IS380.
6. Display SNum and SName of students who took IS380 but not an IS major.
7. Display SNum of students who took the Telecomm course.
8. Display SNum of students who received an A from any of Lees class.
9. Display SNum and SName of students whose GPA is less than 2 but received an A in Lees class.
10. Display SNum and SName of students who have Lee as an instructor.

35
Topic 8. Normalization
Functional Dependency (FD)
- Attribute B is functionally dependent on attribute A if each value (cell) in attribute A determines one and
only one value in attribute B.
Determinant and Dependent

A B
example:
SSN Last Name
(Determinant) (Dependent)

reads:
A functionally determines B
(or) B is functionally dependent on A

Prime attribute (=prime key attribute) and nonprime attribute (=non prime key attribute)

Dependency diagram

Partial dependency: when there exists any determinant that is part of the key (instead of "the whole key").
Transitive dependency: when one nonprime attribute is dependent on another nonprime attribute.

PNUM PNAME ENUM ENAME JOBCLASS HourlyRate Hours


1 Hurricane 101 John News Elect.Eng. 65 13
102 David Senior Comm.Eng. 60 16
104 Anne Ramoras Comm.Eng. 60 19

2 Coast 101 John News Elect.Eng 65 15


103 Hune Arbough Biol.Eng. 55 17

3 Satellite 104 Anne Ramoras Comm.Eng. 60 18


102 David Senior Comm.Eng. 60 14

First Normal Form (1NF)


Arrange your data into table format and fill in appropriate data value for each cell.
Eliminate repeating groups and identify the primary key
1NF if
(1) Primary key attributes are defined,
(2) No repeating groups (each column/row contains only one data), and
(3) All attributes are dependent on the primary key.

PNUM PNAME ENUM ENAME JOBCLASS HourlyRate Hours


1 Hurricane 101 John News Elect.Eng. 65 13
1 Hurricane 102 David Senior Comm.Eng. 60 16
1 Hurricane 104 Anne Ramoras Comm.Eng. 60 19
2 Coast 101 John News Elect.Eng 65 15
2 Coast 103 Hune Arbough Biol.Eng. 55 17
3 Satellite 104 Anne Ramoras Comm.Tech. 60 18
3 Satellite 102 David Senior Comm.Tech. 60 14

36
PNum PName ENum EName JobClass HourlyRate Hours

PNum+ENum PName, EName, JobClass, HourlyRate, Hours


PNum PName
ENum EName, JobClass, HourlyRate
JobClass HourlyRate

Second Normal Form (2NF)


Eliminate partial dependencies
2NF if
(1) It is in 1NF, and
(2) It contains no partial dependencies

PNUM PNAME

ENUM ENAME JobClass HourlyRate

PNUM ENUM HOURS

Third Normal Form (3NF)


Eliminate transitive dependency
3NF if
(1) It is in 2NF, and
(2) It contains no transitive dependencies

PNUM PNAME

ENUM ENAME JobClass

JobClass HourlyRate

PNUM ENUM HOURS

37
The Boyce-Codd Normal Form (BCNF)

BCNF is violated when a prime attribute depends on a nonprime attribute.


Compare this concept with partial dependency...
BCNF if
(1) When every determinant in that table is a candidate key.

Homework 5. Normalization
Due on

Question 1.
A table contains columns A, B, C, D, E, F, G.
A+B is the primary key.
The following dependencies are identified:
C B
A D, E
EG
1) Normalize this table to 2NF; underline the primary key of each table.
2) Then normalize to 3NF; underline the primary key of each table.
3) Then normalize to BCNF; ; underline the primary key of each table.

Question 2.
Neighborhood Hardware is a hardware store. It orders inventory from various distributors. Neighborhood Hardware
gives each distributor a DistID.
Distributors may carry the same product. Each product has a universal UPC Number and product name. However,
each distributor has their own in-house distributor product ID (dist_prod_id) for products they carry. For instance,
Stanley Hammer-Pro has a universal UPC code 9785600021. Acer Inc. would refer to it by its product ID 576-183,
HardwareKing would identify it as 4178 BBR.

Each purchase order has a purchase order date, and it is issued to one distributor. Neighborhood Hardware can
purchase multiple products on a purchase order, each product has a purchase quantity.

1) Identify a candidate key.


2) Identify all FDs in the format of A B, C.

PurOrd PurOrd DistID DistName DistProdID UPCNumber ProdName Qty


Num Date
25278 03/12/12 101 Acer Inc. 576-101 9785600001 Screwdriver 3
576-112 9785600016 Handsaw 1
576-109 9785600007 Bolt cutter 4
576-183 9785600021 Stanley Hammer-Pro 2
25279 03/12/12 102 DOIT Distribution 0-345111 9785600023 Chain saw, 16 in. 1
0-345115 9785600007 Bolt cutter 12
4-896101 9785600015 2.75 in. bolt, 12 8
3-896102 9785600016 Handsaw 2
25281 03/13/12 103 HardwareKing 4152 BGR 9785600001 Screwdriver 3
4177 BXR 9785600023 Chain saw, 16 in. 3
4178 BBR 9785600021 Stanley Hammer-Pro 1
25282 03/13/12 102 DOIT Distribution 0-345115 9785600007 Bolt cutter 4
25283 03/14/12 102 DOIT Distribution 0-345115 9785600007 Bolt cutter 3
0-345111 9785600023 Chain saw, 16 in. 5
4-896101 9785600015 2.75 in. bolt, 12 8
25284 03/14/12 103 HardwareKing 4178 BBR 9785600021 Stanley Hammer-Pro 3
4177 BXR 9785600023 Chainsaw, 16 in. 5

38
Exercise 8.1
John took the following courses in Spring of 2012, they are IS 380 Database, which he received an A; IS
355 Network, which he received a B; and MKT 380 Introduction to Marketing, which he received an A. John's social
security number is 123123123. In Fall 2012, John took only one course: IS 485 IS Project. No grade is assigned for
this course yet. Mary, whose social security number is 321321321, took 2 courses in Spring of 2012: IS 380 and IS
355. She got A in both classes. Mary is taking IS 485 and MKT 380in Fall 2012 , where no grade has been assigned
to either course.
- Transform the above knowledge/data/information into one 1NF table.
- What is the primary key of this table?
- Identify all functional dependencies.

Exercise 8.2
Transform the following hospital receipts into one 1NF table.
Identify all FDs.
Identify the primary key.
Consider 2 cases: One is when the patient is always assigned to the same doctor; the other case is the patient can be
randomly assigned to any doctor available. How would this change the Functional Dependencies?

HIGHLAND HOSPITAL -- We are here to serve YOU!

Visit Date: 1-22-2013


Admission Time: 10:58 Am

Patient ID: 86334 Doctor ID: 99887


Patient Last Name: Smith Doctor Name: Mike Myers
Patient First Name: John Admitted by: 079

TrID Description UnitCost Quantity Subtotal


X185 Aspirin $5 10 $50
B982 X-Ray $72 1 $72
V092 Hospital Stay $50 2 $100

Exercise 8.3
A table contains attributes A, B, C, D, E, F. A+B is the primary key. The following dependencies are identified.
A+B C, D, E, F
BC
D F

1. Draw a dependency diagram


2. Normalize the table to 2NF.
3. Normalize the table to 3NF.

Exercise 8.4
A table contains attributes A, B, C, D, E, F. A+B is the primary key. The following dependencies are identified.
A+B C, D, E, F
BC
C F

1. Draw a dependency diagram


2. Normalize the table to 2NF.
3. Normalize the table to 3NF.

Exercise 8.5

39
ENROLLMENTS
SNum SName CNum CTitle Grade Advisor AOffice
101 Andy ECO241 Macroeconomics A Lee CBA 428
IS 310 Statistics I B
IS 380 Database Management A
IS 385 Systems Analysis A
102 Betty IS 380 Database Management B Thompson CBA 422
IS 300 Introduction to MIS B
ECO241 Macroeconomics A

Assumptions:
Each student has only one advisor.
Several advisors can share the same office, but no advisor has two offices.
CNum is unique. SNum is unique. CTITLE is not unique. Advisor's name is unique.
To simplify the matter, assume SNum+CNum is unique (ie, the student cannot take the same course again).

1. Normalize the table to 1NF. Identify all Functional Dependencies and the primary key.
2. Normalize the table to 2NF.
3. Normalize the table to 3NF.

Exercise 8.6
Normalize the following table to 1NF, 2NF, and 3NF.

COURSE# TITLE PREREQUISITE_C#


IS600 Mathematical Analysis
IS630 Statistical Analysis IS600
IS635 Operations Management IS630
IS640 Computer and Information Systems
IS645 Systems Analysis and Design IS630
IS635
IS640
IS646 Database Management IS630
IS635
IS640

Exercise 8.7
Normalize the following table to 3NF.
Assumptions:
Each student has only one major.
Each department can offer several majors, but each major belongs to one department.
Each department belongs to one college; each college can have several departments.
Each student has only one standing, i.e., Junior, Senior, etc.

STUDENTS
SNum SName Major Dept DeptName DeptPhone College Standing
211343 Stephanos Accounting ACCT Accounting 4356 Business Adm Junior
211344 Johnson Marketing MKT Marketing 4778 Business Adm Senior
211345 Smith Intl Bus. MKT Marketing 4778 Business Adm Junior
211346 Urman Biology BIO Biology 9823 Science Junior
211347 Morrison Bio. Tech BIO Biology 9823 Science Senior
....

Exercise 8.8
Normalize the following table to 3NF.
Assumptions:
- Each item has a unique ID number.
- There are many rooms in one building.
- Each building has one manager. S/he has one phone.

40
ITEMS
ITEM_ID ITEM_NAME ROOM BLDG_CODE BLDG_NAME BLDG_MANAGER PHONE
2311345-789 HP Laserjet Printer 428 CBA College of Business Adm John Smith 5-1987
2394857X87 ViewSonic 19 Monitor 428 CBA College of Business Adm John Smith 5-1987
928375-IU2 HP Laserjet Printer 417 CBA College of Business Adm John Smith 5-1987
2293847X12 ViewSonic 19 Monitor 190 SCI Science Building Lynn Johnson 5-7784
189-XQW CD Room Reader 428 SCI Science Building Lynn Johnson 5-7784

41
Topic 9. Entity-Relationship Diagram (ERD)
Entity
Entity Represented by _________________ Example: __________________

Entity instance Example: __________________

Attribute represented by ________________


- The primary key attribute(s) are underlined

Single-value attribute Multi-value attribute Derived attribute

Multi-value attribute
1:M relationship between columns
Solution:
1) create more columns, so the entire thing is 1:1
2) create another table to handle the 1:M relationship

Relationship
Represented by:

Connectivity
1:1 1:M M:N

Composite Entity
Represented by ________________

Exercise 9.1
Each student may take multiple courses. Each course has an instructor.
Three entities are identified: STUDENTS, COURSES, INSTRUCTORS.
Please draw an ERD for this case.

Exercise 9.2
42
Please draw an E-R Diagram to reflect the following business rules.
An invoice is written by a sales representative. Each sales representative can write many invoices, but each invoice
is written by a single sales representative.
The invoice is written for one customer. However, each customer can have many invoices.
An invoice can include multiple product items, each with a sales quantity.
The product information is stored in a product entity.
These entities are identified: INVOICES, SALESREPS, CUTOMERS, PRODUCTS.

Exercise 9.3
Please draw an ER Diagram to reflect the following business rules, and also draw hypothetical tables from the ERD.
1) Each invoice is paid by one check, each check pays for only one invoice.
2) Each invoice can be paid by multiple checks, each check can only pay for one invoice.
3) Each invoice can be paid by multiple checks, and each check can pay for multiple invoices.

Degree of Relationship
Unary relationship = recursive Binary relationship Ternary relationship
relationship

Combining Degree and Connectivity

Unary Binary Ternary

1:1

1:M

M:N

Cardinality: Range of occurrences associated with each occurrence of the related entity.

Relationship Participation: the necessity of entity existence.


Mandatory vs. Optional

43
Strong vs. Weak entity (weak entity is represented by )

Existence dependency

Homework 6. ER Diagram Due

Exercise 9.4
Name an example of the following relationships, and explain how the example fits the relationship from both
directions.

Unary, 1:1
Unary, 1:M
Unary M:M
Binary 1:1
Binary 1:M
Binary M:N

Exercise 9.5
Please draw an E-R Diagram to reflect the following business rules, and also draw hypothetical tables from the ERD.
1) Each person has one biological father. Each person can be father of multiple children.
2) Each person has one biological father and one biological mother. Each person can be father of multiple children;
each person can be mother of multiple children.

Exercise 9.6
Draw an E-R Diagram to reflect the following business rules. Notice: What are the things that cannot be represented
in ER Diagram?

1. Tiny College (TC) is divided into several schools: a school of business, a school of art and science, a school
of education, and a school of applied science.
2. Each school is administered by a dean.
3. Each school is composed of several departments. For example, the school of business has an accounting
department, a management/marketing department, and an economic/finance department.
4. Each department offers several courses.
5. Each course has several sections. Each section is taught by one professor.
6. Not all courses are offered each semester.
7. A course may have prerequisites courses.
8. Each department employs several professors, and each professor is assigned to a single department.
9. Each department is chaired by a department chair, who is a professor.
10. Each professor may teach up to four sections. A professor may teach no class at all.
11. Each student can enroll in several courses, but a student is enrolled in only one section of a course.
12. Each department has several students whose major is offered by that department. However, each student
only has a single major.
13. Each student has an advisor in his or her department. Each advisor advises several students. An advisor is
also a professor, but not all professors advise students.

Exercise 9.7

44
Please draw an ERD for each of the following case, and design hypothetical tables accordingly. Two entities are
identified: STUDENTS and MAJORS.
1) Each student can have a single major.
2) Each student can have a major and a minor.
3) Each student can have multiple majors and multiple minors.

Exercise 9.8
Please draw an E-R diagram to reflect the following relationships.
The company has a number of inventory, which are supplied by a number of suppliers.
Each time the company orders inventory from the supplier, there is an order form.
It is possible to order multiple products on the same order form.

Exercise 9.9
In addition to the above three relationships, please consider the following scenarios and draw an ER diagram for
each one of them.
5a. The company can order any inventory from any supplier.
5b. Every inventory has only one supplier that the company orders from.
5c. Every inventory has several designated suppliers that the company may order from. Orders placed to other
suppliers are prohibited.

Exercise 9.10
Please draw an ERD to reflect the following relationships.
What is the primary key of the TRANSACTION table?
Each customer can have many ATM cards; each card has a unique card number.
There is one password on each card.
A customer can have multiple accounts (ie, checking, saving, etc.)
A customer can use the card to make transactions, such as deposit and withdraws from his/her accounts.
Each transaction is associated with one "action"; that is, check balance and withdraw money are considered 2
different transactions.

The following entities are identified:


CUSTOMERS
ATM_CARDS
ACCOUNTS
TRANSACTIONS
ATM_MACHINES

The following attributes are identified:

cid: customer ID balance: The current balance of a particular account.


cname: customer name atmid: ATM machine ID
cphone: customer phone atmloc: ATM machine location
atmnum: ATM card number tdate: Transaction date
password: Password of a particular card ttime: Transaction time
issuedate: The issue date of an ATM card ttype: Transaction type, such as "D" for deposit, "W" for
accsuffix: The suffix of an account, such as withdraw.
"01" for checking, "02" for savings, etc. tamount: Transaction amount

Exercise 9.11
Draw an ERD for the following two scenarios.

11a. Draw an ERD that captures all human beings (including humanID and name) and their "current, legal" spouse
(where there should be only one.)
11b. Draw an ERD that captures all human beings and their current and ex marital spouses.

Exercise 9.12
45
Each employee can work on many projects. Each project can have many employees. Each employee can have
multiple skills. Each employee can only use one skill on one project. Each employee has an official title, such as
Associate; however, for each project, an employee can be assigned a title different from his/her official title, such as
Acting Senior Associate. Each project has one manager, who is also an employee.

Each project is held in one city. There can be multiple projects in one city. Each employee can only work in one city.

the following attributes are identified (but not limited to..)

ENum: employee number


EName: employee name
Etitle: employee job title
PNum: project number
PName: project name
SkillCode: skill code
SkillDesc: skill description

Exercise 9.13
For the following scenario, draw an ER Diagram. Identify attributes of each entity.
For each entity, draw a table with a few test records. Identify how the tables are linked.

The company sells products to customers. A sales order is created for each sales transaction. There can be multiple
products sold in a sales order. A sales order may take several shipments to complete. An invoice is created for each
sales order. The customer pays for the invoices by issuing payment checks. The customer may write one check to pay
for multiple invoices; however, an invoice can also be paid by multiple checks.

Exercise 9.14
How would you modify your table structure given the following new requirements?

You may purchase multiple items (products) from Amazon.com in one order (SalesOrder). Each order may take
several shipments to complete. Recently, Amazon started the bundle shipment where you can request to combine
multiple orders in one shipment.

46
Topic 10. SQL*Plus Input/Output Commands
Note: prompt and accept are SQL*Plus commands. They will not work with other software like SQL developer or
SQL navigator.
==

prompt prompt
ex. prompt
prompt Processing.... please wait....
prompt ----------- Please Detach Along This Line ----------------

accept variable prompt 'prompt';


ex. accept vAmount prompt 'Please enter the amount: ';
accept vCustNum prompt 'Please enter the Customers Number: ;

'&variable'
&variable

select 'text', f1, f2, ... from t where [conditions];


select text from t where [conditions];
ex. select 'Customer Name: ', CustName
from Customers
where CustNum='&vCustNum';
ex. select The Order Has Been Processed!
from transaction
where tran# is not null;

File Structure
SQL> select * from STUDENTS;

SNU SNAME STATUS


--- ---------- ----------
001 John Senior
002 Mary Junior
003 Joe Senior
004 Jim Sophomore

Run Time Behavior

SQL> start MyProg3.sql

*--- Welcome to the Student Information Program ---*

Please Enter the Student ID: 001


The Student Name is: John
The Student is a Senior
SQL>

47
Oracle Code
set feedback off
set echo off
set verify off
set heading off

prompt
prompt *--- Welcome to the Student Information Program ---*
prompt
prompt
accept vSNum prompt 'Please Enter the Student ID: ';
select 'The Student Name is: ', sname
from Students
where SNum='&vSNum';
select 'The Student is a ', status
from Students
where SNum='&vSNum';

Exercise 10.1 Lookup Student Name


These tables/data are already in place:

Students Enrollments
Snum Sname Major Status Snum Cnum Semester Grade
101 Andy IS Junior 104 IS300 Fa06 B
102 Betty Freshman 101 IS300 Fa06 A
103 Cindy FIN Senior 102 IS301 Fa06 D
104 David IS Junior 101 IS310 Fa06 A
103 IS310 Sp07
102 IS301 Sp07
104 IS310 Sp07

Write a SQL program ex10_1.sql to do the following:

1. System prompts
Welcome to the Registration System

2. System prompts
Please enter the Student's ID:
and read the student ID (variable name is vSNum)

3. System displays the student's name according to the vSNum entered by the user.

4. System skips 2 empty lines

Exercise 10.2 Lookup grade


Write a program ex10_2.sql for a user to lookup grade of a particular course.

1. System prompts:
Please enter the Student's ID:
and read the student ID (variable name is vSNum)

2. System prompts:
Please enter the course number:

48
and read the input (variable name is vCnum)

3. System displays the semester and grade that matches the student and the course.

Exercise 10.3 Look up enrollments of a given semester


Write a program ex10_3.sql for a user to lookup his enrollment records for a given semester.

1. System prompts:
Please enter the Student's ID:
and read the student ID (variable name is vSNum)

2. System prompts:
Please enter the semester code(like Sp07):
and read the input (variable name is vSemester)

3. System displays the enrollment records for that student during that semester.

Exercise 10.4 Update major


Write a program ex10_4.sql for a user to change his major.
1. System prompts:
Please enter the Student's ID:
and read the student ID (variable name is vSNum)

2. System prompts:
Please enter the new major code:
and read the new major code (variable name is vMajor)

3. System updates the new major for the student.

Exercise 10.5 Insert a new student


Write a program ex10_5.sql to insert a new students data to the database

1. System prompts
New Student ID:
and read the student ID (variable name is vNewStuNum)

2. System prompts
New Student Name:
and read the student's name (variable name is vNewStuName)

49
3. System inserts new ID and new name into the STUDENTS table

4. The system prompts


The following record has been inserted:
and displays the new student's ID and name.

Exercise 10.6 Insert a new enrollment record


Write a program enroll.sql to enroll a student to a course.

1. System prompts
Please enter the Student ID:
and read the student ID (variable name is vSnum)

2. System prompts
Please enter the course number of the course you wish to add:
and read the course number (variable name is vCnum)

3. Insert the new enrollment record to the database.

50
Topic 11. More SQL Commands

11.1 The COLUMN command


Note: Column is a SQL*Plus command.
SQL> select * from trans;

PID PNAME PRICE QUANTITY


---- -------------------- --------- ---------
0001 Monitor 299.99 3
0002 Keyboard 49.99 2
0003 Mouse Pad 1.99 100

SQL> column pname heading 'Product|Description' format a20


SQL> column price heading 'Unit|Price' format $9,999.99
SQL> column quantity heading 'Quantity' format 999

SQL> select * from trans;

Product Unit
PID Description Price Quantity
---- -------------------- ---------- --------
0001 Monitor $299.99 3
0002 Keyboard $49.99 2
0003 Mouse Pad $1.99 100

11.2 Use alias


... use alias for field names
SQL> select pname, price, quantity,
price*quantity, price*quantity*0.0825
from trans;

PNAME PRICE QUANTITY PRICE*QUANTITY PRICE*QUANTITY*0.0825


-------------------- --------- --------- -------------- ---------------------
Monitor 299.99 3 899.97 74.247525
Keyboard 49.99 2 99.98 8.24835
Mouse Pad 1.99 100 199 16.4175

SQL> column pname heading 'Product|Description' format a20


SQL> column price heading 'Unit|Price' format $9,999.99
SQL> column quantity heading 'Quantity' format 999
SQL> column total heading 'Total' format $999,999.99
SQL> column tax heading 'Tax' format $999.99

SQL> select pname, price, quantity,


price*quantity total,
price*quantity*0.0825 tax
from trans;

Product Unit
Description Price Quantity Total Tax
-------------------- ---------- -------- ------------ --------
Monitor $299.99 3 $899.97 $74.25
Keyboard $49.99 2 $99.98 $8.25
Mouse Pad $1.99 100 $199.00 $16.42

SQL> clear column


columns cleared

51
... use alias for table names
SQL> select student.snum, enrollment.snum, student.sname
From student, enrollment
Where student.snum=enrollment.snum;

SQL> select s.snum, e.snum, s.sname


From student s, enrollment e
Where s.snum=e.snum;

11.3 Create a sequence


A sequence is a counter.

You can create a sequence by the following command:

create sequence MySequence1 start with 10000;

select MySequence1.CurrVal from dual;

select MySequence1.NextVal from dual;

Insert into Transaction values (MySequence1.NextVal, ......);

11.4 Views
A definition of a restricted portion of a table.
create view v1 as
select f1, f2,...
from t1
where [conditions];

ex: create view view_IS_students as


select ssn, lastname, firstname, major
from students
where major=IS;

SQL> desc students;


Name Null? Type
----------------------------------------- -------- -------------------
SNUM CHAR(3)
SNAME CHAR(10)
DISABILITY_FLAG CHAR(1)

SQL> select * from students;

SNU SNAME DISABILITY_FLAG


--- ---------- ---------------
101 Andy N
102 Betty Y
103 Cindy N

SQL> desc students2;


ERROR:
ORA-04043: object students2 does not exist

SQL> create view view_students as select snum, sname from students;

View created.

SQL> select * from view_students;

SNU SNAME
--- ----------
101 Andy
102 Betty
103 Cindy

SQL> select * from view_students where disability_flag='Y';


select * from view_students where disability_flag='Y'
52
*
ERROR at line 1:
ORA-00904: "DISABILITY_FLAG": invalid identifier

SQL> desc view_students;


Name Null? Type
----------------------------------------- -------- -------------------
SNUM CHAR(3)
SNAME CHAR(10)

11.5 Union, Intersect, Minus


(select t1f1, t1f2 from t1)
union
(select t2f1, t2f2 from t2);

(select t1f1, t1f2 from t1)


intersect
(select t2f1, t2f2 from t2);

(select t1f1, t1f2 from t1)


minus
(select t2f1, t2f2 from t2);

Union compatible:
- The selects must have the same number of columns
- The matching columns must be the same data type (they dont need to be the same length)
- The matching columns may have different column names

SQL> create table bus (


2 snum varchar2(9),
3 sname varchar2(10),
4 status varchar2(10),
5 gpa number (3,2));

SQL> insert into bus values ('101','Andy','Junior',3.5);

SQL> insert into bus values ('102','Betty','Junior',2.8);

...

SQL> select * From bus;

SNUM SNAME STATUS GPA


--------- ---------- ---------- ----------
101 Andy Junior 3.5
102 Betty Junior 2.8
103 Cindy Senior 3.3
104 David Junior 2.4

4 rows selected.

SQL> create table eng (


2 sid varchar2(3),
3 sname varchar2(10),
4 status varchar2(10));

SQL> insert into eng values ('105','Ellen','Junior');

...

SQL> select * from eng;

SID SNAME STATUS


--- ---------- ----------
105 Ellen Junior
106 Frank Junior
107 George Senior
108 Helen Junior
103 Cindy Senior
104 David Junior

53
6 rows selected.

SQL> -- not union compatible


SQL> select * from bus
2 union
3 select * from eng;
select * from bus
*
ERROR at line 1:
ORA-01789: query block has incorrect number of result columns

SQL> -- Union compatible


SQL> Select snum, sname from bus
2 union
3 select sid, sname from eng;

SNUM SNAME
--------- ----------
101 Andy
102 Betty
103 Cindy
104 David
105 Ellen
106 Frank
107 George
108 Helen

8 rows selected.

SQL> Select snum, sname from bus


2 intersect
3 select sid, sname from eng;

SNUM SNAME
--------- ----------
103 Cindy
104 David

SQL> Select snum, sname from bus


2 minus
3 select sid, sname from eng;

SNUM SNAME
--------- ----------
101 Andy
102 Betty

SQL> Select sid, sname from eng


2 minus
3 select snum, sname from bus;

SID SNAME
--------- ----------
105 Ellen
106 Frank
107 George
108 Helen

Exercise 11.1
Students Enrollments Courses
SNum Sname Major GPA SNum CNum Grade CNum Ctitle Instr
101 Andy IS 3.2 101 IS300 A IS300 Intro MIS Lee
102 Betty FIN 1.8 101 IS380 B IS340 Python Smith
103 Cindy IS 3.8 101 IS385 B IS380 Database Lee
104 David IS 3.3 102 IS380 A IS385 Systems Jones
105 Ellen ACC 2.2 103 IS385 A IS355 Telecomm Lee

1) Write an SQL statement to display SNUM of students who have not enrolled in any class.
2) Write an SQL statement to CNUM that has no student enrolled.
3) Write an SQL statement to display SNUM of students who took both IS 380 and IS 385.

54
4) Write an SQL statement to display SNUM of students who took IS 380 but never took IS 300.
5) Write an SQL statement to display SNUM of students who never had Lee as an instructor.

11.6 Create table with Select statement


create table newtable as
select * from oldtable;

create table newtable as


select column1, column2, ...
from oldtable
where.....;

SQL> create table students2 as


select * from students;

SQL> create table students2 as


select ssn, sname, gpa from students;

SQL> create table students2 as


Select ssn, sname, gpa
From students
Where major=IS;

11.7 Insert with Select statement


insert into to_table
select * from from_table;

insert into to_table (column1, column2, ...)


select column1, column2, ... from from_table;

SQL> Insert into StudentBackup


select * from students;

SQL> Insert into StudentBackup (ssn, sname, gpa)


select ssn, sname, gpa from students;

SQL> Insert into1 studentsBackup (ssn, sname, gpa)


Select ssn, sname, gpa
From students
Where status=Graduated;

55
Topic 12. Program a Counter
File Structure
SQL> describe products;
Name Null? Type
------------------------------- -------- ----
PID CHAR(5)
DESCRIPTION CHAR(25)
PRICE NUMBER(10,2)

SQL> select * from products;

PID DESCRIPTION PRICE


----- ------------------------- ---------
101 Paper 69.99
102 Pen 13.99
103 Pencil 25.99
104 Printer 1099.99

SQL> describe trans;


Name Null? Type
------------------------------- -------- ----
TNUM NUMBER
TDATE DATE
PID CHAR(5)
QTY NUMBER(3)

SQL> select * from trans;

no rows selected

SQL> describe counter;


Name Null? Type
------------------------------- -------- ----
MAXNUM NUMBER(5)

SQL> select * from counter;

MAXNUM
---------
1000

Run Time Behavior


SQL> start a:Checkout.sql

*--------------------------------------------*
* Welcome to the Check out Program *
*--------------------------------------------*

Please Enter the Product ID: 104

Product Description: Printer

Price: 1099.99

Please Enter Quantity: 3

56
The Following Transaction has been confirmed ...

Trans Product Product Unit


Numbe ID Description Price Quantity Total
----- ---------- ------------------------------ ---------- -------- ------------
1000 104 Printer $1,099.99 3 $3,299.97

-- Lets examine what has been updated to the database ...


SQL> select * from trans;

Trans Product
Numbe TDATE ID Quantity
----- --------- ---------- --------
1000 17-FEB-15 104 3

SQL> select * from counter;

MAXNUM
---------
1001

-- Run the program again


SQL> start a:Checkout.sql

*--------------------------------------------*
* Welcome to the Check out Program *
*--------------------------------------------*

Please Enter the Product ID: 103

Product Description: Pencil

Price: $25.99

Please Enter Quantity: 8

The Following Transaction has been confirmed ...

Trans Product Product Unit


Numbe ID Description Price Quantity Total
----- ---------- ------------------------------ ---------- -------- ------------
1001 103 Pencil $25.99 8 $207.92

-- Again, the database has been updated ...


SQL> select * from trans;

Trans Product
Numbe TDATE ID Quantity
----- --------- ---------- --------
1000 17-FEB-15 104 3
1001 17-FEB-15 103 8

SQL> select * from counter;

MAXNUM
---------
1002
SQL>

57
Note: this program can also be done with sequence.

Oracle Code
/* Program 3.5.1 */

set heading off


set feedback off
set echo off
set verify off

prompt
prompt
prompt *--------------------------------------------*
prompt * Welcome to the Check out Program *
prompt *--------------------------------------------*
prompt
prompt

accept vPid prompt 'Please Enter the Product ID: ';

select 'Product Description: ', description from products


where pid='&vPid';
select 'Price: ', price from products
where pid='&vPid';

prompt
prompt

accept vQty prompt 'Please Enter Quantity: ';

insert into trans (tnum, tdate, pid, qty)


select maxnum, sysdate, '&vPid', &vQty from counter;

commit;

set heading on

column tnum heading 'Transaction|Number' format 99999


column pid heading 'Product|ID' format a10
column description heading 'Product!Description' format a30
column price heading 'Unit|Price' format $9,999.99
column qty heading 'Quantity' format 999
column total heading 'Total' format $999,999.99

prompt
prompt
prompt The Following Transaction has been confirmed ...

select tnum, p.pid, description, price, qty, price*qty total


from products p, trans t, counter c
where t.pid=p.pid
and t.tnum=maxnum;

update counter set maxnum=maxnum+1;

commit;

58
Topic 13. Text Manipulation
For a complete reference on this topic, refer to
Oracle Chapter 6. Getting Text Information and Changing It

Concatenation: string||string
ex: select lastname||', '||firstname from student;

lower(string)
upper(string)
initcap(string)
ex: lower('sOPhiE') returns
upper('sOPhiE') returns
initcap('sOPhiE') returns

ltrim(string)
rtrim(string)
ex: ltrim('John ') returns
rtrim('John ') returns
select rtrim(lastname)||', '||rtrim(firstname) from student;

lpad(string,length,'set')
rpad(string,length,'set')
ex. lpad('Sophie',10,'*') returns
rpad('Sophie',10,'*') returns

substr(string,start,count)
ex. substr('Sophie',2,2) returns
substr('Sophie',3,1) returns

Exercise 13.1
Use the above functions to convert a telephone number 6171234567 to (617)123-4567

Exercise 13.2

The STUDENT table consists of the following fields:

SSN char(9)
Lastname char(10)
Firstname char(10)
Middlename char(10)
Phone char(10)

Assume the following records are stored in the table:

SSN LASTNAME FIRSTNAME MIDDLE PHONE


111111111 Smith John Roger 6171111111
222222222 Jones Mary Mimi 6172222222
333333333 Johnson Howard Michael 5083334343

Write the SQL to display the student's full name and phone number in the format of

Smith, John R. ..................(617) 111-1111


Jones, Mary M. ..................(617) 222-2222
Johnson, Howard M. ..............(508) 333-4343

59
Exercise 13.3
You have the following STUDENT table:

SSN LASTNAME FIRSTNAME MIDDLE PHONE


----------- ---------- ---------- ---------- ----------
111111111 Smith John Roger 6171111111
222222222 Jones Mary Mimi 6172222222
333333333 Johnson Howard Michael 5083334343

Write a program to display student information based on a user-input SSN, like the following:

*-- Welcome to the Student Information Program --*

Please enter social security number: 111111111

Student Phone: (617)111-1111

Specifications:
1. skip 2 lines
2. Display the Welcome title
3. System prompts
Please enter social security number:
4. User inputs the SSN
5. System prompts " Student Phone: " and displays the students phone with appropriate format such as ( , ), and -.

60
Homework 7. Oracle Programming 1
Due

1. In Oracle, create a CUSTOMERS table with the following fields. (You may use varchar2 if you like )

SQL> describe customers;


Name Null? Type
------------------------------- -------- ----
SSN CHAR(9)
LASTNAME CHAR(30)
FIRSTNAME CHAR(30)
MIDDLE CHAR(30)
PHONE CHAR(10)

2. Write a program hw7.sql that will insert a new customer record into the table, like the following:

SQL> start a:hw7

*-------------------------------------------*
* -- New Customer Program -- *
*-------------------------------------------*
Please enter the customer's SOCIAL SECURITY NUMBER: 837465538
Please enter the customer's LAST NAME: koch
Please enter the customer's FIRST NAME: george
please enter the customer's MIDDLE NAME: will
Please enter the customers PHONE: 5629851111

*-- The following record has been updated:

Social Security Number: 837-46-5538

Name: Koch, George W.

Phone: (562)985-1111

Specifications:
1. The system skips 1 line and displays the New Customer Program title.
2. The system prompts for social security number, last name, first name, middle name, and phone of the new
customer. Notice that the user can enter in lower case.
3. The system inserts the new record into the CUSTOMERS table.
4. The system displays the new record (from the CUSTOMERS table) for confirmation. Note that the data should be
displayed with appropriate format.

Spool your output to hw7.txt. Run the program until there is no error. Test your program by entering at least 2
customers (so I can see your query pulls up the correct record). Print a copy of hw7.sql and hw7.txt. Turn in both
copies.

61
Topic 14. Date/Time Manipulation
For a complete reference on this topic, refer to
Oracle Chapter 8. Dates: Then, Now, and the Difference

SQL> -- display today's date


SQL> select sysdate from dual;

SYSDATE
---------
23-AUG-15

1 row selected.

SQL> -- use to_char to display various formats of date (see Oracle Complete Reference)
SQL> select to_char(sysdate,'Month dd, yyyy, hh:mi:ss AM, Day') today
2 from dual;

TODAY
------------------------------------------
August 23, 2015, 03:23:53 PM, Sunday

SQL> -- 1 is 1 day
SQL> select to_char(sysdate+1, 'Month dd, yyyy, hh:mi:ss AM, Day') tomorrow
2 from dual;

TOMORROW
------------------------------------------
August 24, 2015, 03:24:20 PM, Monday

SQL> select to_char(sysdate-1, 'Month dd, yyyy, hh:mi:ss AM, Day') yesterday
2 from dual;

YESTERDAY
------------------------------------------
August 22, 2007, 03:24:49 PM, Saturday

-- Difference between 2 dates can be fractions


SQL> select sysdate-checkout from books where booknum='999';

SYSDATE-CHECKOUT
----------------
1.4863079

-- trunc(date) set the date/time to midnight that day


SQL> select to_char(trunc(sysdate), 'Month dd, yyyy, hh:mi:ss AM, Day')
2 from dual;

TO_CHAR(TRUNC(SYSDATE),'MONTHDD,YYYY,HH:MI
------------------------------------------
August 23, 2015, 12:00:00 AM, Sunday

-- To get an integer number of days between 2 dates, use truncon both


SQL> select trunc(sysdate)-trunc(checkout) from books where booknum='999';

TRUNC(SYSDATE)-TRUNC(CHECKOUT)
------------------------------
1

SQL> -- to declare a column as "date" type


SQL> create table students (
sname varchar2(15),
DateofBirth date,
GPA number(3,2));

Table created.

SQL> -- to insert a date value


SQL> insert into students values ('Andy','02-Jan-85',3.72);

1 row created.

62
SQL> insert into students values ('Betty',to_date('06/17/1987','mm/dd/yyyy'), 2.98);

1 row created.

SQL> -- comparing dates (the later the bigger)


SQL> select * from students
where DateofBirth >= '01-jan-86';

SNAME DATEOFBIR GPA


------ --------- -----
Betty 17-JUN-87 2.98

-- How many days have you been born?


SQL> select SName, Sysdate - DateofBirth from students;

SNAME SYSDATE-DATEOFBIRTH
------ -------------------
Andy 8274.64551
Betty 7378.64551

63
Topic 15. Simple Report, Break, and Compute
Note: break and compute are SQL*Plus commands
For a complete reference on this topic, refer to
Oracle Chapter 5. Basic SQLPLUS Reports and Commands
Oracle Chapter 13. Building a Report in SQLPLUS

clear break
clear compute
clear column

SQL> select * from t39;

CNAME STATE ACCOUNT AMOUNT


-------------------- ----- ---------- ---------
ABC Corporation CA Regular 1430
ZZZ Inc. CA Premium 2500
TLC Industry AZ Premium 990
A-1 Unlimited AZ Premium 4500
4x4 Automobile CA Regular 10000

SQL>
SQL> -- learn to use "break on"
SQL> break on state skip 1
SQL> select state, cname, account, amount from t39;

ST CNAME ACCOUNT AMOUNT


-- -------------------- ---------- ---------
CA ABC Corporation Regular 1430
ZZZ Inc. Premium 2500

AZ TLC Industry Premium 990


A-1 Unlimited Premium 4500

CA 4x4 Automobile Regular 10000

SQL> -- "break on" must be used with "order by" to make sense
SQL> select state, cname, account, amount from t39 order by state;

ST CNAME ACCOUNT AMOUNT


-- -------------------- ---------- ---------
AZ TLC Industry Premium 990
A-1 Unlimited Premium 4500

CA ABC Corporation Regular 1430


4x4 Automobile Regular 10000
ZZZ Inc. Premium 2500

64
SQL> -- learn to use "compute"
SQL> break on account skip 2
SQL> compute count of cname on account
SQL> select account, cname, state, amount from t39
2 order by account;

ACCOUNT CNAME ST AMOUNT


---------- -------------------- -- ---------
Premium ZZZ Inc. CA 2500
TLC Industry AZ 990
A-1 Unlimited AZ 4500
********** --------------------
count 3

Regular ABC Corporation CA 1430


4x4 Automobile CA 10000
********** --------------------
count 2

SQL> clear compute


SQL> compute sum avg of amount on account
SQL> column amount format $99,999.99
SQL> select account, cname, state, amount from t39
2 order by account;

ACCOUNT CNAME ST AMOUNT


---------- -------------------- -- -----------
Premium ZZZ Inc. CA $2,500.00
TLC Industry AZ $990.00
A-1 Unlimited AZ $4,500.00
********** -----------
avg $2,663.33
sum $7,990.00

Regular ABC Corporation CA $1,430.00


4x4 Automobile CA $10,000.00
********** -----------
avg $5,715.00
sum $11,430.00

SQL> -- it's a good habit to clear break, compute, and column format when done
SQL> clear break
SQL> clear compute
SQL> clear column

SQL> clear break


breaks cleared
SQL> clear compute
computes cleared

65
Topic 16. Group Operation
For a complete reference on this topic, refer to
Oracle Chapter 10. Grouping Things Together

1. Group Functions
count(field)
count(*)
sum(field)
avg (field)
max(field)
min(field)
distinct(field)

The STUDENTS table:

SSN SNAME DOB Entrance Major Gender GPA Zip


Date
101 Andy 10/1/95 9/1/12 IS M 2.5 90840
102 Betty 3/24/88 9/1/12 IS F 3.7 90840
103 Cindy 11/5/86 2/1/10 Mkt F 2.2 90841
104 David 1/1/91 9/1/10 Fin M 3.8 90841
105 Ellen 3/4/91 2/1/11 IS F 3.5 90840
106 Frank 2/2/88 2/1/11 Mkt M 2.1 90842
... ... .... ... ... ... ...

Write SQL Code to reflect the following queries:

Exercise 16.1
1. How many students are there?

2. How many students major in IS?

3. How many students are male? How many students are female?

4. How many students are male and major in IS? How many students are female and major in IS?

5. What is the average GPA of IS students?

6. What is the highest GPA of all students?

7. What is the lowest GPA of all students?

8. What is the highest GPA of IS students?

9. How many students were born after 1/1/1990?

10. How many students entered the university in 2010?

66
11. Display all majors without redundancy

2. ... group by
select f1, group_function(f2), group_function(f3),...
from table
group by f1;

Exercise 16.2
1. In one SQL command, display the number of student for each major.

2. In one SQL command, display the number of students for each gender.

3. In one SQL command, display the average GPA of each major.

4. In one SQL command, display the number of students by entrance year (ie, 2010, 2011, 2012, etc.)

5. For students live in zip 90840, display how many students are in each major.

6. For male students only, display number of students by entrance year.

7. For students who enter the university in 2001, display number of students by major.

3. ... having
select f1, group_function(f2), group_function(f3),...
from table
group by f1
having [group_function related conditions];

Note: group_function in the having... statement does NOT need to appear in the select... statement.

Exercise 16.3
1. Display majors where average GPA is higher than 3.

2. Display majors where average GPA is lower than 2.

67
3. Display zip code where more than 20 students reside.

4. Display zip code where less than 3 students reside.

Putting it All Together.... Congratulations!!


SELECT...
FROM...
WHERE...
GROUP BY...
HAVING ...
ORDER BY... ;

68
Group by... examples
SQL> set echo on
SQL>
SQL> desc SchClasses;
Name Null? Type
----------------------------------------- -------- ----------------------------
CALL_NUM VARCHAR2(5)
DEPT VARCHAR2(10)
CODE VARCHAR2(10)
SECTION NUMBER(2)
SEMESTER VARCHAR2(10)
YEAR NUMBER(4)
INSTRUCTOR VARCHAR2(15)

SQL> select * from SchClasses;

CALL_ DEPT CODE SECTION SEMESTER YEAR INSTRUCTOR


----- ---------- ---------- ---------- ---------- ---------- ---------------
10111 IS 380 1 Fall 2012 Lee
10112 IS 380 2 Fall 2012 Smith
10113 IS 480 1 Fall 2012 Lee
10114 Fin 380 1 Fall 2012 Murphy
10115 Fin 401 1 Fall 2012 Smith
10116 IS 380 1 Spring 2013 Lee
10117 IS 380 2 Spring 2013 Lee
10118 IS 480 1 Spring 2013 Lee
10119 Fin 380 1 Spring 2013 Murphy
10120 Fin 401 1 Spring 2013 Murphy

10 rows selected.

SQL> desc Enrollments;


Name Null? Type
----------------------------------------- -------- ----------------------------
CALL_NUM VARCHAR2(5)
STU_NUM VARCHAR2(9)
GRADE VARCHAR2(1)
GRADE_POINT NUMBER(1)

SQL> select * from Enrollments;

CALL_ STU_NUM G GRADE_POINT


----- --------- - -----------
10111 111 A 4
10111 222 B 3
10111 333 A 4
10111 444 B 3
10112 555 B 3
10112 666 A 4
10112 777 B 3
10113 888 A 4
10113 999 B 3
10114 222 C 2
10114 444 B 3
10114 666 B 3
10114 777 A 4
10116 111 A 4
10116 222 B 3
10118 333 C 2
10118 444 B 3
10118 555 A 4
10118 666 A 4
10119 777 B 3
...

26 rows selected.

SQL>
SQL> -- 1. How many courses does Lee teach?
SQL>
SQL> select count(*)
2 from SchClasses
3 where Instructor='Lee';

COUNT(*)
----------
5
SQL>
69
SQL>
SQL> -- 2. How many courses does Lee teach during Fall 2012?
SQL>
SQL>
SQL>
SQL>
SQL>
SQL>
SQL> -- 3. How many IS 380 courses does Lee teach during Fall 2012?
SQL>
SQL>
SQL>
SQL>
SQL>
SQL>
SQL> -- 4. How many courses does EACH instructor teach?
SQL> select instructor, count(*)
2 from SchClasses
3 group by instructor;

INSTRUCTOR COUNT(*)
--------------- ----------
Lee 5
Murphy 3
Smith 2

SQL>
SQL> -- 5. How many courses are offered each year?
SQL> select year, count(*)
2 from SchClasses
3 group by year;

YEAR COUNT(*)
---------- ----------
2012 5
2013 5

SQL>
SQL> -- 6.How many courses are offer each year/semester?
SQL> select year, semester, count(*)
2 from SchClasses
3 group by year, semester;

YEAR SEMESTER COUNT(*)


---------- ---------- ----------
2012 Fall 5
2013 Spring 5

SQL>
SQL> -- 7.How many courses are offered per department?
SQL> select dept, count(*)
2 from SchClasses
3 group by dept;

DEPT COUNT(*)
---------- ----------
Fin 4
IS 6

SQL>
SQL> -- 8.How many courses are offered by each department each year?
SQL>
SQL>
SQL>
SQL> -- 9.How many courses are offered by each department, each year/semester?
SQL>
SQL>
SQL>
SQL> -- 10. How many students are enrolled in Fall 2012, IS 380 Section 1 course?
SQL>
SQL>
SQL>
SQL> -- 11. How many students are enrolled in Fall 2012?
SQL>
SQL>
SQL>
SQL> -- 12. How many students are enrolled in Fall 2012, Lee's course?
SQL>
SQL>
SQL>

70
SQL> -- 13. How many students are enrolled in Each year/semester?
SQL> select year, semester, count(*)
2 from SchClasses s, Enrollments e
3 where s.call_num=e.call_num
4 group by year, semester;

YEAR SEMESTER COUNT(*)


---------- ---------- ----------
2012 Fall 13
2013 Spring 13

SQL>
SQL> -- 14. During Fall 2012, what is the enrollment figure for each department?
SQL> select dept, count(*)
2 from SchClasses s, Enrollments e
3 where semester='Fall' and year=2012
4 and s.call_num=e.call_num
5 group by dept;

DEPT COUNT(*)
---------- ----------
Fin 4
IS 9

SQL>
SQL> -- 15. What is the grade distribution for IS 380, Section 1, during Fall 2012?
SQL> select grade, count(*)
2 from SchClasses s, Enrollments e
3 where Semester='Fall' and year=2012
4 and Dept='IS' and Code=380 and Section='1'
5 group by grade;

G COUNT(*)
- ----------
A 9
B 13
C 4

SQL>
SQL> -- 16.What is the grade distribution of courses taught by Lee?
SQL>
SQL>
SQL>
SQL> -- 17.What is average GPA of all courses taught by Lee?
SQL>
SQL>
SQL>
SQL> -- 18.Use one command to display class GPA of each Call_Num.
SQL> select call_num, avg(grade_point)
2 from enrollments
3 group by call_num;

CALL_ AVG(GRADE_POINT)
----- ----------------
10111 3.5
10112 3.33333333
10113 3.5
10114 3
10116 3.5
10118 3.25
10119 2.66666667
10120 3

8 rows selected.

SQL>
SQL> -- 19.Use one command to display class GPA of each Call_Num;
SQL> -- please also display Dept, Code, and Sections
SQL>
SQL> -- this is wrong...
SQL> select e.call_num, dept, code, section, avg(grade_point)
2 from Enrollments e, SchClasses s
3 where e.call_num=s.call_num
4 group by e.call_num;
select e.call_num, dept, code, section, avg(grade_point)
*
ERROR at line 1:
ORA-00979: not a GROUP BY expression

71
SQL>
SQL>

SQL> -- this is right...


SQL> select e.call_num, dept, code, section, avg(grade_point)
2 from Enrollments e, SchClasses s
3 where e.call_num=s.call_num
4 group by e.call_num, dept, code, section;

CALL_ DEPT CODE SECTION AVG(GRADE_POINT)


----- ---------- ---------- ---------- ----------------
10111 IS 380 1 3.5
10112 IS 380 2 3.33333333
10113 IS 480 1 3.5
10114 Fin 380 1 3
10116 IS 380 1 3.5
10118 IS 480 1 3.25
10119 Fin 380 1 2.66666667
10120 Fin 401 1 3

8 rows selected.

SQL>
SQL> -- 20. Display Call_num, Instructor of Call_Num that has class_gpa >= 3
SQL> select e.call_num, instructor, avg(grade_point) class_gpa
2 from Enrollments e, SchClasses s
3 where e.call_num=s.call_num
4 group by e.call_num, instructor
5 having avg(grade_point) >= 3;

CALL_ INSTRUCTOR CLASS_GPA


----- --------------- ----------
10111 Lee 3.5
10112 Smith 3.33333333
10113 Lee 3.5
10114 Murphy 3
10116 Lee 3.5
10118 Lee 3.25
10120 Murphy 3

7 rows selected.

SQL>
SQL> -- 21. Display Call_num, Dept, Code of courses that have 2 or less students enrolled.
SQL>
SQL>
SQL>
SQL>
SQL> -- 22. Display call_num, Dept, Code of courses that have no students enrolled
SQL>
SQL>
SQL> -- 23. Display class GPA by instructor, and sort by class GPA in descending order
SQL>
SQL>
SQL> spool off

Homework 8. Oracle Programming 2


Due on

72
Topic 17. Subqueries
For a complete reference on this topic, refer to
Oracle Chapter 11. When One Query Depends upon Another

ENROLLMENTS
SNAME CNUM GRADE
Andy IS 300 4
Betty IS 300 4
Cindy IS 300 2
Andy IS 380 3
Betty IS 380 4
Cindy IS 385 1
... ... ...

Question: For students who are taking IS 300, display those who have grade higher than the class GPA.
Step 1. What is the class GPA?
SQL> select avg(grade)
from enrollments
where cnum='IS 300';

AVG(GRADE)
----------
3.3333333

Step 2. Whose grade is higher than 3.333333?


SQL> select sname
from enrollments
where cnum='IS 300'
and grade>=3.333333;

NAME
----------
Andy
Betty

Subquery: Combine Step 1 and Step 2 in one query


SQL> select sname
from enrollments
where cnum='IS 300'
and grade >= (select avg(grade)
from enrollments
where cnum='IS 300');

NAME
----------
Andy
Betty

Question: Who gets the highest grade in IS 380?


What is the highest grade in class IS 380?
SQL> select max(grade)
from enrollments
where cnum='IS 380';

MAX(GRADE)
----------
4

Use subquery: WHO gets the highest grade in class IS 380?


SQL> select sname
from enrollments
where cnum='IS 380'
and grade= (select max(grade)
from enrollments
where cnum='IS 380');

SNAME
----------
Betty

73
Exercise 17.1
1. Write an SQL statement to show that, among all the courses that Betty takes, which course does she do the best
(receive the highest grade of all the courses she takes) ?
SQL>

2. Write an SQL statement to show that who gets the lowest grade in class IS 300?
SQL>

Exercise 17.2
Students Courses Enrollments
SNum SNAME STANDING STATUS GPA CNUM TITLE STATUS NumStu SNum CNUM GRADE
101 Andy Freshman Active IS 300 Intro to IS Active 101 IS 300 4
102 Betty Freshman Active IS 380 Database Active 102 IS 300 4
103 Cindy Junior Probation IS 385 Systems Cancelled 103 IS 300 2
104 David Senior Active IS 445 Telecomm Active 101 IS 380 3
105 Ellen Sophomore Probation ... ... ... 102 IS 380 4
... ... ... 103 IS 385 1
... ... ...

3. Write an SQL command to update student 101s GPA to the STUDENTS table. The student's GPA is calculated
from the ENROLLMENTS table.

4. Write an SQL command to update the number of student enrolled (NumStu) of IS 300 in the COURSES table.
Number of student enrolled is calculated from the ENROLLMENTS table.

-- Points of discussion: Data Redundancy and Efficiency.

74
Use the "in" operator

Exercise 17.3
Students Courses Enrollments
SNUM SNAME STANDING STATUS CNUM TITLE STATUS SNUM CNUM GRADE
101 Andy Freshman Active IS 300 Intro MIS Active 101 IS 300 4
102 Betty Freshman Active IS 380 Database Active 102 IS 300 4
103 Cindy Junior Probation IS 385 Systems Cancelled 103 IS 300 2
104 David Senior Active IS 445 Telecomm Active 101 IS 380 3
105 Ellen Sophomore Probation ... ... ... 102 IS 380 4
... ... ... ... 103 IS 385 1
... ... ...

1. Delete enrollment records if the student's status is 'PROBATION'.

2. Update grades to 'W' if the class is 'Cancelled'.

3. Write one SQL statement to update the standing to Senior for students who took 30 or more courses.

4. Write one SQL statement to update status to 'Cancelled' for courses that have 2 or less students enrolled.

5. Write an SQL statement to display SNum of students who are not enrolled in any class.

6. Write one SQL statement to find how many students who are not enrolled in any course.

7. Write an SQL statement to display name of students who are not enrolled in any course.

8. Write one SQL statement to delete students who are not enrolled in any course.

75
9. Write one SQL Statement to find how many courses have no students enrolled.

10. Write an SQL statement to display title of courses where no student is enrolled.

76
Topic 18. Database Administration
Textbook Chapter 14, 764-788

Database Administration
Database Administrator

DBA's Managerial Role


Support end user community
Develop and maintain policies, procedures, and standards of database operation
Maintain data security, privacy, and integrity
Perform data backup and recovery
Data distribution and use

DBA's Technical Role


DBMS and Utilities evaluation, selection, and installation
Design and implementation of databases and applications
Testing and evaluation of databases and applications
Operation of the DBMS, utilities and applications
Training and supporting users
Maintenance of the DBMS, utilities, and applications

Oracle Data Dictionary commands


For a complete reference on this topic, refer to
Oracle Chapter 18. By What Authority
Oracle Chapter 32. The Hitchhikers Guide to the ORACLE8 Data Dictionary

1. Use Data Dictionary

Oracle has an army of data dictionary tables! The followings are only a few of them. Check out Chapter 33 of your
Oracle book. If you are really interested, you can get an Oracle DBA type of book.

The user_tables Table


SQL> select table_name from user_tables;

TABLE_NAME
------------------------------
C
COUNTER
ENG
G
ORD
P
PRODUCT
......

The User_Tab_Columns Table


SQL> SELECT table_name, column_name, data_type from user_tab_columns;

Table
Name COLUMN_NAM DATA_TYPE
---------- ---------- ---------
C CALL# CHAR
C DEPT CHAR
C CODE CHAR
77
C TITLE CHAR
COUNTER TYPE CHAR
COUNTER MAXNUM NUMBER
ENG SNUM CHAR
ENG SNAME CHAR
G S# CHAR
G CALL# CHAR
G GRADE CHAR
G GRADEPT NUMBER
.....

The user_constraints Table


SQL> column owner format a10
SQL> column constraint_name heading 'Cons|Name' format a15
SQL> column constraint_type heading 'Cons|Type' format a15
SQL> column table_name heading 'Table|Name' format a10
SQL> column r_owner format a10
SQL> column r_constraint_name heading 'R|Cons|Name' format a15
SQL>
SQL> select owner, constraint_name, constraint_type, table_name, r_owner,
2 r_constraint_name from user_constraints;

R
Cons Cons Table Cons
OWNER Name Type Name R_OWNER Name
---------- --------------- --------------- ---------- ---------- ---------------
SOPHIE SYS_C00403 P ORD
SOPHIE ORDER_PS R ORD SOPHIE SYS_C00400
SOPHIE SYS_C00374 P P
SOPHIE SYS_C00398 P PRODUCT
SOPHIE SYS_C00400 P SP
SOPHIE SP_P R SP SOPHIE SYS_C00398
SOPHIE SP_S R SP SOPHIE SYS_C00399
SOPHIE SYS_C00399 P SUPPLIER

8 rows selected.

Note: P=Primary Key; R=Foreign Key

The User_Cons_Columns Table


SQL> select owner, constraint_name, table_name, column_name, position
2 from user_cons_columns
3 order by table_name;

OWNER CONSTRAINT_NAME TABLE_NAME COLUMN_NAM POSITION


---------- --------------- ---------- ---------- ---------
SOPHIE ORDER_PS ORD PNUM 1
SOPHIE ORDER_PS ORD SNUM 2
SOPHIE SYS_C00403 ORD ONUM 1
SOPHIE SYS_C00374 P PNUM 1
SOPHIE SYS_C00398 PRODUCT PNUM 1
SOPHIE SP_P SP PNUM 1
SOPHIE SYS_C00400 SP SNUM 2
SOPHIE SP_S SP SNUM 1
SOPHIE SYS_C00400 SP PNUM 1
SOPHIE SYS_C00399 SUPPLIER SNUM 1

10 rows selected.

Exercise 18.1
Given the above data from the data dictionary, draw a referential diagram to represent user Sophies tables. (that is,
identify which tables she has, and all the primary key and foreign keys.)

2. File space management


Chapter 26

3. Performance Tuning
78
Use timer

-- Measure the CPU time of executing a specific command


SQL> set timing on
SQL> create table s (s# char(2), sname char(20), city char(10));
Table created.
real: 930
SQL> set timing off
-- new version of Oracle will show 00:00:00.93

-- Measure the elapsed time between timing start and timing stop
SQL> timing start mytimer
SQL> -- zzzzz
SQL> timing show mytimer
timing for: mytimer
real: 11810
SQL> timing stop mytimer
timing for: mytimer
real: 17910

Use Index
Whats an index?
Using index will improve the data performance when the table has more than 250 records (i.e., for smaller tables,
indexing does not make much of a difference)
Set index on the primary key or foreign key fields

create index index_name on table_name (column1, column2, ...);


create index Index_snum on student(snum);

drop index index_name;


drop index Index_snum;

De-normalize tables

User Management
User
Role: Standard Oracle roles: connect, resource, dba
Customized roles:

/* You must be a DBA user to do the following */


create user user_name identified by password;
grant role to user_name;
drop user user_name;

create user sophie identified by 957263;


grant connect, resource, dba to sophie;
drop user sophie;

4. Data Backup and Recovery

Exercise 18.2
1. Name and describe three of a DBA's managerial roles.
2. Name and describe three of a DBA's Technical role.
3. What is a "Data Dictionary"?
4. What is an index?
5. What is the SQL code to display user Scotts table names?
6. What is the SQL code to display number of tables by each user?
7. What is the SQL code to display column names of user Scotts COURSE table?
8. What is a role in Oracle? What is a user in Oracle? What are the three standard roles in Oracle?
79

You might also like