You are on page 1of 54

CS – Database Management Systems

Session 5 Agenda

 Note on Individual Assignments / Plagiarism


 Oracle Installation Questions
 Chapter 5: Relational Database Management Systems and SQL
 Chapter 5 Team Assignment Review
 Chapter 5 Individual Assignment Review
 do not share or submit someone else's homework.
 do not seek anyone's help or work together on individual
assignments.
 If you have questions, please ask me.
 if you need additional time on any homework assignment, please ask
me before the assignment is due.
Chapter 5: Relational Database
Management Systems and SQL
Chapter 5: Relational Database Management Systems and SQL

History of Relational DBMS and SQL

 Relational databases first proposed by E. F. Codd in 1970


 SQL used in prototype System R, which was developed by IBM in
the late 1970s
 SQL used in Oracle - Ellison, Miner & Oakes, released the
commercial relational database system in late 1970s
 Ingres, another RDBMS was developed at the University of
California at Berkeley by Eugene Wong and Michael Stonebraker
 SQL incorporated into IBM’s SQL/DS in 1981, and DB2 in 1983
 SQL also incorporated in many other RDBMS such as Microsoft
SQL Server, MySQL, Informix, Sybase, PostgreSQL, Microsoft
Access
Chapter 5: Relational Database Management Systems and SQL

Standards

 American National Standards Institute (ANSI) and the International


Standards Organization (ISO) adopted SQL as a standard language
for relational databases and published specifications for the SQL
language in 1986 called SQL-1
 Minor revision, SQL-89
 Major revision, SQL-2,1992
 Major revision, SQL-3, 1999, 2003, 2006, 2008, 2011- multi-part
revision, includes new data types, object-oriented (OO) facilities,
user defined datatypes (UDTs), triggers, support for XML, temporal
databases
 Most vendors support standard, but have slight variations of their
own
Chapter 5: Relational Database Management Systems and SQL

Components of SQL

 Data Definition Language (DDL) is the syntax to define the


database – Ex: create or modify database objects such as tables,
indexes, users, etc.

 Data Manipulation Language (DML) is the syntax used to process


the database – Ex: select, insert, update, delete data from the
database.

 Authorization Language is the syntax used to grant privileges to


users – Ex: grant, revoke, etc
Chapter 5: Relational Database Management Systems and SQL

Examples of DDL statements

CREATE TABLE is used to create table.


Example: SQL> CREATE TABLE <table_name>
( <column_a> <datatype> [<column constraint>],
<column_b> <datatype> [<column constraint>],
…,
[<table constraints>]);

DROP TABLE is used to drop table.


Example: SQL> DROP TABLE <table_name>;

CREATE INDEX is used to create an index.


Example: SQL> CREATE INDEX <index_name>
ON <table_name> (column_b);
Chapter 5: Relational Database Management Systems and SQL

University Sample Database Table DDL


CREATE TABLE Student (
stuId VARCHAR2(6) NOT NULL,
lastName VARCHAR2(20) NOT NULL,
firstName VARCHAR2(20) NOT NULL,
major VARCHAR2(10),
credits NUMBER(3) DEFAULT 0,
CONSTRAINT Student_stuId_pk PRIMARY KEY (stuId),
CONSTRAINT Student_credits_cc CHECK ((credits>=0) AND (credits < 150)));

CREATE TABLE Faculty (


facId VARCHAR2(6) NOT NULL,
name VARCHAR2(20) NOT NULL,
department VARCHAR2(20),
rank VARCHAR2(10),
CONSTRAINT Faculty_facId_pk PRIMARY KEY (facId));
Chapter 5: Relational Database Management Systems and SQL

University Sample Database Table DDL (Con’t)


CREATE TABLE Class (
classNumber VARCHAR2(8) NOT NULL,
facId VARCHAR2(6),
Schedule VARCHAR2(8),
room VARCHAR2(6),
CONSTRAINT Class_classNumber_pk PRIMARY KEY (classNumber),
CONSTRAINT Class_schedule_room_uk UNIQUE (schedule, room),
CONSTRAINT class_facId_fk FOREIGN KEY (facid)
REFERENCES Faculty (facId) ON DELETE CASCADE);

CREATE TABLE Enroll (


stuId VARCHAR2(6) NOT NULL,
classNumber VARCHAR2(8) NOT NULL,
Grade VARCHAR2(2),
CONSTRAINT Enroll_classNumber_stuId_pk PRIMARY KEY (classNumber,stuId),
CONSTRAINT Enroll_classNumber_fk FOREIGN KEY (classNumber)
Chapter 5: Relational Database Management Systems and SQL

University Sample Database

Student Table Faculty Table

Enroll Table

Class Table
ADD (who_updated date,
when_updated varchar2(8));

SQL> ALTER TABLE <table_name>


MODIFY (<column_name> varchar2(50));

SQL> ALTER TABLE <table_name>


DROP COLUMN<column_name>;

SQL> ALTER TABLE <table_name>


RENAME COLUMN <old_column_name>
TO <new_columnd_name>;
Chapter 5: Relational Database Management Systems and SQL

ALTER TABLE (Con’t)

Example to add primary key, foreign key, check constraint:


SQL> ALTER TABLE STUDENT
ADD CONSTRAINT Student_stuId_pk
PRIMARY KEY (stuId);

SQL> ALTER TABLE CLASS


ADD CONSTRAINT class_facId_fk
FOREIGN KEY (facid)
REFERENCES Faculty (facId) ON DELETE CASCADE;

SQL> ALTER TABLE STUDENT


ADD CONSTRAINT Student_credits_cc
CHECK ((credits>=0 AND (credits < 150)));
Chapter 5: Relational Database Management Systems and SQL

ALTER TABLE (Con’t)

Example to drop constraint and rename, drop table:


SQL> ALTER TABLE <table_name>
ADD CONSTRAINT <constraint_name>

SQL> ALTER TABLE <table_name


DROP CONSTRAINT <constraint_name>;

SQL> RENAME <old_table_name>


TO <new_table_name>;

SQL> DROP TABLE <table_name>;


Ex: CREATE INDEX student_n1
ON STUDENT (LASTNAME);

Order is ascending - ASC (default) – or you can create in descending


order - DESC
Ex: CREATE INDEX student_n1
ON STUDENT (LASTNAME DESC);
Chapter 5: Relational Database Management Systems and SQL

UNIQUE INDEXES

Unique specification enforces unique value for indexed columns or


combination of columns:
SQL> CREATE UNIQUE INDEX <index_name>
ON <table_name> (<column_name(s)>);

Note: unique index for primary key is automatically created.


Chapter 5: Relational Database Management Systems and SQL

CREATE USER

CREATE USER: this privilege creates user.


Ex: SQL> create user <username> identified by <password>;

ALTER USER: this privilege is used for authentication or database


resource characteristics. Ex: changing password, tablespace,etc

GRANT CONNECT: Usually when creating a user, you need to GRANT


CONNECT to <username>; to allow the user to connect to the
database.

GRANT RESOURCE would allow user to create objects in his/her


schema. Ex: GRANT RESOURCE to <user_name>;

GRANT ROLE: Instead of granting individual grants to user you can grant
to the role and then just grant the role to the user.
Chapter 5: Relational Database Management Systems and SQL

CREATE VIEW

CREATE VIEW: is a virtual table formed by a query.


It can be used to show:
 a subset of table (value-independent view)
 Only show certain rows by using a WHERE clause (valued-independent
view).
 Rename attributes
 Join several tables
 use functions or sub-queries in the SELECT.
SQL> CREATE VIEW <view_name>
[view_column1, view_column2, …]
AS SELECT column1, column2, …
FROM TABLE_NAME, [TABLE_NAME2, …]
WHERE condition;
Chapter 5: Relational Database Management Systems and SQL

CREATE VIEW (Con’t)

Example of creating a student_new view (limiting number of attributes and


renaming attributes)
SQL> CREATE view STUDENT_NEW
(student_id, first_name, last_name)
AS SELECT stuid, firstname,lastname
FROM STUDENT;
Note: this privilege is not included in the RESOURCE role; therefore
you need to grant it before using.
From sys: grant create view to resource;
Chapter 5: Relational Database Management Systems and SQL

CREATE VIEW (Con’t)


SQL> desc student
Name Null? Type
---------------- -------- ------
STUID NOT NULL VARCHAR2(6)
LASTNAME NOT NULL VARCHAR2(20)
FIRSTNAME NOT NULL VARCHAR2(20)
MAJOR VARCHAR2(10)
CREDITS NUMBER(3)

SQL> desc student_new


Name Null? Type
---------------- -------- ------
STUDENT_ID NOT NULL VARCHAR2(6)
FIRST_NAME NOT NULL VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(20)
Chapter 5: Relational Database Management Systems and SQL

Examples of DDL statements (Con’t)

ALTER TABLE: is used to add, modify, drop columns in a table.


Example: SQL> ALTER TABLE <table_name>
ADD (who_updated varchar2(8),
when_updated date);

SQL> ALTER TABLE <table_name>


MODIFY (customer_name varchar2(50));

SQL> ALTER TABLE <table_name>


DROP COLUMN<column_name>;

SQL> ALTER TABLE <table_name>


RENAME COLUMN <old_column_name>
TO <new_columnd_name>;
Chapter 5: Relational Database Management Systems and SQL

SELECT Clause

Find the name of all students:


SQL> SELECT firstname, lastname
FROM student;

Select all the attributes:


SQL> SELECT *
FROM student;

Select a list of majors that students are taking (no duplicates)


SQL> SELECT DISTINCT major
FROM student;
Chapter 5: Relational Database Management Systems and SQL

INSERT Clause

Describe Student table:


SQL> desc student
stuId VARCHAR2(6) NOT NULL
lastName VARCHAR2(20) NOT NULL
firstName VARCHAR2(20) NOT NULL
major VARCHAR2(10)
credits NUMBER(3)

Insert row into the student table:


SQL> INSERT INTO STUDENT
VALUES ('S1025',‘Jones','Tom',‘Math',50);

Note: The order of the values should follow the order of the columns on the table.
Chapter 5: Relational Database Management Systems and SQL

DELETE/TRUNCATE Clause

Delete all of the rows from the student table:


SQL> DELETE FROM student;

SQL> TRUNCATE TABLE student;

Note: Difference between DELETE and TRUNCATE


is that TRUNCATE cannot be rolled back.
Chapter 5: Relational Database Management Systems and SQL

UPDATE Clause

Describe Student table:


SQL> desc student
stuId VARCHAR2(6) NOT NULL
lastName VARCHAR2(20) NOT NULL
firstName VARCHAR2(20) NOT NULL
major VARCHAR2(10)
credits NUMBER(3)

Change Tom Smith’s major from History to Math:


SQL> UPDATE STUDENT
SET major = ‘Math’
WHERE lastName = ‘Smith’
AND firstName = ‘Tom’;
Chapter 5: Relational Database Management Systems and SQL

WHERE Clause

Find the name of all students that are majoring in Math:


SQL> SELECT firstname, lastname
FROM student
WHERE major = ‘Math’;

Find the name of all students that are majoring in Math and have taken
more than 30 credits:
SQL> SELECT firstname, lastname
FROM student
WHERE major = ‘Math’
AND credits > 30;
Chapter 5: Relational Database Management Systems and SQL

WHERE Clause (Con’t)

Find the name of all students EXCEPT the ones majoring in Math:
SQL> SELECT firstname, lastname
FROM student
WHERE major <> ‘Math’;

Find the name of all students with the last name beginning with ‘S’
SQL> SELECT firstname, lastname
FROM student
WHERE lastName like ‘S%’;
Chapter 5: Relational Database Management Systems and SQL

WHERE Clause (Con’t)

Find the names of all faculty with salary between 90k and 100k:
SQL> SELECT *
FROM faculty
WHERE salary BETWEEN 90000 AND 100000;

Delete the students that major in History:


SQL> DELETE FROM student
WHERE major = ‘History’;
Chapter 5: Relational Database Management Systems and SQL

ORDER Clause

Find the name of all students in alphabetical order:


SQL> SELECT firstname, lastname
FROM student
ORDER BY lastname;

Find the name of all students in descending order:


SQL> SELECT firstname, lastname
FROM student
ORDER BY lastname desc;

Select a list of majors that students are taking (no duplicates)


SQL> SELECT DISTINCT major
FROM student;
Chapter 5: Relational Database Management Systems and SQL

INNER / OUTER JOIN Tables

What are the classes that each student is enrolled in:


SQL> SELECT s.stuId, s.firstname, s.lastname, e.classNumber
FROM student s,
enroll e
WHERE s.stuID = e.stuID
ORDER BY s.lastname;

OUTER JOIN will tell you all the students whether they are enrolled in a class or not:
SQL> SELECT s.stuId, s.firstname, s.lastname, e.classNumber
FROM student s,
enroll e
WHERE s.stuID = e.stuID(+)
ORDER BY s.lastname;
Chapter 5: Relational Database Management Systems and SQL

INNER JOIN Example


Chapter 5: Relational Database Management Systems and SQL

OUTER JOIN Example


Chapter 5: Relational Database Management Systems and SQL

GROUP BY / HAVING CLAUSE

Find the names and average salaries of all departments:


SQL> SELECT department, avg(salary)
FROM faculty
GROUP BY department;

Find the names and average salaries of all departments whose average salary is
greater than 90000:
SQL> SELECT department, avg(salary)
FROM faculty
GROUP BY department
HAVING avg(salary) > 90000;
Chapter 5: Relational Database Management Systems and SQL

GROUP BY / HAVING CLAUSE Example


Chapter 5: Relational Database Management Systems and SQL

NOT IN

Find all students enrolled in a class:


SQL> SELECT * FROM student
WHERE stuid
IN
(SELECT stuid FROM enroll);

Find all students NOT enrolled in a class:


SQL> SELECT * FROM student
WHERE stuid
NOT IN
(SELECT stuid FROM enroll);
Chapter 5: Relational Database Management Systems and SQL

NOT IN Example
Chapter 5: Relational Database Management Systems and SQL

UNION / UNION ALL

UNION – selects from 2 tables WITHOUT duplicates:


SQL> SELECT stuid
FROM student
UNION
SELECT stuid
FROM enroll;

UNION ALL – selects from 2 tables WITH duplicates:


SQL> SELECT stuid
FROM student
UNION ALL
SELECT stuid
FROM enroll;
Chapter 5: Relational Database Management Systems and SQL

UNION / UNION ALL Example


Chapter 5: Relational Database Management Systems and SQL

INTERSECT /MINUS

INTERSECT – returns rows from one table that also RESIDES in


the other table:
SQL> SELECT stuid
FROM student
INTERSECT
SELECT stuid
FROM enroll;
Chapter 5: Relational Database Management Systems and SQL

INTERSECT /MINUS (Con’t)

MINUS– returns rows from one table MINUS the rows from the
second table:
SQL> SELECT stuid
FROM student
MINUS
SELECT stuid
FROM enroll;
Chapter 5: Relational Database Management Systems and SQL

INTERSECT / MINUS Example


Chapter 5: Relational Database Management Systems and SQL

TRIGGERS

Triggers can be executed before or after insert, update, or delete


CREATE OR REPLACE TRIGGER <trigger_name>
[BEFORE/AFTER] [INSERT/UPDATE/DELETE] ON <table_name>
REFERENCING NEW AS NEW OLD AS OLD
[FOR EACH ROW] [WHEN condition]
BEGIN
trigger body
END;
/

:OLD refers to the old value being updated.


:NEW refers to the new value that is being inserted or updated
Chapter 5: Relational Database Management Systems and SQL

TRIGGERS (Con’t)

Example of updating who_updated and when_updated:

CREATE or REPLACE TRIGGER student_t1


BEFORE INSERT OR UPDATE on student
REFERENCING NEW AS NEW OLD AS OLD
for EACH ROW
BEGIN :NEW.WHO_UPDATED := USER;
:NEW.WHEN_UPDATED := SYSDATE;
END;
/
Chapter 5: Relational Database Management Systems and SQL

TRIGGERS (Con’t)
Chapter 5: Relational Database Management Systems and SQL

TRIGGERS (Con’t)

 Triggers can be disabled using the alter trigger command:


Ex: ALTER TRIGGER <trigger_name> DISABLE;
 Triggers can be enabled using the alter trigger command:
Ex: ALTER TRIGGER <trigger_name> ENABLE;
 Triggers can be dropped using the drop trigger command:
Ex: DROP TRIGGER <trigger_name>;
Chapter 5 Questions?
Chapter 5: Individual and Team
Assignments Review
Chapter 5: Relational Database Management Systems and SQL

Chapter 5: Individual Laboratory Exercises Assignment

Use DDL provided to create the University database in Oracle:


Fig_5.1_DDL&InsertsforUniversityExample.txt

Step 5.1. Highlight and copy the CREATE TABLE commands (one at a
time) and paste them into SQL*Plus at the SQL> prompt.
You should see the message: Table Created after each statement is executed.
Show your work – screenshots

Step 5.2. Now insert the records into your tables. To do this, copy each
INSERT command (one at a time) and paste them into SQL*Plus at
SQL> prompt.
You should see the message: 1 row created after each statement is executed.
Show your work – screenshots
Chapter 5: Relational Database Management Systems and SQL

Chapter 5: Individual Laboratory Exercises Assignment (Con’t)

Step 5.3. Design SQL queries for the following questions:


Step 5.3a. Find the names of all History majors.

Step 5.3b. Find the class number, schedule, and room for all classes
that Smith of the History department teaches.

Step 5.3c. Find the names of all students who have fewer than average
number of credits.

Step 5.3d. Find the names of all the teachers that Ann Chin has, along
with all her classes and midterm grades from each

Step 5.3e. For each student, find the number of classes he or she is
enrolled in. Limit the results to only students who are enrolled.
Chapter 5: Relational Database Management Systems and SQL

Chapter 5: Individual Laboratory Exercises Assignment (Con’t)

5.4. Execute the five queries in the database and show the results.
Show your work – screenshots
Chapter 5: Relational Database Management Systems and SQL

Chapter 5 Team Assignment

For the relational schema you developed at the end of Chapter 4 for
the team project, carry out the following steps to implement the
design using Oracle:

Step 5.1 - Update the data dictionary and list of assumptions as


needed. For each table, write the table name and write out the
names, data types, and sizes of all the data items, nullity, and
identify any constraints, using the conventions of the DBMS you will
use for implementation.
Chapter 5: Relational Database Management Systems and SQL

Chapter 5 Team Assignment (Con’t)

Example:
TABLE: Student
Attribute Data Type Length Nullity Constraint
stuId VARCHAR2 6 NOT NULL Primary
Key
lastName VARCHAR2 20 NOT NULL
firstName VARCHAR2 20 NOT NULL
major VARCHAR2 10
credits NUMBER 3 DEFAULT 0
>=0 <150
Chapter 5: Relational Database Management Systems and SQL

Chapter 5 Team Assignment (Con’t)

Step 5.2 - Write and execute SQL statements to create all tables needed to
implement the design.
Create Oracle DDL statements from Step 5.1 and create your tables and
primary keys in the Oracle database.
Show your work - screenshots.

Step 5.3 – Write and execute SQL statements to create indexes for foreign
keys and for any other columns as needed
Create Oracle DDL statements from Step 5.1 and issue your foreign key
constraint statements in the Oracle database.
Show your work - screenshots.

Note: you may combine Step 5.2 and 5.3 and issue your foreign
constraints as part of the create table statement.
Chapter 5: Relational Database Management Systems and SQL

Chapter 5 Team Assignment (Con’t)

Step 5.4 - Write and execute SQL statements to insert at least five records
in each table, preserving all constraints.
Create five INSERT statements for each table and execute each insert
statement in the Oracle database.
Show your work - screenshots.

Step 5.5 - Write and execute SQL statements that will process five non-
routine requests for information from the database just created.
Come up with 5 questions and create SQL Statements to satisfy each question.
Show your work - screenshots.
Note: Make sure to ask 5 different questions so you have 5 different sql
statements.
Chapter 5: Relational Database Management Systems and SQL

Chapter 5 Team Assignment (Con’t)

Step 5.6 - Write and execute SQL statements to create at least one trigger.
Show your work - screenshots.

Step 5.7 - Write and execute SQL statements to demonstrate that the
trigger is working as expected.
To demonstrate that the trigger is working as expected, provide a screenshot of
the data before and after the trigger is executed.

You might also like