Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

Database Administration

(Advance SQL)

Compiled by:

Monina D. Barretto Page | 1


Table of Contents

Message to the Student ............................................................................................................................. 3


Course Syllabus .......................................................................................................................................... 5
INTRODUCTION TO DATABASE ADMINISTRATION ................................................................... 13
STRUCTURED QUERY LANGUAGE (SQL) .................................................................................... 15
INTEGRITY CONSTRAINTS ............................................................................................................... 27
WORKING WITH MULTIPLE TABLES .............................................................................................. 35
WHERE clause as join predicate .................................................................................................. 35
Use of JOIN to combine data from multiple tables .................................................................. 37
SUBQUERY............................................................................................................................................ 44
TRANSACTION ..................................................................................................................................... 48
STORED PROCEDURE ................................................................................................................... 52
VIEWS ..................................................................................................................................................... 58
TRIGGERS ............................................................................................................................................. 61
ERROR HANDLING .............................................................................................................................. 69
BACK-UP AND RECOVERY ............................................................................................................... 72
CONCURRENCY CONTROL .............................................................................................................. 75
IMPORT / EXPORT IN RELATIONAL DATABASES ...................................................................... 78
Appendix: MySQL Workbench and the Visual Editor .............................................................................. 86

Page | 2
Message to the Student

This instructional material presents all topics which are based in the course syllabus. It
is presented in a concise, simple manner intended to guide you through the different
topics of the course. Please read the material thoroughly for better understanding of the
lessons.

You are encouraged to read additional learning materials available to you. There are
suggested reading materials at the end of each topic.

All course materials, activities which have a need to access the internet are optional. You
may access them only if you can gain access to the net.

The assessments at the end of each module must be answered. They are intended to
gauge your understanding of what you have learned from the lessons.
Your professor should get in touch with you at the start of the semester regarding the
submission of answers to assessment and will give further instructions on how distance
learning will be implemented.

Thank you, God bless, and keep safe.

Page | 3
Additional notes to the student
Hi,
Please see which case applies to you:

1. If you have a laptop with MySQL or SQL Server already installed, then you
may run your programs using either of the two RDBMS.

2. If you have a laptop but has no RDBMS installed, and you have access to
the internet although limited, when you gain access to the net, you can
download MySQL which is an open source software using this link
https://dev.mysql.com/downloads/workbench/
The tutorial on how to download the software in in the following link. This is
just a 5 minute video and is very straigthforward and easy to follow.
https://www.youtube.com/watch?v=u96rVINbAUI
Once you already have the software, you can run your programs in MySQL.
3. If you have a laptop but has no MySQL nor SQL Server in your laptop, and
has no way of accessing the internet, you may use MS Access (MS Office)
for the programming exercises. There will be some syntax differences
though.

4. If you do not have a laptop, then you will have to write codes and do desk
checking. The important thing is to know which commands to use
based on the requirement and to be familiar with the syntax. You may
not be able to run your codes now but as long as you follow the syntax in
coding, it will be a matter of encoding your program once you get hold of a
computer (this is not however expected of you during the semester).
Just make sure you practice programming by answering (by writing) all of
the assessment/activities at the end of SQL topics.

The SQL programs in this instructional material are written in SQL Server and MySQL.
For those syntax where there is no comment as to which RDBMS code was used, it
means the syntax is the same for both.

Since MySQL is open source, this is what will be used. It would also be good though to
read the portions for SQL Server since concepts are the same. The syntax differs for
some cases.

Page | 4
Course Syllabus
POLYTECHNIC UNIVERSITY OF THE PHILIPPINES
College of Computer and Information Sciences
Department of Information Technology

COURSE TITLE Database Administration

COURSE CODE COMP 20213

CREDIT UNITS 3 UNITS / 5 HOURS (2 Units Lecture And 1 Unit Lab)

COURSE COMP 20093


PREREQUISITE

COURSE This course discusses basic concepts on database administration. It includes discussions how
DESCRIPTION SQL is used to enforce database security, ensure database availability, and optimize database
performance. This course builds student knowledge in coding advance SQL and integrates it
with the knowledge learned from the pre-requisite subject to develop an application which fully
utilizes the capabilities of a database management system.

Institutional Learning Outcomes Program Outcomes Course Outcomes

1. Creative and Critical Thinking Apply knowledge of computing, An


Graduates use their imaginative as well science, and mathematics appropriate Analyze real life business problem, while
as rational thinking abilities to life to the discipline. dissecting the root cause of the problem.
situations in order to push boundaries,
realize possibilities, and deepen their Analyze complex problems, and
interdisciplinary and general identify and define the computing
Evaluate database needs of a group and
requirements appropriate to its
understanding of the world. formulate recommendations based on
solution.
principles in database design.
Identify and analyze user needs and
take them into account in the selection,
creation, evaluation and
administration of computer-based
systems.
2. Effective Communication Communicate effectively with the Document data gathered in every step of
Graduates are proficient in the four computing community and with the process.
macro skills in communication (reading, society-at- large about complex Create reports on progress updates.
writing, listening, and speaking) and are computing activities through logical Create project presentations on the
able to use these skills in solving writing, presentations, and clear application
problems. Making decisions and instructions.
articulating thoughts when engaging
with people in various circumstances.

3. Strong Service Orientation Function effectively as a member or Perform tasks, depending on the role
Graduates exemplify the potentialities leader of a development team assignment
of an efficient, well-rounded and recognizing the different roles within a Contribute expertise to other members of
responsible professional deeply team to accomplish a common goal. the team.
committed to service excellence. Solve problems, whether technical and or
non-technical issues that may arise.

Page | 5
4. Community Engagement Analyze the local and global impact of Design and develop applications that will
Graduates take an active role in the computing information technology on benefit the community
promotion and fulfillment of various individuals, organizations, and society.
advocacies (educational, social and
environmental) for the advancement of
community welfare. Integrate IT-based solutions into the
user environment effectively.

5. Adeptness in the Responsible Use of Apply knowledge through the use of Design and develop efficiently running
Technology current techniques, skills, tools and applications
Graduates demonstrate optimized use practices necessary for the IT
of digital learning abilities, including profession Write advance SQL statements that will
technical and numerical skills. maintain data integrity and manage the
Understand best practices and database system
standards and their applications.

Design, implement, and evaluate


computer-based systems, processes,
components, or programs to meet
desired needs and requirements under
various constraints.

Assist in the creation of an effective IT


project plan.

6. Passion to Lifelong Learning Recognize the need for and engage in Plan knowledge sharing with the team
Graduates are enabled to perform and planning, self-learning, and improving for lessons which will be applied in the
function in the society by taking performance as a foundation for development of the database
responsibility in their quest to know continuing professional development. application.
more about the world through lifelong
learning.

7. High Level of Leadership and Function effectively as a member or Perform the role of a leader and
Organizational Skills leader of a development team organize the team so that each member
Graduates are developed to become the recognizing the different roles within a will be able to maximize his full
best professionals in their respective team to accomplish a common goal. potential
disciplines by manifesting the
appropriate skills and leaderships
qualities.

8. Sense of Personal and Professional Understand professional, ethical, legal, Design database applications which will
Ethics security and social issues and be useful or beneficial to the well-being of
Graduates show desirable attitudes and responsibilities in the utilization of the stakeholders
behavior either in their personal and information technology.
professional circumstances.

9. Sense of National and Global Analyze the local and global impact of Design database applications which will
Responsiveness computing information technology on be useful or beneficial to the broader
Graduates’ deep sense of national individuals, organizations, and society. segment of the community
compliments the need to live in a global
village where one’s culture and other
people culture are respected.

Page | 6
Course Plan

Week Topic Learning Outcomes Methodology Resources Assessment*

Week Introduction to the Course a. Demonstrate an Orientation University Quick recitation


1 Introductions (Faculty and understanding of what the Self- Student using online
Students) subject is all about, what Introduction Handbook application to
Discussion of Course will be in scope for the (On-line) get students’
Syllabus including Grading semester, and what College understanding
System and General rules students are expected to Manual of what has
Classroom Management learn
been discussed
b. Communicate with fellow Course
students and teacher and Syllabus
begin to establish rapport
c. Identify and explain the Online
course assessment and application
validation criteria ,
including grading system
to understand how to pass
the subject
d. Explain what are the do’s
and don’ts while the class
is on-going
Week Introduction to Database a. Explain what the Online Class Slide Online quiz
1 Administration responsibilities of a Discussion Presentatio
Data Administration database administrator are Reading n
DBA Role b. Describe the impact of poor Assignment
Data Security, Data database administration Online games Online
Availability, Data Quality c. Define how a DBA ensures application
the availability, security, Video
and quality of a database Presentation

Week Structured Query Language a. Create program codes using Online Class Slide Submission of
2-4 - Classifications of SQL basic SQL structure using Discussion Presentatio part of project
Commands single table Reading n requirement of
- Command Syntax of b. Create program codes using Assignment SQL programs
SQL Commands other DML, DDL Online games Online
- Column and Scalar commands application
Functions c. Explain when and what
aggregate functions to use
d. Identify appropriate scalar
function to use to simplify
a program requirement
e. Test program codes to
ensure they meet the
requirements

Week Application of Integrity a. Explain the use and Class Slide Submission of
5 Constraints importance of integrity Discussion Presentatio part of project
constraints Demonstratio n requirement of
b. Determine how to enforce n SQL programs
integrity constraints in Online Online (on integrity
program codes exercises application constraints)
c. Create tables following the
rules of integrity
constraints

Page | 7
d. Ensure that table design is
optimal i.e. proper data
type/size is assigned to
fields
e. Create program codes
which show how data
manipulation is cascaded
on the basis of referential
integrity constraints

Week Multiple Table Processing a. Create complex program Class Slide Submission of
6-8 INNER/OUTER JOIN codes using specific Discussion Presentatio part of project
UNION/INTERSECT/EXCE commands for multiple Online games n requirement of
PT table processing SQL programs
b. Specifically use JOIN as Online (multiple table
join predicate and application processing)
differentiate it from
WHERE as a join predicate
c. Process multiple tables
using
UNION/INTERSECT/EXCE
PT
d. Test program codes to
ensure they meet the
requirements

Week MIDTERM Online Midterm


9 Examination

Week Subquery a. Analyze problems to Class Slide Submission of


10 determine when to use a Discussion Presentatio part of project
subquery Laboratory* n requirement of
b. Create program codes for Online SQL programs
problems requiring exercises Online (subquery)
subquery application
c. Test program codes to
ensure they meet the
requirements

Week Transactions a. Explain the theories Class Slide Submission of


11-12 Stored Procedures surrounding transactions Discussion Presentatio part of project
VIEWS b. Demonstrate when to use Laboratory* n requirement of
Stored Procedures and Online SQL programs
what are its advantages exercises Online (stored
c. Analyze when to use application procedures/view
VIEWS and what are its Online games
s)
advantages
d. Create program codes for
problems requiring views
and stored procedures
e. Test program codes to
ensure they meet the
requirements

Week Triggers a. Determine when to use Class Slide Submission of


13 Error Handling triggers Discussion Presentatio part of project
b. Explain the parts of the Laboratory* n requirement of
program with triggers SQL programs

Page | 8
c. Discuss concepts that are Online Online (triggers/error
used with triggers exercises application handling)
d. Differentiate the two types
of triggers. Computer
e. Code, test, and debug
programs with triggers DBMS-
f. Explain the function of SQL
error handling routines

Week Importing and Exporting a. Execute data import from Class Slide
14 Data excel or a text file into a Discussion Presentatio
From / Into Excel / Text database Laboratory* n
Files b. Execute data export from a Online
Data Transfers between database into an excel or a exercises Online
Tables text file application
c. Explore the different ways
of moving data from and Computer
into the database using
different data storage types DBMS-
SQL

Week Database Back-up a. Enumerate the different Class Slide Online quiz
15-16 Database Concurrency causes why database may Discussion Presentatio
be damaged and records Laboratory* n
may be lost Online games
b. Differentiate a cold back- Online
up from a hot back-up Video application
c. Explain the different means Presentation
by which database may be Computer
recovered
d. Explain the concepts of DBMS-
database concurrency SQL
e. Discuss the impact of
having no concurrency
issues.
f. Differentiate pessimistic
and optimistic approaches
to concurrency control.
Week Project Presentation Project
16-17 Documentation

Database
Implementation

Project
Presentation

18 FINAL EXAMINATION Online Final


Examination

*May not apply with a different teaching modality (i.e. distance learning)

Suggested Readings and References

REFERENCES

1. Modern Database Management by J.A. Hoffer, Ramesh Topi , 13th ed, 2019.
2. Fundamentals of Database Systems, Ramez Elmasri and Shamkant B. Navathe, 7th Ed, 2017
3. Database Systems: Design, Implementation, and Management, Coronel, Carlos & Morris, Steven, 11th Ed,
2017

Page | 9
4. Introduction to Database Management Systems, 3G e-Learning FZ LLC,2015
5. Database Systems: A Practical Approach to Design, Implementation, and Management, Connolly, Thomas M.
Begg, Carolyn, 6th Ed, 2015
6. SQL Tutorial (https://www.w3schools.com/sql/)
7. DB2 SQL Workshop Guide, 2002 and other DBMS Guides

Note: Extended readings may be assigned by the professor.

Software/Program Developed Rubrics


CRITERIA EXCELLENT GOOD SATISFACTORY POOR FAILED
96-100 86-95 76-85 60-75 Below 60
Program Appropriate SQL Program runs Program runs Some parts of the Program does not
Efficiency (.30) codes are used for without errors. without errors. code does not run
efficiency and Few program More program run. Program not
program runs lines not coded lines not coded coded optimally
without errors optimally optimally
Requirements Software Software Software produces Software Software
Specification produces correct produces correct correct results but produces produces
Satisfaction results and results and and display them incorrect results; incorrect results;
(.30) displays them displays them accurately; Software meets Software does
accurately; accurately; Software meets few of the input not meet input
software meets Software meets SOME of the and output and output
ALL the input MOST of the input and output specifications specifications
and output input and output specifications
specifications specifications
Complexity and Application used Application used Application used Application used Application used
Scope* (.20) the right number the right number less than required less than less than
of required of required number of tables; required number required number
tables; tables; Processing of tables; of tables;
Processing Processing specification Processing Processing
specification specification complex specification specification easy
complex moderate moderate

Database - All tables - All tables - All tables - Few tables - Most tables
Design (.20) normalized normalized normalized incorrectly incorrectly
- All - All - Some normalized normalized
relational relational relational - Some - Some
keys correct keys correct keys relational relational
- All data - Some errors incorrect keys keys
domain or missing - Some errors incorrect incorrect
complete in data or missing in - Some errors - Some errors
and correct domain data domain or missing or missing
in data in data
domain domain
*Processing involves use of more advanced SQL commands, views, stored procedures, subquery

Course Grading System

COURSE ASSESSMENT& EVALUATION CRITERIA (GRADING & REQUIREMENTS)

Assignments / Quizzes / Exercises

Major Requirements

• Midterm and Final Exam


• Database Application project in collaboration with Advance Programming

Page | 10
GRADING SYSTEM: *

FIRST GRADING = Class Standing (70%): Quizzes, Assignment, Exercises, Project Activities; Midterm
Examination (30%)

SECOND GRADING = Class Standing (70%): Quizzes, Assignment, Exercises, Project Activities ; Final Examination
(30%)

FINAL GRADE = (FIRST GRADING + SECOND GRADING) / 2

*May not apply with a different teaching modality (i.e. distance learning)

Classroom Policy

Aside from what is prescribed in the student handbook, the following are the professor’s additional house rules:

1. The course is expected to have a minimum of four (4) quizzes.


2. Assignments and research projects/report works will be given throughout the semester. Such requirements shall be
due as announced in class. Late submission shall be penalized with grade deductions (5% per day) or shall no longer
be accepted, depending on the subject facilitator’s discretion. Assignments and exercises are designed to assist you
in understanding the materials presented in class, and to prepare you for the exams.
3. Students are required to attend classes regularly, including possible make-up classes. The student will be held liable
for all topics covered and assignments made during his/her absence. The university guidelines on attendance and
tardiness will be implemented.
4. Any evidence of copying or cheating during any examinations may result in a failing grade from the examination for
all parties involved. Note that other university guidelines shall be used in dealing with this matter.
5. Students are advised to keep graded work until the semester has ended.
6. Contents of the syllabus are subject to modification with notification.
7. Cell phones, radios or other listening devices are not allowed to be used inside lecture and laboratory rooms to
prevent any distractive interruption of the class activity. *
8. No foods, drinks, cigarettes nor children are allowed inside the lecture and laboratory rooms. *
9. Withdrawal and dropping from the subject should be done in accordance with existing university policies and
guidelines regarding the matter.

*May not apply with a different teaching modality (i.e. distance learning, non F2F mode)

Consultation Time

Page | 11
Prepared by: Reviewed by:

Asst. Prof. Monina D. Barretto,MBA Asst. Prof. Melvin C. Roxas, MSGITS

Faculty Member from the Main Campus Department/Academic Program Head

Recommending Approval:

Prof. Gisela May A. Albano, DEM

Dean/Branch or Satellite Campuses Director

Approved by:

Prof. Emmanuel C. De Guzman, Ph.D

Vice President for Academic Affairs/ Vice


President for Branches and Satellite Campuses

Page | 12
INTRODUCTION TO DATABASE ADMINISTRATION

OVERVIEW
This module discusses what the importance of a database administrator is to an organization. It
explains the responsibilities of the DBA and highlights the key aspects of database handling.

LEARNING OUTCOMES
After successful completion of this module, the students are expected to:
1. Explain what the responsibilities of a database administrator are
2. Describe the impact of poor database administration
3. Define how a DBA ensures the availability, security, and quality of a database

COURSE MATERIALS
Core roles of the Database Administrator:
1. Analyzing and designing the database – includes logical / physical data modelling and
the creation of data dictionary
2. Selecting DBMS and related software tools- requires evaluating vendors and their
software products
3. Installing and upgrading the DBMS
4. Tuning database performance – periodic rebuilding, reorganizing and re-indexing of
DB
5. Improving DB query processing performance
6. Managing data security, privacy, and integrity
7. Performing data backup and recovery

Ineffective data administration leads to the following:


1. Multiple definition of same data entity and /or inconsistent representations of the same
data elements in databases
2. Missing key data elements whose loss eliminates the value of existing data
3. Low data quality levels due to inappropriate sources of data or timing of data transfers
from one system to another
4. Inadequate familiarity with existing data, including awareness of data location
5. Poor and inconsistent query response time, excessive database downtime

Page | 13
6. Either stringent or inadequate controls to ensure agreed upon data privacy and
security
7. Lack of access to data due to damaged, sabotaged, or stolen files or due to hardware
failures
8. Embarrassment to the organization because of unauthorized access of data
For a Database Administrator to be effective in his role of managing the database, he should
have a good understanding of the main tool which is used to communicate with the database
management system which is the Structured Query Language (SQL), the standard language
for relational databases.
The role of a Database Administrator can be summarized into three important aspects of
database handling.
In terms of database:
▪ Security
▪ Availability
▪ Quality

Watch

How to get into Database Administration


https://www.youtube.com/watch?v=-OpXfYO_2cQ

Read

Chapter 11: Data and Database Administration, Modern Database Management by Hoffer,
Ramesh, and Topi

ASSESSMENTS:

Answer the following questions:


1. How does a database administrator ensure database quality?
2. Why must a database administrator have a good knowledge of SQL?
3. Give an example of multiple definition of same data entity in the database
4. In your own words, explain how a database administrator can prevent excessive database
downtime.
5. Each of the results of ineffective data administration above can be classified in any of the
three most important aspects of database handling, security, availability, and quality. Identify
to which aspect each result can be classified. For example, #8 ‘Embarrassment to the
organization because of unauthorized access of data’ would fall under security aspect.
ACTIVITY (Optional):
Interview a DBA. From the interview list down the work that he does which relates to keeping
the database secure and available at all times.

Page | 14
STRUCTURED QUERY LANGUAGE (SQL)

SQL is the standard language for creating and querying relational


databases
OVERVIEW
This module serves as a review to basic SQL and introduces the student to the other
classifications of SQL commands. It provides the syntax and examples for commands under
each classification of SQL.

LEARNING OUTCOMES

After successful completion of this module, the students are expected to be able to:
1. Create program codes using basic SQL structure using single table
2. Create program codes using other DML, DDL commands
3. Explain when and what aggregate functions to use
4. Identify appropriate scalar function to use to simplify a program requirement
5. Test program codes to ensure they meet the requirements

COURSE MATERIALS
(*To be able ro run SQL codes, see appendix for the UI and editor of MysQL)
Classification of SQL commands:
1. Data Manipulation Language (DML) – core commands of SQL used for updating,
inserting, modifying, and querying the data in the database
2. Data Definition Language (DDL) – used to create, alter, and drop tables/database
3. Data Control Language (DCL) – used to grant or revoke privileges to access the
database or particular objects within the database; used to store or remove
transactions that would affect the database

DDL (Data Definition Language) Commands


1. CREATE TABLE - defines a new table and its columns / database
2. ALTER TABLE – adds new columns to an existing table or alters existing columns;
also used to add or drop table constraints
3. DROP TABLE - removes a table from a database
DML (Data Manipulation Language) Commands
1. SELECT – allows users to query the data contained in the tables based on given
qualifications
2. UPDATE – makes modification on data in the table

Page | 15
3. INSERT – adds new records to the table
4. DELETE – removes records from the table

DCL (Data Control Language) Commands


1. GRANT - allows specified users to perform specified tasks.
2. REVOKE - cancels previously granted or denied permissions

SQL Command Syntax


Notations on syntax of SQL commands
1. Capitalized words denote the command syntax
2. Lowercase words denote values that must be supplied by user
3. Square brackets enclose optional syntax
4. Ellipses (…) indicate the accompanying clause may be repeated as
necessary
5. Each SQL command ends with a semicolon (optional, depending on
RDBMS)

DDL (Data Definition Language) Command Syntax


1. CREATE TABLE
Syntax:
CREATE TABLE [database_name] table_name
( <column_definition> [ ,...n ] )
[CONSTRAINT constraint_name] [ ; ]
Examples:
CREATE TABLE customer_t
(cust_id INTEGER NOT NULL,
cust_name VARCHAR(25) NOT NULL,
cust_address VARCHAR(30),
city VARCHAR(20),
state VARCHAR(2),
postal_code VARCHAR(9),
CONSTRAINT customer_pk PRIMARY KEY (cust_id));

Page | 16
CREATE TABLE customer_t
(cust_id INTEGER PRIMARY KEY,
cust_name VARCHAR(25) NOT NULL,
cust_address VARCHAR(30),
gender CHAR,
city VARCHAR(20),
state VARCHAR(2),
postal_code VARCHAR(9));

2. ALTER TABLE

Syntax

ALTER TABLE tablename


Alter-table-action

Examples:
ALTER TABLE customer_t
ADD cust_type VARCHAR(2) → add another attribute to
the table

ALTER TABLE customer_t


ADD CONSTRAINT pk_cust PRIMARY KEY (cust_id) → add primary key
Constraint

ALTER TABLE customer_t


ALTER COLUMN cust_type VARCHAR(10) → change data type/size of an
attribute (SQL Server)

ALTER TABLE customer_t


MODIFY cust_type VARCHAR(10) → change data type/size of an
attribute (MySQL)

ALTER TABLE customer_t


ADD CONSTRAINT def_customer_t_city → add default constraint to a
DEFAULT ‘Mnl’ FOR city column (SQL Server)

ALTER TABLE customer_t → add default constraint to a


ALTER COLUMN City SET DEFAULT 'Mnl'; column (MySQL)

Page | 17
3. DROP TABLE
Syntax
DROP TABLE table_name
Example
DROP TABLE customer_t

DML (Data Manipulation Language) Command Syntax


1. UPDATE
Syntax :
UPDATE tablename
SET attribute_name = constant value or another attribute;
Example:
UPDATE customer_t
SET state = ‘NY’ WHERE city = ‘New York’;

2. DELETE
Syntax :
DELETE FROM tablename
Examples:
DELETE FROM customer_t → deletes all records

DELETE FROM customer_t → deletes record if cust_id is 1


WHERE cust_id = 1

3. INSERT
Syntax :
INSERT INTO tablename VALUES (constant values
separated by commas)
Example:
INSERT INTO customer_t VALUES

Page | 18
(1,’Kenra’, ’F’, ‘52nd St. Lexington Ave.’ , ’New York’, ’NY’,123),
(2, ‘Mischka’, ‘F’, ’743 West Irving Road’, ‘Chicago’, ’IL’,321);

4. SELECT
Syntax: The SELECT clauses should be in the following order,
SELECT,
FROM, WHERE, GROUP BY, HAVING, ORDER BY although not all
clauses
may not necessarily be needed in a requirement.
SELECT column, […n],
[literals],
[arithmetic expression],
[scalar or column functions]
FROM <tables or views>
WHERE <condition for row selection>
GROUP BY <column, […n]> → divides the query result into groups
HAVING condition for group selection → filter groups
ORDER BY column, […n] → sort keys

Examples:
SELECT * → displays all attributes of all
FROM customer_t records from customer_t

SELECT cust_id, cust_name, cust_address → displays specific


FROM customer_t columns if cust_id is 1
WHERE cust_id = 1

*For MySQL, you cannot DELETE nor UPDATE without a WHERE clause if you are in the
safe mode. Go to Edit / Preferences / SQL Editor to click/unclick Safe Updates and then
reconnect.

Page | 19
SQL Functions
1. COLUMN FUNCTIONS - produce a summary row for a set of rows
2. SCALAR FUNCTIONS - returns a value for a row based on input argument

Most common COLUMN Functions


1. SUM() - computes total
2. AVG() - computes average
3. MIN() - finds minimum value
4. MAX() - finds maximum value
5. COUNT(*) - determines the total number of rows

Syntax:
SELECT SUM(column name)
FROM table name;
SELECT AVG(column name)
FROM table name;
SELECT MIN(column name)
FROM table name;
SELECT MAX(column name)
FROM table name;
SELECT COUNT(*)
FROM table name;
Examples:
SELECT SUM(quantity)
FROM product_t;
SELECT AVG(price)
FROM product_t;
SELECT COUNT(*)
FROM product_t;

SCALAR Functions
See the full list of scalar function in the following links:
https://dev.mysql.com/doc/refman/8.0/en/functions.html (MySQL)
https://docs.microsoft.com/en-us/sql/t-sql/functions/functions?view=sql-server-ver15
(SQL Server)

Examples of more commonly used scalar function in table below.

Page | 20
Other Examples:
SELECT DATEDIFF(‘mm’, birthdate ,GETDATE()) → returns difference in
FROM student_t; months between 2 dates
(SQL Server)
SELECT SUBSTR(‘God loves you’,5,4) → Extracts 4 characters starting
in position 5;output is ‘love’
(MySQL)

GROUP BY (Clause in SELECT)


The GROUP BY clause tells which rows in a table are to be grouped together. It divides a
table into subsets (by groups).
With GROUP BY, a column function results in a single value for each group. There could be
more than 1 attribute in a GROUP BY, e.g. GROUP BY division, job. This means, the records
will be processed first by division then by job.

Page | 21
Test Data to be used in GROUP BY examples : Employee_T table

Example 1: Get the average salary of each division


This means that each division would have each own average salary. To be able to do that, we
have to group the records by division and compute for the average by division
Output:
SELECT division, AVG(Salary) as [Average Division Average Salary
Salary]
ISD 6000
FROM EMP
FIN 4750
GROUP BY division
HR 3000

Example 2: Display the total salary per job level


Total salary for each job level is needed. Aggregate the salary per job level
Output:
SELECT job, SUM(Salary) as [Total Salary] Job Total Salary
FROM EMP MGR 7000
GROUP BY job RF 3500

SMR 17000

Page | 22
Important Reminder:

If a SELECT clause has a COLUMN function and fields not in COLUMN


function, all fields not in COLUMN function must be included in GROUP
BY clause

GROUP BY with HAVING (Clause in SELECT)


The HAVING clause is a search condition for a group or an aggregate. This is typically used
with the GROUP BY clause.
The HAVING clause tells which groups of information are to be processed based upon a
group qualification criteria rather than rows.

Example 1: Display the average salary of divisions if the average salary is greater than 6,000.
SELECT division, AVG(Salary) AS [Average Salary] Output:
FROM EMP Division Average Salary
GROUP BY division ISD 6000
HAVING AVG(Salary) > 5000

Example 2: Display the total salary per job level if the total salary is less than 10,000.
SELECT job, SUM(Salary) AS [Total Salary] Output:
FROM EMP Job Total Salary
GROUP BY job MGR 7000
HAVING SUM(Salary) < 10000 RF 3500

USING BOOLEAN OPERATORS WITH SELECT CLAUSE


AND – joins 2 or more conditions only when all conditions are true
OR – joins 2 or more conditions when any conditions are true
NOT – negates an expression
If multiple boolean operators are used in an SQL statement, NOT is evaluated first, then
AND, then OR.

Page | 23
Example 1:
SELECT *
FROM customer_t
WHERE gender = ‘F’ AND state = ‘NY’ or state = ‘IL’ or state = ‘NJ’

In this example, all female residents of New York (NY) will be selected including
all residents of Illinois (IL) and New Jersey (NJ). Conditions joined by an AND
will be evaluated first and then those joined by the OR operator

Example 2:
SELECT *
FROM customer_t
WHERE gender = ‘F’ AND (state = ‘NY’ or state = ‘IL’ or state =
‘NJ’)

In this example, all female residents of New York (NY) , Illinois (IL,) and New
Jersey (NJ) will be processed. Conditions inside the parenthesis are prioritized so
the checking of the state is processed first and the output will be ANDed with
the condition on gender.

Note : You cannot use a column function in a WHERE clause. Below code is wrong:
SELECT SUM(Quantity)
FROM Product
WHERE SUM(Quantity) > 0

Guidelines in Creating Data Names


1. Relate to Business, not technical
2. Be meaningful – almost to the point of being self-documenting
3. Be unique
4. Be repeatable
5. Follow a standard syntax

Page | 24
Watch
https://www.youtube.com/watch?v=27axs9dO7AE
Read
Chapter 6, Introduction to SQL
Chapter 7, Advanced SQL
Modern Database Management by Hoffer, Ramesh, Topi

ASSESSMENTS

True or False
1. A column function can be used in a WHERE clause
2. The HAVING and WHERE clauses can be used interchangeably.
3. There should only be 1 attribute in a GROUP BY
4. The clauses in a SELECT statement should be coded in a specific order
5. The use of ‘*’ in a SELECT clause means all attributes from the table will be
displayed as part of the output.
Programming
Use the Employee_T table (from the topic on GROUP BY) for the following problems. Create
SQL programs for the following requirements. Take note of the syntax provided to be able to
create your SQL code.
1. Create a database and name it DB_Employee
2. Create Employee_T table in the database. Provide the appropriate data type/size for each
attribute
3. Alter a property of an attribute in Employee_T. Increase the size of one of
its attributes, any attribute.
4. Add another attribute to Employee_T. The attribute is Date_Hired.
5. Insert 5 records in Employee_T. Provide your own data.
6. List all records from Employee_T sorted by division
7. List only the name of the employees who are managers
8. List the names of the employees who are from ISD and whose salary is > 200
9. List all records of employees who are from ISD or FIN, and whose salary is > 200
10. Update any field of any one record in Employee_T.
11. Update the salary to 1000 of all the managers in the table
12. Count how many employees there are in the table
13. Count how managers are there from the table.
14. Sum the salaries of all in the ISD department.
15. Sum up the salary per division. Show division in the output
16. Sum the the salary per division and display only the total salaries which are greater than 600
17. Display the average salary of the managers.
18. Display the average salary per job level.
19. Display the average salary per job level where the average salary is between 100 to 300
20. Delete records from Employee_t if the salary is less than 100.

Page | 25
ACTIVITIES
1. Create a different table, e.g. Student and practice the same set of questions above using
this table. Identify the attributes that may be part of the table that you will create e.g. for a
Student table, attributes may be student id, student name, birthdate, address, course
2. Research on the other scalar functions and practice programming on how they are used.
Examples of these are LEFT, RIGHT, RTRIM, LTRIM, ROUND, etc…

Page | 26
INTEGRITY CONSTRAINTS

Integrity constraints maintains accuracy and integrity of data in the


database

OVERVIEW

This module discusses how database management systems are set up to ensure validity and
accuracy of data. It shows how data integrity can be enforced from table creation up to data
processing.

LEARNING OUTCOMES

At the end of this module, the students are expected to:


1. Explain the use and importance of integrity constraints
2. Determine how to enforce integrity constraints in program codes
3. Create tables following the rules of integrity constraints
4. Ensure that table design is optimal i.e. proper data type/size is assigned to fields
5. Create program codes which show how data manipulation is cascaded on the basis of
referential integrity constraints

COURSE MATERIALS
Types of Integrity Constraints
1. Entity Integrity - Rule designed to ensure that every relation has a primary key
2. Domain Constraint - A domain definition usually consists of the following:
• Attribute name
• Meaning
• Data type
• Size
• Allowable value or allowable range
3. Referential Integrity - Rule that maintains consistency among the rows of two
relations. The rule states that if there is a foreign key in one relation, either the foreign
key must match a primary key in another relation or foreign key must be null

Page | 27
Cascading Referential Integrity Constraints
Tables to be used in the examples

Page | 28
Page | 29
Page | 30
Page | 31
In this example above, the cust_id should have been defined with a default
value when the table was created.
*On Update / Delete Set Default are not supported in MySQL

Page | 32
Read

Chapter 4, Logical Database Design and the Relational Model,


Modern Database Management 11th Ed. by Hoffer, Ramesh, and Topi

ASSESSMENTS / ACTIVITIES

1. Create table Employee using below attributes with the data type/sizes provided
Employee Number INT, must not be null
Employee Name Variable Character : Size (20) must not be null
Salary Number: Size (10,2) must not be null
Job Level Character : Size (3)
Dept code Character : Size (2)
2. Create table Department using below attributes with the data type/sizes provided.
Dept code Character : Size (2) must not be null
Dept Name Variable Character : Size (20) must not be null
Dept Mgr Variable Character : Size (30)
2.1 The constraint in Department table should be that every time a dept code is
deleted In Department table, corresponding record with same department is
likewise deleted in Employee table.
2.2 Populate Employee and Department tables
2.2.1 Take note that dept code that you will use in Employee table must be dept
code which are in the Department table
2.2.2 Delete 1 record in the Department table. Take note of what happened in
Employee table
2.3 Revise constraint in Department table so that if a dept code is updated in
Department table, it is likewise updated in Employee table.
2.3.1 Update the value of a department code. For example, say one of the
department codes is ‘EDU’, update it to ‘EDT. Take note of what happened for

Page | 33
corresoponding records in Employee table.
2.4 Revise constraint in Department table so that if a dept code is updated in
Department table, it is is updated to null in Employee table.
2.4.1 Update the value of a department code. For example, say one of the
department codes is ‘EDU’, update it to ‘EDT. Take note of what happened to
the corresponding records in Employee table.

Page | 34
WORKING WITH MULTIPLE TABLES

OVERVIEW

This module introduces the different commands which will allow multiple table processing. It
familiarizes the students with how these commands are used in different scenarios.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Create complex program codes using specific commands for multiple table processing
2. Specifically use JOIN as join predicate and differentiate it from WHERE as a join predicate
3. Process multiple tables using UNION/INTERSECT/EXCEPT
4. Test program codes to ensure they meet the requirements

COURSE MATERIALS

WHERE clause as join predicate

Tables to be used in examples


Employee table Department table

Tables should be joined by a common attribute. In the tables above, the common attribute is
the department id, deptId. Where the deptId is equal for both tables, then the records can be
joined.
Example :
List the employee name, and the name of the department where he belongs. Take note that
the employee name (empName) is in the Employee table while the department name
(deptName) is in the Department table so we will get the 2 attributes from 2 different tables.

Page | 35
SELECT empName, deptName
FROM Employee, Department
WHERE Employee.deptId = Department.deptId → join predicate
*deptID which exists in both tables is qualified by the table names,
Employee and Department, Employee.deptID and Department.deptID

Other ways to write the SQL statement are


SELECT empname, deptname
FROM Employee AS E, Department AS D → use alias for the tables
WHERE E.deptid = D.deptid; → use the alias as the
qualifier

SELECT empname, deptname


FROM Employee , Department
WHERE deptid = workdept; → if department ID has different
names in the 2 tables, deptID in
one table and workdept in the
other

Output:

empName deptName

Customer
Stephen Service

Tony Research

Kevin Research

The deptId of Stephen is 102 which is found in Department table with ‘Customer
Service’ as the corresponding name. The deptID of Tony and Kevin is 101 which
is found in the Department table with department name as ‘Research’

Page | 36
Use of JOIN to combine data from multiple tables

1. Inner Join – displays only the rows that have a match in joined tables
2. Outer Join – returns rows of tables with or without a match
3. Cross Join – produces cartesian product of tables involved in the join;
unconditionally matches all rows of one table with the other table; the
number of rows will be the product of the number of rows of all tables
involved.

INNER JOIN (JOIN …ON)


 The JOIN…ON syntax can be also be used to perform a join.
SELECT empname, deptname
FROM Employee AS E, Department AS D
WHERE E.deptid = D.deptid;
Is the same as

SELECT empname, deptname


FROM Employee E INNER JOIN Department D → ‘INNER’ may be
ON E.deptid = D.deptid dropped

*JOIN..ON has the advantage of moving the JOIN syntax into the FROM clause

GENERAL RULE
The number of tables minus one (n-1) is USUALLY the LEAST
number of join predicates needed for the query, to ensure that
there are no un-linked tables

OUTER JOIN
 The OUTER JOIN syntax can be used to obtain data that exists in one table without
matching data in the other table.

Page | 37
LEFT, RIGHT, FULL OUTER JOIN
 SQL Standard considers the first table you name as the one on the "left", and the
second table as the one on the "right."
 So, if you want all the rows from the first table and any matching rows from the second
table, you'll use a LEFT OUTER JOIN.
 Conversely, if you want all the rows from the second table and any matching rows from
the first table, you'll specify a RIGHT OUTER JOIN.*
 FULL OUTER JOIN combines the results of both left and right outer joins and returns all
(matched or unmatched) rows from the tables on both sides of the join clause**
(Full Join is not supported in MySQL)

Example 1 (LEFT JOIN): List all employee names with the department even if no department
has been assigned yet.
SELECT empname, deptname
FROM Employee E LEFT JOIN Department D
ON E.deptid = D.deptid;

Example 2 (RIGHT JOIN) : List down the employees and department even if department has
no assigned employees yet

SELECT empname, deptname


FROM Employee E RIGHT JOIN Department D
ON E.deptid = D.deptid;

Page | 38
Example 3 (FULL JOIN) : List all employees, departments from both tables (including
unmatched records).
SELECT empname, deptname
FROM Employee E FULL JOIN Department D
ON E.deptid = D.deptid;

*http://searchsqlserver.techtarget.com/feature/How-to-use-the-LEFT-vs-RIGHT-OUTER-JOIN-in-SQL

** www.w3resource.com › sql › joins › perform-a-full-outer-join

Union / Intersect / Except


Union
Combines the results of two or more queries into a single result set that includes all the rows
that belong to all queries in the union.
The UNION operation is different from using joins that combine columns from two tables.
The following are basic rules for combining the result sets of two queries by using UNION:
• The number and the order of the columns must be the same in all queries.
• The data types must be compatible.
The UNION operator selects only distinct values by default. To allow duplicate values, use the
ALL keyword with UNION.

Page | 39
Syntax:
Query
{UNION| UNION ALL}
Query

Page | 40
INTERSECT
INTERSECT returns distinct rows that are output by both the left and right input queries
operator.

Basic Rules
• The number and the order of the columns must be the same in all queries.
• The data types must be compatible.
Syntax:
Query
INTERSECT
Query

EXCEPT
EXCEPT returns distinct rows from the left input query that aren’t output by the right input query
Basic Rules
• The number and the order of the columns must be the same in all queries.
• The data types must be compatible.
Syntax:

Page | 41
Query
EXCEPT
Query

INTERSECT and EXCEPT are not supported in MySQL. Depending on the problem, you
may use the IN operator (in a subquery) to simulate INTERSECT or the NOT IN to simulate
EXCEPT.
Example: The equivalent of the example above on INTERSECT using the IN operator is
SELECT name FROM tbl3
WHERE name IN (SELECT name FROM tbl4)

Example: Use of NOT IN in place of EXCEPT


SELECT name FROM tbl3
WHERE name NOT IN (SELECT name FROM tbl4)
(the answers here should be Maine, Jacky, and Nats)

Watch

Check the playlist from this tutorial on multiple tables processing


https://www.youtube.com/playlist?list=PL08903FB7ACA1C2FB

Page | 42
Read

Chapter 7, Advance SQL


Modern Database Management 11th Ed., by Hoffer, Ramesh, Topi
https://www.w3schools.com/sql/

ASSESSMENTS

Answer the following questions:


1. What are the rules that must be satisfied in order to perform a union,
intersect, and except?
2. What type of Join must be used if we want to display only all matching
records from 2 tables
3. How many records will a cross join output if 1 table has 5 records while the second
table has 6 records?
4. When do you use an inner join over an outer join?
5. What is the difference between a left join and a right join?

ACTIVITIES
Use the 2 tables below
EMPLOYEE(EmpNo, EName, JobLevel, DateHired, EmpAddress) → Employee Master File
EMPEVALUATION(EmpNo, Rating, RatingPeriod) → Table of all over-all ratings of employee
for all rating periods
Use join, intersect, union, or except for the following problems:
1.Display the employee number, name, and his ratings for the different rating periods.
2. Display the employee number, name, and address of employees who got 90 and above
in any of the rating periods.
3. Display the employee number, name, and address of employees who got between 70-75
during ‘FY2018’ rating period.
4. Create two solutions/programs for this problem. For the first, use Intersect, for the second,
use Join.
Display only the employee number of those who were hired
after 12/31/2018 whose rating is 90 and above for rating period ‘FY2019’
5. Display all employee numbers who did not get a rating of 90 in any of the rating periods.

Page | 43
SUBQUERY

Subquery is a query nested inside another query.

OVERVIEW

A subquery is a query within a query. Subquery technique involves placing an inner query
which provides a set of one or more values for the search condition of the outer query.
Subquery provides an option for multiple table processing.

LEARNING OUTCOMES

At the end of this module, the student is expected to


1. Analyze problems to determine when to use a subquery
2. Create program codes for problems requiring subquery
3. Test program codes to ensure they meet the requirements

COURSE MATERIALS
Uses of subquery
A Subquery can be used with
• SELECT
• INSERT
• UPDATE
• DELETE
SELECT with Subquery
Example: Generate a list of employees who have the lowest salary.
Without a subquery, output will be generated using 2 SELECT statements
SELECT MIN(SALARY)
FROM EMP_T
Output : 1500

SELECT EMP_LNAME, SALARY


FROM EMP_T
WHERE SALARY = 1500

Page | 44
Using a subquery same problem could be solved using a single SELECT statement with a
subquery
Example : Generate a list of employees who have the lowest salary
SELECT EMP_LNAME, SALARY
FROM EMP_T
WHERE SALARY = (SELECT MIN(SALARY) FROM EMP_T)

SELECT MIN(SALARY) FROM EMP_T is the inner query or the subquery and it is evaluated
first. The answer of which is passed to the outer query
Example : Generate a list of employees whose salaries are lower than the average salary
SELECT *
FROM EMP_T
WHERE SALARY < (SELECT AVG(SALARY) FROM
EMP_T)

Update with Subquery


Example : Update the Remarks attribute for all employees to ‘For adjustment’ if their salary is
less than the average salary
UPDATE Emp_T
SET Remarks = ‘For adjustment’
WHERE Salary < (SELECT AVG(Salary)FROM Emp_T);

Delete with Subquery


Example: Delete the record of a rank and file employee from Bonus file if employee is receiving
a salary equal to or greater than the minimum salary of a manager.
DELETE FROM Bonus
WHERE JobLevel = ‘RF’ AND
Salary >= (SELECT MIN(Salary)
FROM Bonus
WHERE JobLevel = ‘MGR’ );

Page | 45
Insert with Subquery
• Write your INSERT statement with a subquery.
• Do not use VALUES clause.
• Match the number of columns in the INSERT clause to those in the subquery.

Syntax 1: (Select specific columns to be copied from source to destination tables)


INSERT INTO destinationTable (column1, column2, ...,
columnN)
SELECT column1, column2, ..., columnN
FROM sourceTable
[WHERE (condition)]
Example 1:
INSERT INTO Faculty_T (EmpNo, EmpName, HireDate,
PayGrade)
SELECT EmpNo, Emp_Name, Hire_Date, Pay_Grade
FROM Employee_T
WHERE Emp_Code = ‘FA’;

Syntax 2: (Destination and source tables have exactly the same domain and all
attributes from source is copied into destination table)
INSERT INTO destinationTable
SELECT *
FROM sourceTable
[WHERE (condition)]
Example :
INSERT INTO Faculty_T
SELECT *
FROM EMPLOYEE_T
WHERE Emp_Code = ‘FA’;

Page | 46
Read

Chapter 7, Advance SQL, Modern Database Management, 11th Ed.


By Hoffer, Ramesh, Topi

ASSESSMENTS/ACTIVITIES

Use the table below and create a program for the following problems:
EMPLOYEE(EmpNo, Sname, JobLevel, Status, DateHired, Salary, EmpAddress).
(Please create the table and populate it for your test data for these exercises.
Joblevel values could be MGR-manager, RF-Rank and file, S-Supervisor
Status values could be R- regular, P-probationary, C-contractual)
1. List the records of employees whose salary is the same as employee whose
empno is ‘11111’
2. List the names of employees whose salary is greater than the minimum
salary
3. List the names of the employees who have the highest salaries
4. Create another table called Regular_Emp, with the same attributes except for status
REGULAR_EMP(EmpNo, Sname, JobLevel, DateHired, Salary, EmpAddress
4.1 Copy all records from Employee table to Regular_Emp table if the status is =’R’
This will effectively store in Regular_Emp table all records of regular employees
5. List all records of employees whose salary is less than the average salary of all employees

Page | 47
TRANSACTION

A transaction is a sequence of operations performed as a single


logical unit of work.

OVERVIEW

This module provides an insight on how instructions are processed as a logical unit of
work. It discusses the properties of transactions which helps ensure the validity of
data.

LEARNING OUTCOMES

At the end of this module, the student is expected to


1. Describe what transactions are
2. Explain the different properties of a transaction
3. Differentiate the modes of transaction

COURSE MATERIALS
Properties of Transactions
• A logical unit of work must exhibit four (4) properties, called an ACID Test
❑ A - Atomicity
❑ C - Consistency
❑ I - Isolation
❑ D – Durability
❑ A - Atomicity - when two or more pieces of information are involved in a
transaction either all the pieces are committed or none of them are
committed.

Page | 48
In above example, 2 activities were successful, but the third failed. The transaction
quantity of 50 was not added to Customer Qty. With atomicity, the full transaction will not be
saved (meaning results activities 1 and 2 will not be saved too ) in the database. All transactions
activities need to be successful for the transaction to be committed in the database.

❑ C – Consistency - at the end of a transaction, either a new and valid form


of data exists or data is returned to its original state.

❑ I – Isolation - Modifications made by concurrent transactions must be


isolated from the modifications made by any other concurrent transactions.
A transaction either recognizes data in the state it was in before another concurrent transaction
modified it, or it recognizes the data after the second transaction has completed

Serializability
When two or more transactions are processed concurrently, the results in the database should
be logically consistent with the results that would have been achieved had the transactions
been processed in an arbitrary serial fashion

❑ D – Durability - After a transaction is committed, its effects are


permanently in place in the system

TRANSACTION STATEMENTS
• COMMIT - makes all data modifications performed since the start of the transaction a
permanent part of the database; frees the resources held by the transaction
• ROLLBACK - erase all data modifications made from the start of the transaction;
frees the resources held by the transaction
✓ If a transaction is successful, all of the data modifications made during the
transaction are committed and become a permanent part of the database.
✓ If a transaction encounters errors and must be canceled or rolled back, then all of
the data modifications are erased.

MODES OF TRANSACTIONS
1. AUTOCOMMIT
2. EXPLICIT

Page | 49
3. IMPLICIT
AUTOCOMMIT

• Each individual statement is a transaction that is immediately committed.


Example: (the values inserted will be immediately stored into the Movie table)
INSERT INTO Movie(Genre,Title,Price)
VALUES ('Action',‘Lone Ranger',‘100.00')
EXPLICIT

• Each transaction is explicitly started with the BEGIN TRANSACTION (for SQL Server) or
START TRANSACTION (for MySQL) statement and explicitly ended with a COMMIT or
ROLLBACK statement.
Example: (In this example, the COMMIT statement has to be coded before the inserted record
will be saved.)
BEGIN TRANSACTION
INSERT Movie(Genre,Title,Price)
VALUES (‘Suspense’,’Train to Busan’,600)
COMMIT TRANSACTION
*If the transaction should be not be saved, ROLLBACK TRANSACTION should be coded
IMPLICIT (Discussion below on Implicit mode applies only to SQL Server)

• A new transaction is implicitly started when the prior transaction completes, but each
transaction is explicitly completed with a COMMIT or ROLLBACK statement.

• SET IMPLICIT_TRANSACTIONS { ON | OFF }


o When ON, the system is in implicit transaction mode.
o It is equivalent to an unseen BEGIN TRANSACTION being executed first.
o When OFF, we say the transaction mode is autocommit.

Watch
Database Transactions
https://www.youtube.com/watch?v=Y7ulFqYjaT4
https://www.youtube.com/watch?v=PguCDI_fi3U
https://www.youtube.com/watch?v=NHKHzwolbKU
https://www.youtube.com/watch?v=J9VP5CILdP4

Page | 50
Read

Chapter 17, An Introduction to Transaction Processing Concepts and Theory


Fundamentals of Database Systems, 5th Ed by Elmasri & Navathe

ASSESSMENTS / ACTIVITIES

Answer the following questions


1. Explain what a transaction is.
2. Explain atomicity and durability.
3. What is the default mode of transaction?
4. How do you begin an explicit transaction?
5. Discuss serializability in the context of isolation as a property of a transaction.
6. Use the same table and data used in previous activities
EMPLOYEE(EmpNo, Sname, JobLevel, Status, DateHired, Salary, EmpAddress).
6.1 Use explicit transaction mode
6.2 Update any record in the file.
6.3 If you do not COMMIT nor ROLLBACK, what happens?

Page | 51
STORED PROCEDURE

OVERVIEW

This module discusses the use and advantages of stored procedures. It familiarizes the
student with the syntax of stored procedure and illustrates how to create stored procedures.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Explain the parts of a stored procedure
2. Create program codes of stored procedure
3. Demonstrate when to use stored procedures
4. Discuss the advantages of using stored procedure

COURSE MATERIALS
Definitions

• Modules of code that implement application logic and are included on the database
server

• A collection of procedural and SQL statements that are assigned a unique name and
stored in the database

• Accept input parameters and return multiple values in the form of output parameters
to the calling procedure or batch.

Advantages of using stored procedures

• Performance improves for compiled SQL statements

• Network traffic decreases as processing moves from the client to the server

• Security improves if the stored proc rather than the data is accessed and code is
moved to the server, away from direct end-user-access

• Data integrity improves as multiple applications access the same stored proc

• Stored procs result in a thinner client and a fatter database server

• They allow modular programming. You can create the procedure once, and call it
any number of times in your program. This can improve the maintainability of your
application and allow applications to access the database in a uniform manner.

Page | 52
The following discussion on stored procedure will be for SQL Server
Syntax (abbreviated version)
CREATE { PROC | PROCEDURE }
[parameter data type = default] [,…n]
AS
{ [ BEGIN ]
sql_statement [;] [ ...n ]
[ END ] }

Example 1 ( with input parameter): Create a stored procedure which will display all records
from customer_t table based on the input city
CREATE PROCEDURE sproc_custcity
@city varchar(15) = ‘ ’ → input
AS
BEGIN
SELECT *
FROM customer_t
WHERE cust_city = @city
END
To execute sproc_custcity,
EXECUTE sproc_cust ‘London’
‘London’ is the input parameter which is received by @city inside the stored
procedure. This will list all records from customer_t if the city is ‘London’

To change input parameter, run EXECUTE with a different input, e.g.


EXECUTE sproc_cust ‘New York’
This will list all records from customer_t if the city is ‘New York’.

Example 2 (No parameter): Create a stored proc which will display all records from order_t
table if the date of order is 10 years old or older

Page | 53
CREATE PROCEDURE sproc_gettrans
AS
BEGIN
SELECT *
FROM order_t
WHERE DATEDIFF(YEAR,ORDERDTE,GETDATE()) >= 10
END
To execute sproc_gettrans
EXECUTE sproc_gettrans
This will list all records from order_t if the order date has 10 years or more
gap from today’s date

Example 3 (with output parameter): Create a stored procedure which will display the total
purchase from order_t
CREATE PROCEDURE sproc_gettrans
@sumpurch float = 0 output → output parameter
AS
BEGIN
SELECT @sumpurch = sum(purchamt)
FROM order_t
END
To execute sproc_gettrans
DECLARE @sumpurch float
EXECUTE SPROC_gettrans @sumpurch output
SELECT @sumpurch AS ‘Sum of Purchase‘
This will display the total purchase from order_t

Summary
To Create a Stored Procedure in Object Explorer (for SQL Server)
1. In Object Explorer, connect to an instance of Database and then expand that instance.
2. Expand Programmability.

Page | 54
3. Right-click Stored Procedures, and then click New Stored Procedure.
4. In the Query Editor, replace the SELECT statement with the your own SELECT
statement
5. To test the syntax, on the Query menu, click Parse. If an error message is returned,
correct as needed.
6. To create the procedure, from the Query menu, click Execute. The procedure is
created as an object in the database.
7. To see the procedure listed in Object Explorer, right-click Stored Procedures and
select Refresh.
8. To run the procedure,
8.1 in Object Explorer, right-click on the stored procedure and select Execute Stored
Procedure (you can enter values of your parameters in the window which will
appear)
8.2 In a new query editor, type

EXECUTE procedure_name parameters


e.g
EXECUTE sproc_cust ‘London’
End of Stored Procedure discussion for SQL Server

The following discussion on stored procedure will be for MySQL. All of below materials
are found in MySQL Reference Manual. See the given link.
https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html

Syntax (abbreviated):
CREATE PROCEDURE sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body

proc_parameter:
[ IN | OUT | INOUT ] param_name type  optional

routine_body:
Valid SQL routine statement

• An IN parameter passes a value into a procedure. The procedure might modify the
value, but the modification is not visible to the caller when the procedure returns.

Page | 55
• An OUT parameter passes a value from the procedure back to the caller. Its initial value
is NULL within the procedure, and its value is visible to the caller when the procedure
returns.
• An INOUT parameter is initialized by the caller, can be modified by the procedure, and
any change made by the procedure is visible to the caller when the procedure returns.

A CALL statement invokes the stored procedure


For each OUT or INOUT parameter, pass a user-defined variable in the CALL statement.
The delimiter command to change the statement delimiter from ; to // while the procedure is
being defined. This enables the ; delimiter used in the procedure body to be passed through to
the server rather than being interpreted by mysql itself.
Example. This example passes an input parameter name of state and returns the
number of records for the input state.

delimiter //
CREATE PROCEDURE sproc_gettrans (In instate char(2), out recs int)
BEGIN
SELECT count(*) into recs
FROM customer_t where state = instate;
END//

call sproc_gettrans ('ny', @recs);


select @recs

Output:
End of Stored Procedure discussion for MySQL

Watch

Stored Procedures in SQL Server Part 18


https://www.youtube.com/watch?v=Qu3E-oncF3g

Page | 56
Read

Chapter 8, Database Application Development, page 389


Modern Database Management, 11th Ed, Hoffer, Ramesh, Topi
https://msdn.microsoft.com/en-us/library/ms187926.aspx

ASSESSMENTS/ACTIVITIES

Answer the following questions


1. Give one advantage of a stored procedure and explain
2. Where do you think will a stored procedure be most useful?
3. Why does the use of a stored procedure decrease network traffic?
4. Use the same table and data used in previous activities
EMPLOYEE(EmpNo, Sname, JobLevel, Status, DateHired, Salary, EmpAddress).
4.1 Create a stored procedure that will display all records from Employee table given
an input parameter Status. So if the input value is ‘P’, all probationary employees
will be displayed, if the input value is ‘R’, all regular employees’ records will be
displayed, and so on
4.2 Create a stored procedure that will list all records for an employee with a given
hire date
4.3 Create a stored procedure that will list the names of those who are hired for the
current day (no input parameter here, check out a scalar function that can be
used).

Page | 57
VIEWS

Views are virtual tables created from base tables using SQL queries

OVERVIEW

This module defines virtual tables and explains why or when they should be used instead of
physical tables. It instructs the student on how to create views.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Discuss the reasons why views are used
2. Create programs with application of views

COURSE MATERIALS
Purpose

• Simplify queries and improve programmer productivity

• Help provide data security and confidentiality – allows users to access data
through the view, without granting the users permissions to directly access
the underlying base tables

• Provide a customized view for the users


Syntax:
CREATE VIEW view_name [ (column [ ,...n ] ) ]
AS
select_statement ;
Where:
view_name - Is the name of the view
column - Is the name to be used for a column in a view.
If column is not specified, the view columns acquire the same names as the columns in the
SELECT statement. A column name is required when a column is derived from an arithmetic
expression or a function.
AS
Specifies the actions the view is to perform.

Page | 58
select_statement
Is the SELECT statement that defines the view. The statement can use more than one table and
other views.
The SELECT clause in the view definition cannot include an ORDER BY clause, unless there is
also a TOP clause in the select list of the SELECT statement.

Example 1 : Create a view of the customer, with his id, customer name, salesman id and all
corresponding orders (order number, purchase amount, order date) from the Orders table.
CREATE VIEW customer_order_v
AS
SELECT C.customer_id, cust_name, salesman_id, ord_no,
purch_amt , order_date
FROM customer C, orders O
WHERE C.customer_id = O.customer_id
To see content of customer_order_v,
SELECT *
FROM customer_order_v

Example 2 : Create a view of the total purchases per customer.


CREATE VIEW purchase_summary_v (custid, cust_total)
AS

Page | 59
SELECT customer_id, sum(purch_amt)
FROM orders
GROUP BY customer_id

*The attribute names in the purchase_summary_v view will be the ones specified in the
parenthesis, custid and cust_total

Watch
Views in SQL Server, Part 39
https://www.youtube.com/watch?v=VQpmOmZO2mo
Read
https://msdn.microsoft.com/en-us/library/ms187956.aspx

ASSESSMENTS/ACTIVITIES

Answer the following questions


1. State an example where a view simplifies a query
2. Give an example where you can apply the use of a view for security purposes
3. Use the same table and data used in previous activities
EMPLOYEE(EmpNo, Sname, JobLevel, Status, DateHired, Salary, EmpAddress).
Provide your own name for the views to be created
3.1 Create a view that will display only empno, datehired, salary of records from
the Employee table if the employee salary is equal to the highest salary.
3.2 Create a view that will display only empno, datehired, salary of records from
the Employee table if the employee salary is in the highest salary range.
Highest salary range is: highest salary – 5000 to highest salary. For example,
if the highest salary is 20,000. The highest salary range is 15,000 to 20,000.
The lower range was taken by subtracting 5000 from the highest salary.

Page | 60
TRIGGERS

OVERVIEW

This module discusses a special kind of stored procedure which is automatically


triggered/run when certain events occur.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Determine when to use triggers
2. Explain the parts of the program with triggers
3. Discuss concepts that are used with triggers
4. Differentiate the two types of triggers.
5. Code, test, and debug programs with triggers

COURSE MATERIALS
Definition
A trigger is a special kind of stored procedure that automatically executes when an event occurs
in the database server.
An event could be a DML, DDL, or logon event.

Types Of Trigger
DML triggers

• execute when a user tries to modify data through a data manipulation


language (DML) event.
DDL triggers

• execute in response to a variety of data definition language (DDL)


events. These events primarily correspond to CREATE, ALTER, and
DROP statements
The following are syntax and examples for SQL Server
DML Trigger
Syntax 1:
CREATE TRIGGER trigger_name → name of trigger
ON { table | view } → trigger table
{ FOR | AFTER | INSTEAD OF }

Page | 61
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS
{ sql_statement [ ; ] [ ,...n ] } → trigger action

The trigger table or the table view is the table or view on which the DML trigger is executed.
FOR | AFTER
For or AFTER specifies that the DML trigger is fired only when all operations specified in the
triggering event have executed successfully.

INSTEAD OF
Specifies that the DML trigger action is executed instead of the DML operation, therefore,
overriding the actions of the triggering statements.
sql_statement
The trigger actions that go into effect when the operation/event is tried.

Inserted and Deleted Tables


• logical or conceptual tables
• Special tables used by DML trigger statements
• temporary, memory-resident tables automatically created by SQL Server

The ‘deleted’ table


The ‘deleted’ table stores copies of the affected rows during DELETE and UPDATE statements.
During the execution of a DELETE statement, rows are deleted from the trigger table and
transferred to the ‘deleted’ table. The ‘deleted’ table and the trigger table ordinarily have no rows
in common.

The ‘inserted’ table


The ‘inserted’ table stores copies of the affected rows during INSERT and UPDATE statements.
During an insert transaction, new rows are added to both the ‘inserted’ table and the trigger
table. The rows in the ‘inserted’ table are copies of the new rows in the trigger table.

An update transaction is similar to a delete operation followed by an insert operation; the old
rows are copied to the ‘deleted’ table first, and then the new rows are copied to the trigger table
and to the ‘inserted’ table.

Page | 62
To illustrate, update the telephone number from 732-3333 to 732-3334

DML Trigger
Example 1 : Move deleted records in Customer History table (Customer_Hist_T)
CREATE TRIGGER CustDelete_tr
ON Customer_t
AFTER
DELETE
AS
BEGIN
INSERT INTO Customer_Hist_T
SELECT *
FROM deleted
END

After successful deletion of record from Customer_T. The deleted


record is then temporarily moved to deleted file. The trigger
action is to save that temporary record in deleted file to
Customer_Hist_T

Page | 63
Example 2: Create audit trail on changes
CREATE TRIGGER CustUpdate_tr
ON Customer_t
AFTER UPDATE
AS
INSERT INTO Customer_Hist_T
SELECT * from
FROM deleted;

Updated records are actually deleted (old version) and then inserted
(new version). The old version of the record is temporarily stored in
deleted table. Above trigger permanently stores old versions of updated
records in a Customer History table (audit trails).

DDL Trigger
Syntax 2:
CREATE TRIGGER trigger_name
ON { ALL SERVER | DATABASE }
{ FOR | AFTER } event_type , [...n]
AS
{ sql_statement [ ; ] [ ,...n ]}

Event Types - DDL Events that fire a DDL Trigger

• CREATE_TABLE
• ALTER_TABLE
• DROP_TABLE
• CREATE_VIEW
• ALTER_VIEW
• DROP_VIEW

Page | 64
Example
CREATE TRIGGER TR_safety
ON DATABASE
FOR DROP_TABLE
AS
BEGIN
ROLLBACK
PRINT ‘You must disable Trigger “TR_safety” to drop
END
End of Triggers for SQL Server

The following are trigger syntax and examples for MySQL


(https://dev.mysql.com/doc/refman/8.0/en/create-trigger.html)

DML Trigger
Syntax (abbreviated):

CREATE TRIGGER trigger_name

trigger_time

trigger_event

ON tbl_name FOR EACH ROW

trigger_body

trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger
activates before or after each row to be modified.
Basic column value checks occur prior to trigger activation, so you cannot use BEFORE triggers
to convert values inappropriate for the column type to valid values.
trigger_time: { BEFORE | AFTER }

trigger_event indicates the kind of operation that activates the trigger.


These trigger_event values are permitted:
• INSERT: The trigger activates whenever a new row is inserted into the table
• UPDATE: The trigger activates whenever a row is modified
• DELETE: The trigger activates whenever a row is deleted from the table
trigger_event: { INSERT | UPDATE | DELETE }

Page | 65
trigger_body is the statement to execute when the trigger activates. To execute multiple
statements, use the BEGIN ... END
Example:
(https://www.mysqltutorial.org/create-the-first-trigger-in-mysql.aspx/)

First, create a new table named customer_audit to keep the changes to the customer_t table:

CREATE TABLE customer_audit (


id INT AUTO_INCREMENT PRIMARY KEY,
cust_number INT NOT NULL,
cust_name VARCHAR(50) NOT NULL,
changedate DATETIME DEFAULT NULL,
action VARCHAR(50) DEFAULT NULL);

Next, create a BEFORE DELETE trigger that is invoked before a DELETE is made to
the Customer_t table.
CREATE TRIGGER before_cust_delete
BEFORE DELETE
ON customer_t FOR EACH ROW
INSERT INTO customer_audit  trigger body
VALUES (id, old.cust_id, old.cust_name, now(), 'delete');

Once a delete on customer_t is done, the trigger before_cust_delete will be automatically


executed and it will trigger an insert into customer_audit. It will contain the cust_id, cust_name
of the deleted record.
Within the trigger body, you can refer to columns in the subject table (the table associated with
the trigger) by using the aliases OLD and NEW. OLD.col_name refers to a column of an
existing row before it is updated or deleted. NEW.col_name refers to the column of a new row
to be inserted or an existing row after it is updated.(see example above on how the old alias is
used).
MySQL does not support DDLTrigger
(https://dev.mysql.com/worklog/task/?id=2418)

End of Triggers for MySQL

Page | 66
Advantages Of Trigger:

• Promotes stronger data integrity and consistency of use within the database

• Data auditing - create logs of information about data updates

• Security - Prevent unauthorized changes to the database

• Stored only once, so code maintenance is simplified

How to copy entire table into another table

In this example, we copy customer_t to customer_hist_t

SQL Server: SELECT * INTO customer_hist_t


FROM customer_t

MySQL : CREATE TABLE customer_hist_t


SELECT * from customer_t;

Watch

Triggers/SQL/Tutorial 20 (MySQL)
https://www.youtube.com/watch?time_continue=317&v=gpthfJnvzY8&feature=emb_l
ogo
DML Triggers in sql server, Part 43
https://www.youtube.com/watch?v=k0S4P-a6d5w&t=62s

Read

Chapter 7, Advanced SQL


Modern Database Management, 11th Ed., by Hoffer, Ramesh, Topi
https://msdn.microsoft.com/en-us/library/ms187926.aspx

ASSESSMENTS/ACTIVITIES

Answer the following questions:


1. When do you use a BEGIN…END in the trigger body?
2. What is the difference between a DML and a DDL trigger?
3. What alias do you use to get column values of deleted records?
4. Use the same table and data used in previous activities
EMPLOYEE(EmpNo, Sname, JobLevel, Status, DateHired, Salary, EmpAddress).
4.1 Create another table and call it EMPLOYEE_HIST. This will be the history table or

Page | 67
audit trail for all changes to Employee table. It should have the same fields as Employee
4.2 Create a trigger that will store in Employe_Hist table all records which are deleted
from Employee table
4.3 Create a trigger that will store in Employe_Hist table the before and after images of
all records which are updated in Employee table
5. What events will fire a DDL trigger (for SQL Server)?

Page | 68
ERROR HANDLING

OVERVIEW

Error Handling explains what are the things to be done in case certain errors are encountered
by the program.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Explain the function of error handling routines

COURSE MATERIALS
MySQL does not support TRY/CATCH. Instead an error handler is declared which calls
rollback. See example below
https://stackoverflow.com/questions/9974325/mysql-transaction-within-a-stored-procedure
https://dev.mysql.com/doc/refman/8.0/en/declare-handler.html

Example:
START TRANSACTION;

DECLARE EXIT HANDLER FOR SQLEXCEPTION


BEGIN
ROLLBACK;
EXIT PROCEDURE;
END;
COMMIT;

All discussions that follows are for SQL Server.


TRY/CATCH

• A group of Transact-SQL statements can be enclosed in a TRY block. If an error occurs


in the TRY block, control is passed to another group of statements that is enclosed in a
CATCH block.
Syntax:
BEGIN TRY
Contains the query for which we need to do the
error handling
END TRY
BEGIN CATCH

Page | 69
If there is an error in the query within the TRY block,
the flow will be passed to this CATCH block
END CATCH
Example:
BEGIN TRY
INSERT INTO Customer_t
VALUES(@custid,@custname,@address)
END TRY
BEGIN CATCH
PRINT 'Error Number: ' + str(error_number())
PRINT 'Line Number: ' + str(error_line())
PRINT error_message()
ROLLBACK
END CATCH
XACT_STATE

• Is a scalar function that reports the user transaction state of a current


running request.
• It indicates whether the request has an active user transaction, and
whether the transaction is capable of being committed.

Example : (with XACT_STATE())


BEGIN TRY
INSERT INTO Cust_t
VALUES(@custid,@custname,@address)
END TRY
BEGIN CATCH

Page | 70
PRINT 'Error Number: ' + str(error_number())
PRINT 'Line Number: ' + str(error_line())
PRINT error_message()
ROLLBACK
END CATCH
IF XACT_STATE() = 1
BEGIN
COMMIT TRANSACTION
PRINT 'Transaction committed.'
END;

Watch

Error Handling in sql server, Part 56


https://www.youtube.com/watch?v=VLDirfx_OQg

Read

https://technet.microsoft.com/en-us/library/ms189797(v=sql.110).aspx

ASSESSMENTS/ACTIVITIES

1. Why are error handling routines used in programming?

Page | 71
BACK-UP AND RECOVERY

OVERVIEW

This module explains why there is a need to back-up , what are the types of back-up, and what
are the different methods of doing a back-up

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Enumerate the different causes why database may be damaged and records may be lost
2. Differentiate a cold back-up from a hot back-up
3. Explain the different means by which database may be recovered

COURSE MATERIALS
Causes of Database Damage

• Human Error, Program Error

• Hardware Failure, Network Failure

• Computer Viruses

• Incorrect or Invalid Data

• Natural Catastrophe
The database administrator must minimize downtime while back-up is on-going so
that there will be as little disruption as possible, restoring the database as soon as
possible after a loss or damage.

Basic Recovery Facilities

• Backup Facilities

• Journalizing Facilities

• Checkpoint Facility

• Recovery Manager

Backup Facilities

• Backup Utilities (COPY)

• Export

Page | 72
• SELECT…. INTO (SQL Server)

• CREATE TABLE… SELECT… (MySQL)


(see full syntax in chapter on triggers)
The back-up frequency is typically once a day.
Scripts are created to automate back-up
Backup Types

• Cold backup - full backup where the database is shutdown

• Hot backup – selected portion of the database is shutdown from use


Backup needs to be balanced versus database downtime and cost of additional
technology; some DBMS automatically make backup copies stored in separated disks
(live backup)
Journalizing Facilities
Two basic journals

• Transaction log

• Database change log


Checkpoint Facility

• State wherein the DBMS refuses to accept any new transactions

• All transactions in progress are completed and journal files are brought up-to-date

• Database and transaction logs are synchronized

• Checkpoint record is written to the log file used to restart system


DBMS may perform Checkpoints automatically or can be initiated by commands in
user app programs
Checkpoint record is written to the log file which is a snapshot of the database.
Checkpoint contains necessary info to restart system
Checkpoints should be taken frequently (e.g. several times in an hour) so that when
failures occur, it is possible to resume processing from the most recent checkpoint.
Thus only a few minutes of processing work must be repeated compared with several
hours for a complete restart of the day’s processing
DBMS may perform Checkpoints automatically or can be initiated by commands in
user application programs.
Recovery Manager

• DBMS Module that restores database to a correct condition using journal logs or
backups

Page | 73
Watch

Backup and Restore Database in Sql Server


https://www.youtube.com/watch?v=mr8Lpkx5yag

Read

Chapter 11, Data and Database Administration


Modern Database Management 11th Ed, Hoffer, Topi, Ramesh
https://technet.microsoft.com/en-us/library/ms190805(v=sql.105).aspx

ASSESSMENTS

Answer the following questions:


1. What type of data need a more frequent back-up?
2. Differentiate a cold and a hot back-up.
3. Why should a cold back-up be less frequent than a hot back-up?
4. Enumerate three causes of database damage and give an instance when they have
happened
5. Write the SQL code which will copy the entire table (TABLE1) into a new
table (TABLE2)
6. What type of stored procedure have we learned that can be used to create
a database change log or a transaction log?

ACTIVITY (optional)
Using the video (https://www.youtube.com/watch?v=mr8Lpkx5yag), create a backup
of a database. Restore the database backed up.

Page | 74
CONCURRENCY CONTROL

OVERVIEW

This module explains what concurrency is all about and how the database management system
manages transactions to maintain data integrity.

LEARNING OUTCOMES

At the end of this module, the student must be able to:


1. Explain the concept of concurrency control.
2. Discuss the impact of having no concurrency issues.
3. Differentiate pessimistic and optimistic approaches to concurrency control.

COURSE MATERIALS
Definition
Concurrency is when more than one transaction is being processed against a database at the
same time
Concurrency Control pertains to actions that must be taken to ensure that data integrity is
maintained; ensures that one user’s actions do not adversely impact another user’s actions

Concurrency Processing Example

Page | 75
Transactions are processed in an interleaving manner so that more than 1 transactions could be
running at any given time. Two or more transactions may be running concurrently at a database
server.

Two Approaches to Concurrency Control

• Pessimistic Approach
Involves locking; cautious approach so that others cannot use the data we are using.
Once updates to a data that has been locked is done, the lock on the data is released

• Optimistic Approach
Involves versioning; most of the time users will not request the same data and if ever they
do, they may only want to read them
Optimistic approach involves versioning
o Each transaction is restricted to a view of the DB as of the time of start of
transaction
o When a transaction modifies a records, the DBMS creates a new version
instead of overwriting the old record

Concurrency Issues
• Lost Updates
When two or more transactions select the same row and the last update overwrites updates
made by the other transaction, which results in lost data.
• Dirty reads (inconsistent read)
When user reads data that have been partially updated by another user; Dirty read the
transaction reads a modified record that has not yet been committed to the database
• Phantom reads
The transaction's first read of the range of rows shows a row that no longer exists in the second
or succeeding read as a result of a deletion by a different transaction.
Similarly, the transaction's second or succeeding read shows a row that did not exist in the
original read as the result of an insertion by a different transaction.

Deadlock
An impasse that results when two or more transactions have locked a common resource and
each must wait for the other to unlock that resource

Page | 76
Example:
User A User B
1. Lock Resource X 1. Lock Resource Y
2. Request Resource Y 2. Request Resource X
(Wait for Y) (Wait for X)

Managing Deadlock
Deadlock Prevention – user must lock all records required at the beginning of transaction
Deadlock Resolution – DBMS resolves the deadlock by backing out one of the deadlocked
transactions

Read

Chapter 11, Data and Database Administration


Modern Database Management 11th Ed, Hoffer, Topi, Ramesh

ASSESSMENTS/ACTIVITIES

Answer the following questions:


1. Explain what the meaning of concurrency is.
2. What is concurrency control?
3. Differentiate the two approaches to concurrency control.
4. Give an example of a dirty read.
5. Explain what happens in a phantom read.
6. Explain what a deadlock is.
7. What will be the impact of deadlock to processing?

Page | 77
IMPORT / EXPORT IN RELATIONAL DATABASES

OVERVIEW
This section shows how to put data into an RDBMS from external sources like excel file or text
file and vice versa. Data can also be moved from one RDBMS into another RDBMS. This will
show how to export/import data using SQL Server and MySQL.

LEARNING OUTCOMES

At the end of this module, the student is expected to:


1. Execute data import from excel or a text file into a database
2. Execute data export from a database into an excel or a text file
3. Explore the different ways of moving data from and into the database using different data
storage types

COURSE MATERIALS
Part 1: How to Import / Export Data in SQL Server
To be able to perform data movement to and from a database, follow the steps as presented
below. Alternatively, the video at the end will explain the step by step process of exporting and
importing data.
Step 1: From the database where you want to import/export data, go to Tasks, and click on
import or export.

Page | 78
Step 2: Provide your data source.
If you are importing, meaning you are moving data from an external source into the database,
you may be choose an excel file or a text file as input. The data from the input source will be
converted to records in a table of a database.
If you are exporting, meaning you are taking data from a database to an external source, please
choose SQL Server Native client

Page | 79
Step 3: Provide your data destination
If you are importing, the destination should be the Sql Service Native client and database table
where you would want to store the data from the external source.
If you are exporting, the destination should be an excel file or a file flat and you need to provide
the filename (with the location where you will be storing it in your drive)

Step 4: This window appears if you are exporting.


Click on the first button to copy all records from the table to the destination.
Click on the second button if you need only particular records from the source. (a SQL
statement will be used to select the records)

Page | 80
Step 5: Click on Run Immediately

This window will appear and you are done.


If you imported a file, check out the table where you stored the data.
If you exported a file, check out the file in the location you had provided.

Watch

Getting started with SQL Server Import/Export Wizard


https://www.youtube.com/watch?v=ClAPdbzi4WQ

Page | 81
Part 2: How to Import / Export Data in MySQL

Export Excel Data into MySQL


https://dev.mysql.com/doc/mysql-for-excel/en/mysql-for-excel-export.html
Data from a Microsoft Excel worksheet can be exported to a new MySQL database table within
an existing schema.
Important: The export-data operation ignores columns containing binary data (Varbinary or
Blob).
To export Excel worksheet data to a MySQL table

• Start Excel, select the Data menu tab, and then click MySQL for Excel to open the
MySQL for Excel task pane.
• From the Open a MySQL Connection area in the task pane, double-click an existing
local or remote connection to display the available database schemas.
• Select a schema from the list and click Next to display all database objects in the
schema (tables, views, and procedures).
• Select the cells in the Excel worksheet to export and then click Export Excel Data to New
Table. A preview window displays the selected data and provides Column
Options and Advanced Options to be used during the export operation.
• In the Export Data to MySQL dialog (see the next figure), do the following:
o Specify whether the first row in the preview should be used as the column name.
This option is selected by default.
o The First Row Contains Column Names check box controls the data type for
columns either by defaulting the type to a suitable one for rows 2-n (if checked)
or to one suitable for rows 1-n (if unchecked).
o Type a unique table name and select the collation to use for the new table.
o Choose or create a primary key column for the new table.
o Select each column and apply the appropriate options and option values.
o Click Export Data to create the new table with data.

Page | 82
Exporting Excel data to MySQL

Import MySQL Data into Excel


https://dev.mysql.com/doc/mysql-for-excel/en/mysql-for-excel-import.html
Data can be imported from MySQL into a Microsoft Excel worksheet by using the Import MySQL
Data option after selecting either a table, view, or procedure to import.
Important: The import-data operation ignores columns containing binary data (Varbinary or
Blob).
To import MySQL data into an Excel worksheet

• Start Excel, select the Data menu tab, and then click MySQL for Excel to open the
MySQL for Excel task pane.

Page | 83
• From the Open a MySQL Connection area in the task pane, double-click an existing
local or remote connection to display the available database schemas.
• Select a schema from the list and click Next to display all database objects in the
schema (tables, views, and procedures).
• Select the table, view, or procedure with data to import and then click Import MySQL
Data. A preview window displays the selected data and provides Options and Advanced
Options to be used during the import operation.
• Click Import to finish the operation.
The Import Data windows provides a preview of the columns to select during the import
operation. You can specify both the columns and rows to import. As the following figure shows,
the preview includes a small subset of the rows for the selected table or view.

Importing table data with MySQL for Excel

Importing a Table or View. Import-data options apply to the current operation only. The options
for importing a table or view are:

• Include Column Names as Headers: Selected by default, this inserts the column names
at the top of the Microsoft Excel worksheet as a "headers" row.

Page | 84
• Limit to ___ Rows and Start with Row ___: Deselected by default, this limits the range of
imported data. The Limit to option defaults to 1, and defines the number of rows to
import. The Start with Row option defaults to 1 (the first row), and defines where the
import begins. Each option has a maximum value of COUNT(rows) in the table.
• Create a PivotTable with the imported data: Deselected by default. For usage
instructions,
• Add Summary Fields: Deselected by default, this option adds a summary field to each
column.

Choosing Columns To Import. By default, all columns are selected and will be imported.
Specific columns may be selected (or unselected) using the standard Microsoft Windows
method of either Control + Mouse click to toggle the selection of individual columns,
or Shift + Mouse click to select a range of columns.
The background color of a column shows the status of each column. The color white means that
the column has been selected, and therefore it will be imported. Conversely, a gray background
means that the column will not be imported.
Right-clicking anywhere in the preview grid opens a context-menu with either a Select
None or Select All option, depending on the current status.

ASSESSMENTS/ACTIVITIES

Use whichever RDBMS is available for you.


1. Import a worksheet in an excel file into the database. Use an excel file.Name the table
depending on its contents
2. Export a table in the database to aa excel file. Name the excel file depending on its
contents.

--- END ---

References / sources of this instructional material are indicated as reading materials at


the end of every module.
Other sources are attributed in the topic where they are used.

Page | 85
Appendix: MySQL Workbench and the Visual Editor

This is the Home screen of MySQL Workbench, your user interface to MySQL

Click on Local Instance MySQL80 (encircled) and you will be routed to the SQL
editor (below)

Visual SQL Editor

Page | 86
Description of the Visual SQL Editor Elements
(https://dev.mysql.com/doc/workbench/en/wb-sql-editor.html)

1 - Home screen tab. The Home screen tab provides quick access to connections, models, and the
MySQL Migration wizard. Unlike the other main tabs, the Home screen tab does not close. For additional
information, see Chapter 4, Home Screen Tab.

2 - Connection tab. Each connection made to the MySQL server is represented by a separate connection
tab. A server can be active or inactive when the connection tab for it is opened. For assistance in
creating and managing MySQL connections, see Chapter 5, Connections in MySQL Workbench.

3 - SQL query tab. The SQL query tab is a secondary tab that opens by default when you make a
connection to a MySQL server. Each query tab is uniquely identified by an incrementing number: query
1, query 2, and so on. To close an open tab, click the x on the tab. For a closer look at query editing in
MySQL Workbench, (see Section 8.1.1, “SQL Query Tab”).

All SQL query tabs provide an area to edit queries. You can open other specialized editors within tabs in
this same central area. For example, you can edit schemas, tables, columns, and so on. Administration
tabs also open in this area.

4 - Main menu bar. The menu bar has the following


menus: File, Edit, View, Query, Database, Server, Tools, Scripting, and Help. The actions available to you
depend on which tab is selected when you click a menu. For a description of frequently used menus,
see Section 8.1.3, “Query and Edit Menus”.

5 - Main toolbar. The quick actions in this toolbar are (ordered from left to right):

• Create a new SQL tab for executing queries


• Open a SQL script file in a new query tab
• Open Inspector for the selected object
• Create a new schema in the connected server
• Create a new table in the active schema in connected server
• Create a new view in the active schema in the connected server
• Create a new stored procedure in the active schema in the connected server
• Create a new function in the active schema in the connected server
• Search table data for text in objects selected in the sidebar schema tree
• Reconnect to DBMS

6 - Shortcut actions. Provides the following shortcuts (ordered from left to right):

• Show preferences dialog (see Section 3.2, “Workbench Preferences”)


• Hide or show the sidebar panel
• Hide or show the output area panel
• Hide or show the secondary sidebar panel

7 - Sidebar panel. The sidebar has two main labels: Navigator and Information. The labels are omitted on
some hosts.

Page | 87
The Navigator has two subtabs: Administration (previously named Management) and Schemas. You can
merge (or separate) the content of the two tabs into a single list by clicking merge ( ).

The Information area provides the Object Info and Session subtabs, which include read-only information
about a selected object and about the active connection.

8 - Secondary sidebar panel (SQL Additions). The SQL Additions area provides the following subtabs:

• Context Help (see Section 8.1.6, “SQL Additions - Context Help Tab”)
• Snippets (see Section 8.1.5, “SQL Additions - Snippets Tab”)

9 - Output area panel. The output panel can display a summary of the executed queries in the following
forms: Action Output, Text Output, or History Output.

To be able to create tables, SQL programs, go to the editor by clicking on the first icon in the Main
toolbar (See #5 above, highlighted in bold).

To run your queries, find the Execute commands in Query of the main menu bar (See #4 above). Other
ways to execute your queries will be using the icons exactly at the top of the editor (encircled in figure
below).

The bottom panel in figure above (Action Output) shows the status of your query. It will show a white
check in green if the execution is successful. It will show a cross in red if failed.

The middle panel (Result Grid) shows the output.

Top panel is where you write your SQL code.

Schema at the left shows all objects (databases, tables, views, stored procedures, etc.)

-End-

Page | 88
Page | 89

You might also like