380 Notes Fa2016
380 Notes Fa2016
Database
Lecture Notes
Fall 2016
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.
Data
Record:
Field or Attribute:
Table:
Data Management
Insert:
Update:
Delete:
Data Retrieval or Query:
Ad-hoc Query:
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.
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
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
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
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
5
Relational Database Concepts
Entity, instance, and Attributes
Entity (some call it entity set)
- A conceptual collection of things, 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.
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
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
==
==
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".
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
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?
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
STUDENTS ADVISORS
Primary Key: SNum AdvNum
Foreign Key: AdvNum, references Advisors.AdvNum None
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
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)
2) For each table, identify the primary key and foreign key(s).
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
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
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
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.
16
8. Display SNum of students who received an A from any of Lees class.
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.
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
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
Query
Asking database questions or view the table from different perspective/criterion without modifying the content.
18
Topic 4. Basic SQL
Data Definition Language (DDL)
Creating a Table
create table t
(fd_name1 fd_type,
fd_name2 fd_type, ...);
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));
Writing comments
You can write comments in the 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!!
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];
Data Query
Display Records
select [columns]
from [table]
where [conditions];
20
Conditions
Mathematical and Logical operators
=, <>, !=, >, <, >=, <=, and, or, not
ex: ... where price > 10;
ex: ... where price > 10 and code <> 1234;
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 */
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
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.
21
8. Delete the student record whose SSN is 222.
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
Log in: A log in screen appears. Log in to ORACLE by (not case sensitive):
Username
Password
Host
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.
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.
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
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.
1 row created.
SQL>
SQL> select * from stu;
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.
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.
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.
** This is the way that you will turn in most of the homework!
Lets write another Oracle program which would query the STU table that you just created.
25
Go to Notepad and choose File New.
set echo on
spool a:myprog2.txt
spool off
now choose File - Save. Specify the new file name to be a:myprog2.sql.
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.
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.
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
28
Topic 6. JOIN
Join is done by product, select, and project in one SELECT statement
SELECT [columns]
FROM [tables]
WHERE [conditions];
12 rows selected.
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;
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.
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
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.
DROP constraints:
alter table t2 drop primary key (f1,f2);
32
2. DROP constraints:
alter table child drop constraint fk1;
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));
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.
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:
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.
36
PNum PName ENum EName JobClass HourlyRate Hours
PNUM PNAME
PNUM PNAME
JobClass HourlyRate
37
The Boyce-Codd Normal Form (BCNF)
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.
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?
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
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
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.
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: __________________
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
1:1
1:M
M:N
Cardinality: Range of occurrences associated with each occurrence of the related entity.
43
Strong vs. Weak entity (weak entity is represented by )
Existence dependency
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.
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.
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 ----------------
'&variable'
&variable
File Structure
SQL> select * from STUDENTS;
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';
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
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.
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.
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.
2. System prompts:
Please enter the new major code:
and read the new major code (variable name is vMajor)
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
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)
50
Topic 11. More SQL Commands
Product Unit
PID Description Price Quantity
---- -------------------- ---------- --------
0001 Monitor $299.99 3
0002 Keyboard $49.99 2
0003 Mouse Pad $1.99 100
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
51
... use alias for table names
SQL> select student.snum, enrollment.snum, student.sname
From student, enrollment
Where student.snum=enrollment.snum;
11.4 Views
A definition of a restricted portion of a table.
create view v1 as
select f1, f2,...
from t1
where [conditions];
View created.
SNU SNAME
--- ----------
101 Andy
102 Betty
103 Cindy
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
...
4 rows selected.
...
53
6 rows selected.
SNUM SNAME
--------- ----------
101 Andy
102 Betty
103 Cindy
104 David
105 Ellen
106 Frank
107 George
108 Helen
8 rows selected.
SNUM SNAME
--------- ----------
103 Cindy
104 David
SNUM SNAME
--------- ----------
101 Andy
102 Betty
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.
55
Topic 12. Program a Counter
File Structure
SQL> describe products;
Name Null? Type
------------------------------- -------- ----
PID CHAR(5)
DESCRIPTION CHAR(25)
PRICE NUMBER(10,2)
no rows selected
MAXNUM
---------
1000
*--------------------------------------------*
* Welcome to the Check out Program *
*--------------------------------------------*
Price: 1099.99
56
The Following Transaction has been confirmed ...
Trans Product
Numbe TDATE ID Quantity
----- --------- ---------- --------
1000 17-FEB-15 104 3
MAXNUM
---------
1001
*--------------------------------------------*
* Welcome to the Check out Program *
*--------------------------------------------*
Price: $25.99
Trans Product
Numbe TDATE ID Quantity
----- --------- ---------- --------
1000 17-FEB-15 104 3
1001 17-FEB-15 103 8
MAXNUM
---------
1002
SQL>
57
Note: this program can also be done with sequence.
Oracle Code
/* Program 3.5.1 */
prompt
prompt
prompt *--------------------------------------------*
prompt * Welcome to the Check out Program *
prompt *--------------------------------------------*
prompt
prompt
prompt
prompt
commit;
set heading on
prompt
prompt
prompt The Following Transaction has been confirmed ...
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
SSN char(9)
Lastname char(10)
Firstname char(10)
Middlename char(10)
Phone char(10)
Write the SQL to display the student's full name and phone number in the format of
59
Exercise 13.3
You have the following STUDENT table:
Write a program to display student information based on a user-input SSN, like the following:
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 )
2. Write a program hw7.sql that will insert a new customer record into the table, like the following:
*-------------------------------------------*
* -- 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
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
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
SYSDATE-CHECKOUT
----------------
1.4863079
TO_CHAR(TRUNC(SYSDATE),'MONTHDD,YYYY,HH:MI
------------------------------------------
August 23, 2015, 12:00:00 AM, Sunday
TRUNC(SYSDATE)-TRUNC(CHECKOUT)
------------------------------
1
Table created.
1 row created.
62
SQL> insert into students values ('Betty',to_date('06/17/1987','mm/dd/yyyy'), 2.98);
1 row created.
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>
SQL> -- learn to use "break on"
SQL> break on state skip 1
SQL> select state, cname, account, amount from t39;
SQL> -- "break on" must be used with "order by" to make sense
SQL> select state, cname, account, amount from t39 order by state;
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;
SQL> -- it's a good habit to clear break, compute, and column format when done
SQL> clear break
SQL> clear compute
SQL> clear column
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)
Exercise 16.1
1. How many students are there?
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?
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.
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.
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.
67
3. Display zip code where more than 20 students reside.
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)
10 rows selected.
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;
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;
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>
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;
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
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
NAME
----------
Andy
Betty
NAME
----------
Andy
Betty
MAX(GRADE)
----------
4
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.
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
... ... ...
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
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.
TABLE_NAME
------------------------------
C
COUNTER
ENG
G
ORD
P
PRODUCT
......
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
.....
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.
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.)
3. Performance Tuning
78
Use timer
-- 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
De-normalize tables
User Management
User
Role: Standard Oracle roles: connect, resource, dba
Customized roles:
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