Professional Documents
Culture Documents
Instructional Material DBA
Instructional Material DBA
(Advance SQL)
Compiled by:
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.
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 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.
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.
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 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
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
*May not apply with a different teaching modality (i.e. distance learning)
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
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
Major Requirements
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%)
*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:
*May not apply with a different teaching modality (i.e. distance learning, non F2F mode)
Consultation Time
Page | 11
Prepared by: Reviewed by:
Recommending Approval:
Approved by:
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
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
Read
Chapter 11: Data and Database Administration, Modern Database Management by Hoffer,
Ramesh, and Topi
ASSESSMENTS:
Page | 14
STRUCTURED QUERY LANGUAGE (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
Page | 15
3. INSERT – adds new records to the table
4. DELETE – removes records from the table
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
Examples:
ALTER TABLE customer_t
ADD cust_type VARCHAR(2) → add another attribute to
the table
Page | 17
3. DROP TABLE
Syntax
DROP TABLE table_name
Example
DROP TABLE customer_t
2. DELETE
Syntax :
DELETE FROM tablename
Examples:
DELETE FROM customer_t → deletes all records
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
*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
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)
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)
Page | 21
Test Data to be used in GROUP BY examples : Employee_T table
SMR 17000
Page | 22
Important Reminder:
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
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
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
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
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
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
COURSE MATERIALS
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
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.
*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
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
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)
Watch
Page | 42
Read
ASSESSMENTS
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
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
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
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)
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 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
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
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
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.
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
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 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.
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
ASSESSMENTS / ACTIVITIES
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
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.
• 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
• 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’
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
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.
delimiter //
CREATE PROCEDURE sproc_gettrans (In instate char(2), out recs int)
BEGIN
SELECT count(*) into recs
FROM customer_t where state = instate;
END//
Output:
End of Stored Procedure discussion for MySQL
Watch
Page | 56
Read
ASSESSMENTS/ACTIVITIES
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
COURSE MATERIALS
Purpose
• 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
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
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
Page | 60
TRIGGERS
OVERVIEW
LEARNING OUTCOMES
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
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.
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
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 ]}
• 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
DML Trigger
Syntax (abbreviated):
trigger_time
trigger_event
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 }
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:
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');
Page | 66
Advantages Of Trigger:
• Promotes stronger data integrity and consistency of use within the database
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
ASSESSMENTS/ACTIVITIES
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
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;
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
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
Read
https://technet.microsoft.com/en-us/library/ms189797(v=sql.110).aspx
ASSESSMENTS/ACTIVITIES
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
COURSE MATERIALS
Causes of Database Damage
• Computer Viruses
• 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.
• Backup Facilities
• Journalizing Facilities
• Checkpoint Facility
• Recovery Manager
Backup Facilities
• Export
Page | 72
• SELECT…. INTO (SQL Server)
• Transaction log
• All transactions in progress are completed and journal files are brought up-to-date
• DBMS Module that restores database to a correct condition using journal logs or
backups
Page | 73
Watch
Read
ASSESSMENTS
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
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
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.
• 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
ASSESSMENTS/ACTIVITIES
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
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)
Page | 80
Step 5: Click on Run Immediately
Watch
Page | 81
Part 2: How to Import / Export Data in MySQL
• 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
• 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 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
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)
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.
5 - Main toolbar. The quick actions in this toolbar are (ordered from left to right):
6 - Shortcut actions. Provides the following shortcuts (ordered from left to right):
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.
Schema at the left shows all objects (databases, tables, views, stored procedures, etc.)
-End-
Page | 88
Page | 89