0% found this document useful (0 votes)
3 views

Module 8 Lecture

This document provides advanced SQL concepts, focusing on the SQL ALTER and MERGE statements, as well as outer join queries and additional SQL features. It outlines learning objectives, database structure, and practical examples for modifying tables, adding constraints, and combining data. The content is based on the Wedgewood Pacific database and includes detailed SQL syntax and use cases.

Uploaded by

samerelking3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Module 8 Lecture

This document provides advanced SQL concepts, focusing on the SQL ALTER and MERGE statements, as well as outer join queries and additional SQL features. It outlines learning objectives, database structure, and practical examples for modifying tables, adding constraints, and combining data. The content is based on the Wedgewood Pacific database and includes detailed SQL syntax and use cases.

Uploaded by

samerelking3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

Database Concepts

Ninth Edition

Extension B
Advanced SQL

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Learning Objectives (1 of 2)
2

• To understand reasons for using the SQL ALTER statement


• To use the SQL ALTER statement
• To understand the need for the SQL MERGE statement
• To use the SQL MERGE statement
• To understand the need for additional types of SQL queries
• To use SQL outer join queries
• To use SQL correlated subqueries
• To use SQL queries on recursive relationships
• To understand the reasons for using SQL set operators
• To use SQL set operators

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Learning Objectives (2 of 2)
3

• To understand the reasons for using SQL views


• To use SQL statements to create and use SQL views
• To understand SQL/Persistent Stored Modules
(SQL/PSM)
• To use SQL statements to create and use SQL user-
defined functions
• To introduce the topic of importing Microsoft Excel 2019
data into a database table
• To introduce the topic of using Microsoft Access 2019 as
an application development platform

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Background
4

• The discussion in this extension will continue to be based on the


Wedgewood Pacific (WP) database.
• The tables in this database, in schema format, are:
PRODUCTION_ITEM (SKU, SKU_Description,
ProductionStartDate, ProductionEndDate,
QuantityOnHand, QuantityInProduction)
CATALOG_SKU_2017(CatalogID, SKU, CatalogDescription,
CatalogPage, DateOnWebsite)
CATALOG_SKU_2018(CatalogID, SKU, CatalogDescription,
CatalogPage, DateOnWebsite)

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.1 WP Database Column
5

Characteristics for the


PRODUCTION_ITEM Table

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.2 WP Database Column
6

Characteristics for the


CATALOG_SKU_20## Tables

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.3 WP Database Data for the
7

PRODUCTION_ITEM Table

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.4 WP Database Data for the
8

CATALOG_SKU_2017 Table

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.5 WP Database Data for the
9

CATALOG_SKU_2018 Table

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.6 SQL CREATE TABLE
10

Statements to Modify the WP


Database

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
11

Figure B.7 SQL


INSERT Statements
to Populate the New
WP Database Tables

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.8 The Revised Database
12

Design for the WP Database

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.9 Data in the New WP
13

Database Tables (1 of 3)

(a) Data in the New PRODUCTION_ITEM Table


MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.9 Data in the New WP
14

Database Tables (2 of 3)

(b) Data in the New CATALOG_SKU_2017 Table


MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.9 Data in the New WP
15

Database Tables (3 of 3)

(c) Data in the New CATALOG_SKU_2018 Table


MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using the SQL ALTER TABLE
16

Statement
To understand reasons for using the SQL ALTER statement
• The SQL ALTER TABLE statement is used to modify the
structure of a table once it has been created in a
database.
– Can be used to add, modify, and drop columns and
constraints
– Very useful to modify the AUTO_INCREMENT starting
value in MySQL 8.0

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Modifying the MySQL
17

AUTO_INCREMENT Starting Value


To use the SQL ALTER statement
• Notice in Figure B-6 the increment value (of the surrogate
key) has been changed using the ALTER TABLE
statement as shown below.
/* *** EXAMPLE CODE – THIS STATEMENT HAS
ALREADY BEEN RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-01 *** */
ALTER TABLE CATALOG_SKU_2017
AUTO_INCREMENT = 20170001;
• The same has been done for the 2018 catalog!

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Modifying the MySQL
18

AUTO_INCREMENT Starting Value


To use the SQL ALTER statement
• /* Note use of NULL to generate next AUTO_INCREMENT value in MySQL */

INSERT INTO CATALOG_SKU_2017 VALUES(NULL,170102001, 'Our low price


Alpha II model in black.', 10, '2017-01-01’);

INSERT INTO CATALOG_SKU_2018 VALUES(NULL, 180103001, 'Our low


price Alpha III model in black.', 10, '2018-01-01');

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
19

Adding a Column to an Existing Table


To use the SQL ALTER statement

• The SQL ALTER TABLE statement can be used to add a column to


an existing table as seen below.
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-03 *** */
ALTER TABLE {TableName}
ADD {ColumnName} {DataType} {OptionalColumnConstraints};

• Note that the SQL COLUMN keyword is not used in an ADD


{COLUMN} clause. MySQL does allow it but is not required!
• The above statement is sufficient if adding a column that allows NULL
values. If a NOT NULL column constraint exists then the following
steps must be used:
1. Add the column as column that allows NULL values.
2. Update all table rows with data values in the new column.
3. Modify the column to set the NOT NULL constraint.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
20

Adding a Column to an Existing Table


To use the SQL ALTER statement

1. Add a new column named ApprovalDate as a NULL column to the


PRODUCTION_ITEM table.
ALTER TABLE PRODUCTION_ITEM ADD ApprovalDate DATE NULL;

2. Update the current rows in the PRODUCTION_ITEM table with the FAA
approval dates for the existing drone models. Examples:
UPDATE PRODUCTION_ITEM SET ApprovalDate = '2016-08-31' WHERE SKU = 170102001;

UPDATE PRODUCTION_ITEM SET ApprovalDate = '2016-08-31’ WHERE SKU = 170102005;

UPDATE PRODUCTION_ITEM SET ApprovalDate = '2016-09-30’ WHERE SKU = 170201001;

3. Modify the ApprovalDate column to set the NOT NULL column constraint.
ALTER TABLE PRODUCTION_ITEM MODIFY COLUMN ApprovalDate DATE NOT NULL;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.10
21

PRODUCTION_ITEM.ApprovalDate
set to NOT NULL

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Adding a Table Constraint to an
22

Existing Table
To use the SQL ALTER statement

• The SQL ALTER TABLE statement can be used to add a table


constraint to an existing table. The basic syntax is:
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-06 *** */
ALTER TABLE {TableName}
ADD CONSTRAINT {ConstraintName} {TableConstraint};

• Note that the SQL CONSTRAINT keyword is used in an ADD


CONSTRAINT clause
• Note the addition of the CHECK constraint below.
/* *** SQL-ALTER-TABLE-ExtB-07 *** */
ALTER TABLE PRODUCTION_ITEM
ADD CONSTRAINT CheckProductionDate CHECK
(ApprovalDate < ProductionStartDate);

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.11 The PRODUCTION_ITEM
23

CheckProductionDate Constraint

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Adding a Referential Integrity
24

Constraint to an Existing Table


To use the SQL ALTER statement
• The SQL ALTER TABLE statement can be used to add a referential integrity
constraint to an existing table. The basic syntax is:
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-08 *** */
ALTER TABLE {TableName}
ADD CONSTRAINT {ConstraintName} FOREIGN KEY({ColumnName})
REFERENCES {TableName}({PrimaryKeyColumn})
{Optional ON UPDATE clause}
{Optional ON DELETE clause};
• Note that the SQL CONSTRAINT keyword is used in an ADD CONSTRAINT
clause.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Adding a Referential Integrity
25

Constraint to an Existing Table


To use the SQL ALTER statement
/* *** SQL-ALTER-TABLE-ExtB-09 *** */

ALTER TABLE CATALOG_SKU_2018

ADD CONSTRAINT CAT18_PROD_ITEM_FK FOREIGN KEY(SKU) REFERENCES


PRODUCTION_ITEM(SKU)

ON UPDATE NO ACTION

ON DELETE NO ACTION;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.12 The Database Design for
26

the WP Database with the Added


Relationship

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Removing a Table Column from an
27

Existing Table
To use the SQL ALTER statement
• The SQL ALTER TABLE statement can be used to
remove a column from a table. Note that the SQL
COLUMN keyword is used in the DROP COLUMN clause.
The basic syntax is:
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-10 *** */
ALTER TABLE {TableName}
DROP COLUMN {ColumnName};

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Removing a Table Constraint from an
28

Existing Table
To use the SQL ALTER statement
• The SQL ALTER TABLE statement can be used to
remove a table constraint. Note that the SQL
CONSTRAINT keyword is used in the DROP
CONSTRAINT clause. The basic syntax is:
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-ALTER-TABLE-ExtB-11 *** */
ALTER TABLE {TableName}
DROP CONSTRAINT {ConstraintName};

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using the SQL MERGE Statement
29

To understand the need for the SQL MERGE statement


• The SQL MERGE statement combines the capabilities of
the SQL INSERT and SQL UPDATE statement into one
statement that can selectively insert or update data
depending upon what data is already in a table. While
Microsoft SQL Server and Oracle Database support the
MERGE statement, MySQL does not.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.13 SQL CREATE TABLE
30

Statement to Create the


PRODUCTION_ ITEM_DATA Table

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
31

Figure B.14 Adding Data to the


PRODUCTION_ITEM_ DATA Table (1 of 2)

(a) SQL Statements to Add Data to the PRODUCTION_ITEM_DATA Table


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
32

Figure B.14 Adding Data to the


PRODUCTION_ITEM_ DATA Table (2 of 2)

(b) The Data in the PRODUCTION_ITEM_DATA Table


SQL Server 2017, SQL Server Management Studio, Microsoft Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using the SQL MERGE Statement
33

To understand the need for the SQL MERGE statement


MERGE INTO PRODUCTION_ITEM AS PROI

USING PRODUCTION_ITEM_DATA AS PROID

ON PROI.SKU = PROID.SKU

WHEN MATCHED THEN

UPDATE SET PROI.ProductionEndDate = PROID.ProductionEndDate

WHEN NOT MATCHED THEN

INSERT (SKU, SKU_Description, ProductionStartDate, ProductionEndDate,


QuantityOnHand, QuantityInProduction, ApprovalDate)

VALUES (PROID.SKU, PROID.SKU_Description, PROID.ProductionStartDate,


PROID.ProductionEndDate, PROID.QuantityOnHand, PROID.QuantityInProduction,
PROID.ApprovalDate);

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using Outer Join Queries
34

To use SQL outer join queries


• In the WP database, we combine both the EMPLOYEE,
ASSIGNMENT, and PROJECT databases with the following JOIN ON
syntax:
/* *** SQL-Query-CH03-53 *** */
SELECT ProjectName, FirstName, LastName, HoursWorked
FROM EMPLOYEE AS E JOIN ASSIGNMENT AS A
ON E.EmployeeNumber = A.EmployeeNumber
JOIN PROJECT AS P
ON A.ProjectID = P.ProjectID
ORDER BY P.ProjectID, A.EmployeeNumber;
• The results of this query can be seen in Figure B-15.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
35

Figure B.15 The Results for SQL-Query-


CH03-53

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Results of Using Left JOIN ON Query
36

To use SQL outer join queries

• The problem with the previous query is no data about the new project with
ProjectID 1700! But now consider the following SQL query statement—which
simplifies SQL Query-CH03-53 by retrieving employee numbers instead of
employee names and thus eliminates the need to include the EMPLOYEE
table in the query—and notice the use of the JOIN ON syntax—the SQL LEFT
keyword is simply added to the SQL query to include data from the left side
(PROJECT), even though it has no match!
/* *** SQL-Query-ExtB-02 *** */
SELECT ProjectName, EmployeeNumber, HoursWorked
FROM PROJECT AS P LEFT JOIN ASSIGNMENT AS A
ON P.ProjectID = A.ProjectID
ORDER BY P.ProjectID;

• The results of this query can be seen in Figure B-16. Notice the last row of
this data!

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
37

Figure B.16 The Results for SQL-Query-


ExtB-02

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
38

Results of Using Right JOIN ON Queries


To use SQL outer join queries

• Right outer joins operate similarly, except that the SQL RIGHT keyword is
used, and rows in the table on the right-hand side of the FROM clause are
included. For example, you could join all three tables together with the
following modification of SQL-QueryCH03-53, which includes a right outer join
which will show not only the employees assigned to projects but also those
employees who are not assigned.
/* *** SQL-Query-ExtB-03 *** */
SELECT ProjectName, FirstName, LastName, HoursWorked
FROM (PROJECT AS P JOIN ASSIGNMENT AS A
ON P.ProjectID = A.ProjectID)
RIGHT JOIN EMPLOYEE AS E
ON A.EmployeeNumber = E.EmployeeNumber
ORDER BY P.ProjectID, A.EmployeeNumber;

• The result of this join, which now shows not only the employees assigned to
projects but also those employees who are not assigned to any projects, is
shown in Figure B-17.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
39

Figure B.17 The Results for SQL-Query-


ExtB-03

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using Correlated Subqueries
40

To use SQL correlated subqueries


• A correlated subquery works very differently than a regular subquery.
– A regular subquery processes from the bottom up whereas a correlated
subquery takes a value from the table in the query and compares it to
every row in the subquery and then repeats for the next value in the main
query.
– Regular Subquery:
/* *** SQL-Query-ExtB-04 *** */
SELECT E.FirstName, E.lastName
FROM EMPLOYEE AS E
WHERE EmployeeNumber IN
( SELECT A.EmployeeNumber
FROM ASSIGNMENT AS A
WHERE A.ProjectID = 1000);

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using Correlated Subqueries
41

To use SQL correlated subqueries


• A correlated subquery works very differently than a regular subquery.
– A correlated subquery will use the same table in both the main and
subquery and only differentiate them by using a version.

• Example: take the value of LastName from the first row in EMPLOYEE and
examine all of the other rows in the table. If we find a row that has the same
last name as the one in the first row, we know there are duplicates, so we
print the EmployeeNumber, LastName, and FirstName of the first row.

/* *** SQL-Query-ExtB-05 *** */


SELECT E1.EmployeeNumber, E1.FirstName, E1.LastName
FROM EMPLOYEE AS E1
WHERE E1.LastName IN
(SELECT E2.LastName
FROM EMPLOYEE AS E2
WHERE E1.LastName = E2.LastName
AND E1.EmployeeNumber <>
E2.EmployeeNumber);
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
42

Correlated Subqueries Using the EXISTS


and NOT EXISTS Comparison Operators
To use SQL correlated subqueries
• The use of EXISTS and NOT EXISTS creates another
form of a correlated subquery.
• These operators simply test whether there are any values
returned by the subquery, which indicates there are values
meeting the conditions of the subquery.
– If one or more values are returned, then values from
the subquery are used to run the top-level query.
– If no values are returned, the top-level query produces
an empty set as the result.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
43

Figure B.18 SQL EXISTS and NOT EXISTS


Comparison Operators

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
44

Correlated Subqueries Using the EXISTS


and NOT EXISTS Comparison Operators
To use SQL correlated subqueries
SQL EXISTS keyword as follows:

/* *** SQL-Query-ExtB-07 *** */


SELECT E1.EmployeeNumber, E1.FirstName, E1.LastName

FROM EMPLOYEE AS E1
WHERE EXISTS
(SELECT E2.LastName
FROM EMPLOYEE AS E2
WHERE E1.LastName = E2.LastName
AND E1.EmployeeNumber <> E2.EmployeeNumber);

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
SQL Queries on Recursive
45

Relationships
To use SQL queries on recursive relationships
• Recursive relationships use the same technique we just used in correlated
subqueries. This gives two virtual tables with the queries using them written
just the same as we would any other query.
• The following query will show which employees are supervisors (represented
by an “s”) and which employees (represented by an “e”) they supervise.
/* *** SQL-Query-ExtB-09 *** */
SELECT S.FirstName AS SupervisorFirstName,
S.LastName AS SupervisorLastName,
E.FirstName AS EmployeeFirstName,
E.LastName AS EmployeeLastName
FROM EMPLOYEE S JOIN EMPLOYEE E
ON S.EmployeeNumber = E.Supervisor
ORDER BY S.EmployeeNumber;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using SQL Set Operators
46

To understand the reasons for using SQL set operators

• Mathematicians use the term set theory to describe mathematical operations on sets,
where a set is defined as a group of distinct items.

• Venn diagrams are the standard method of visualizing sets and their relationships.
Some definitions of sets are:
– A set is represented by a labeled circle, as shown in Figure B-19(a).
– A subset is a portion of a set that is contained entirely within the set, as shown
in Figure B-19(b).
– The union of two sets is shown in Figure B-19(c), and represents the two sets
together to get a set that contains all values in both sets. This is equivalent to an
OR logical operation (A OR B).
– The intersection of two sets is shown in Figure B-19(d), and represents the
area common to both sets. This is equivalent to an AND logical operation (A AND
B).
– The complement of set B in set A is shown in Figure B-19(e), and represents
everything in set A that is not in set B. This is equivalent to a logical operation
using A AND (NOT B). It is equivalent to the set difference (A – B).

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.19 Venn Diagrams
47

(a) A Set (b) A Subset (c) The Union of Two Sets (d) The Intersection of Two
Sets (e) The Complement of Two Sets
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.20 SQL Set Operators
48

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using SQL Set Operators
49

To understand the reasons for using SQL set operators

• Example of SQL UNION operator:

/* *** SQL-Query-ExtB-10 *** */


SELECT SKU, CatalogDescription, CatalogPage, DateOnWebSite
FROM CATALOG_SKU_2017
UNION
SELECT SKU, CatalogDescription, CatalogPage, DateOnWebSite

FROM CATALOG_SKU_2018;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
50

Creating and Working with SQL Views


To understand the reasons for using SQL views
• An SQL view is a virtual table that is constructed from other
tables or views.
– A view has no data of its own but uses data stored in tables
or other views.
– Views are created using SQL SELECT statements and then
used in other SELECT statements as just another table.
– The only limitation on the SQL statements that create the
views is that they cannot contain ORDER BY clauses.
– If the results of a query using a view need to be sorted, the
sort order must be provided by the SELECT statement that
processes the view.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
51

The SQL CREATE VIEW statement


To use SQL statements to create and use SQL views
• The SQL CREATE VIEW statement is used to create view structures.
The syntax of this statement is:
/* *** EXAMPLE CODE – DO NOT RUN *** */
/* *** SQL-CREATE-VIEW-ExtB-01 *** */
CREATE VIEW {ViewName} AS
{SQL SELECT statement};

• The view below (EmployeePhoneView) is based on the EMPLOYEE


table in the WP database.
/* *** SQL-CREATE-VIEW-ExtB-02 *** */
CREATE VIEW EmployeePhoneView AS
SELECT FirstName, LastName, OfficePhone AS EmployeePhone
FROM EMPLOYEE;

• The view above is shown in Figure B-21 that follows.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.21 Creating a View in the
52

MySQL Workbench

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
53

Figure B.22 Creating a View in the


Microsoft SQL Server Management Studio

SQL Server 2017, SQL Server Management Studio, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.23 Creating a View in Oracle
54

SQL Developer

Oracle Database XE, SQL Developer 18.4, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
55

Figure B.24 Using EmployeePhoneView in


the MySQL Workbench

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
56

Figure B.25 Using EmployeePhoneView in the


Microsoft SQL Server Management Studio

SQL Server 2017, SQL Server Management Studio, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
57

Figure B.26 Using EmployeePhoneView in


Oracle SQL Developer

Oracle Database XE, SQL Developer 18.4, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
58

Using SQL Views


To use SQL statements to create and use SQL views
• Generally, SQL views are used to prepare data for use in
an information system application.
• Application programmers prefer that the work of
transforming database data into the information that will
be used in and presented by the application be done by
the DBMS itself. Views are the main tool used for this.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.27 SQL Views as the Basis
59

for Application Reports

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
60

Figure B.28 The Wallingford Motors CRM


Web Application Customer Contacts List

Edge, Windows 10, Microsoft Corporation.


Access 2019, Windows 10, Microsoft Corporation.
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
61

Figure B.29 Some Uses for SQL Views

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
62

Using Views to Hide Columns or Rows


To use SQL statements to create and use SQL views
• Views can be used to hide columns to simplify results or to prevent the display
of sensitive information.
• The following statement defines a view, BasicDepartmentDataView:
• will produce that list:
/* *** SQL-CREATE-VIEW-ExtB-03 *** */
CREATE VIEW BasicDepartmentDataView AS
SELECT DepartmentName, DepartmentPhone
FROM DEPARTMENT;

• Selecting from the view:


/* *** SQL-Query-ExtB-12 *** */
SELECT *
FROM BasicDepartmentDataView
ORDER BY DepartmentName;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
63

Using Views to Display Results of


Computed Columns (1 of 2)
To use SQL statements to create and use SQL views
• Another use of views is to show the results of computed columns without
requiring the user to enter the computation expression.

• For example, the following view allows the user to compare the maximum
hours allocated for each WP project to the total hours worked to date on the
project:

/* *** SQL-CREATE-VIEW-ExtB-05 *** */


CREATE VIEW ProjectHoursToDateView AS
SELECT PROJECT.ProjectID, ProjectName,
MaxHours AS ProjectMaxHours,
SUM(HoursWorked) AS ProjectHoursWorkedToDate
FROM PROJECT JOIN ASSIGNMENT
ON PROJECT.ProjectID = ASSIGNMENT.ProjectID
GROUP BY PROJECT.ProjectID;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
64

Using Views to Display Results of


Computed Columns (2 of 2)
To use SQL statements to create and use SQL views

/* *** SQL-Query-ExtB-14 *** */


SELECT *
FROM ProjectHoursToDateView
ORDER BY ProjectID;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
65

Using Views to Hide Complicated SQL


Syntax (1 of 2)
To use SQL statements to create and use SQL views
• Another use of views is to hide complicated SQL syntax. By using views,
developers do not need to enter complex SQL statements when they want
particular results.

• Such views allow developers who do not know how to write complicated SQL
statements to enjoy the benefits of such statements.
• This use of views also ensures consistency. Suppose that WP users need to
know which employees are assigned to which projects and how many hours
each employee has worked on that project. The following view can show this:
/* *** SQL-CREATE-VIEW-ExtB-06 *** */
CREATE VIEW EmployeeProjectHoursWorkedView AS
SELECT ProjectName, FirstName, LastName, HoursWorked
FROM EMPLOYEE AS E JOIN ASSIGNMENT AS A
ON E.EmployeeNumber = A.EmployeeNumber
JOIN PROJECT AS P
ON A.ProjectID = P.ProjectID;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
66

Using Views to Hide Complicated SQL


Syntax (2 of 2)
To use SQL statements to create and use SQL views
• After the previous view has been created, the results of
this statement can be obtained with a single SELECT
statement as shown below.
/* *** SQL-Query-ExtB-15 *** */
SELECT *
FROM EmployeeProjectHoursWorkedView
ORDER BY LastName, FirstName;
The results of this query can be seen on the next slide in
Figure B-30.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.30 The Results for SQL-
67

Query-ExtB-15

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
68

Layering Computations and Built-In


Functions (1 of 3)
To use SQL statements to create and use SQL views
• You cannot use a computation or a built-in function as part of a WHERE
clause.
• You can, however, construct a view that computes a variable and then write
an SQL statement on that view that uses the computed variable in a WHERE
clause. Using view ProjectHoursToDateView, you can utilize ProjectMaxHours,
ProjectHoursWorkedToDate in both an additional calculation and the WHERE clause,
as follows:

/* *** SQL-Query-ExtB-16 *** */


SELECT ProjectID, ProjectName, ProjectMaxHours,
ProjectHoursWorkedToDate
FROM ProjectHoursToDateView
WHERE ProjectHoursWorkedToDate > ProjectMaxHours
ORDER BY ProjectID;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
69

Layering Computations and Built-In


Functions (2 of 3)
To use SQL statements to create and use SQL views
• Here, we are using the result of a computation in a WHERE clause, something that is
not allowed in a single SQL statement. This allows users to determine which projects
have exceeded the number of hours allocated to them by producing the result—and it
looks like

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
70

Layering Computations and Built-In


Functions (3 of 3)
To use SQL statements to create and use SQL views

• Such layering can be continued over many levels. We can turn this SELECT
statement into another view named ProjectsOverAllocatedMaxHoursView (again
without the ORDER BY clause):
/* *** SQL-CREATE-VIEW-ExtB-07 *** */ /* *** SQL-Query-ExtB-17 *** */
CREATE VIEW SELECT ProjectID, ProjectName,
ProjectsOverAllocatedMaxHoursView AS ProjectMaxHours,
SELECT ProjectID, ProjectName, ProjectMaxHours, ProjectHoursWorkedToDate,
ProjectHoursWorkedToDate (ProjectHoursWorkedToDate - ProjectMaxHours)
FROM ProjectHoursToDateView AS HoursOverMaxAllocated
WHERE ProjectHoursWorkedToDate > FROM ProjectsOverAllocatedMaxHoursView
ProjectMaxHours; ORDER BY ProjectID;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
71

SQL/Persistent Stored Modules


(SQL/PSM)
To understand SQL/Persistent Stored Modules (SQL/PSM)
• SQL/PSM provides program variables and cursor functionality.
• It also includes control-of-flow language such as BEGIN . . . END
blocks, IF . . . THEN . . . ELSE logic structures, and LOOPs, as well
as the ability to provide usable output to users.
• The most important feature of SQL/PSM, however, is that it allows the
code that implements these features in a database to be contained in
that database. Thus the name:
– Persistent— the code remains available for use over time
– Stored—the code is stored for reuse in the database
– Modules—the code is written as a self-contained block of code.
• The SQL code can be written as one of three module types: user-
defined functions, triggers, and stored procedures.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
SQL/PSM User-Defined Functions
72

To understand SQL/Persistent Stored Modules (SQL/PSM)


• A user-defined function (also known as a stored function) is a stored
set of SQL statements that:
– Is called by name from another SQL statement.
– May have input parameters passed to it by the calling SQL
statement.
– Returns an output value to the SQL statement that called the
function.
• The logical process flow of a user-defined function is illustrated in
Figure B-31 that follows.
• SQL/ PSM user-defined functions are very similar to the SQL built-in
functions (COUNT, SUM, AVG, MAX, and MIN), except that, as the
name implies, we create them ourselves to perform specific tasks that
we need to do.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.31 User-Defined Functions
73

Logical Process Flow

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Example of Not Using a User-Defined
74

Function
To use SQL statements to create and use SQL user-defined functions

• A common problem is needing a name in the format LastName, FirstName


(including the comma!) in a report when the database stores the basic data in
two fields named FirstName and LastName.

• Using the data in the WP database, we could, of course, simply include the
code to do this in an SQL statement using a concatenation operator as shown
below.
/* *** SQL-Query-ExtB-18 *** */
SELECT CONCAT(RTRIM(LastName),', ',RTRIM(FirstName)) AS EmployeeName,
Department, OfficePhone, EmailAddress
FROM EMPLOYEE
ORDER BY EmployeeName;

• The result of the query above is shown in Figure B-32 that follows.

• Notice how a user-defined function could be created for storing the same
name to be reused later shown in Figure B-33!
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.32 The Results for SQL-
75

Query-ExtB-18

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.33 MySQL 8.0 User- Defined
76

Functions (1 of 2)

(a) Code to Create User-Defined Function to Concatenate FirstName


and LastName
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.33 MySQL 8.0 User- Defined
77

Functions (2 of 2)

(b) The NameConcatenation User-Defined Function in MySQL


Workbench
MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Using the User-Defined Function
78

To use SQL statements to create and use SQL user-


defined functions
• Now that we have created and stored the user-defined
function, we can use it as follows:
/* *** SQL-Query-ExtB-19 *** */
SELECT NameConcatenation(FirstName, LastName) AS EmployeeName, Department,
OfficePhone, EmailAddress
FROM EMPLOYEE
ORDER BY EmployeeName;

• The advantage of having a user-defined function is that


we can now use it whenever we need to without having to
recreate the code. Now we have a function that produces
the results we want, which of course are identical to the
results for SQL-Query-ExtB-18, and which are shown in
Figure B-34.
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.34 The Result of SQL-
79

Query-ExtB-19

MySQL Community Server 8.0, MySQL Workbench, Oracle Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
SQL/PSM Triggers
80

To use SQL statements to create and use SQL user-defined functions

• A trigger is a stored program that is executed by the DBMS whenever a


specified event occurs.
– Triggers for Oracle Database are written in Java or in Oracle’s PL/SQL.
– A trigger is attached to a table or a view.
– A table or a view may have many triggers, but a trigger is associated with
just one table or view.
– A trigger is invoked by an SQL DML INSERT, UPDATE, or DELETE
request on the table or view to which it is attached.
– There are three types of triggers:
§ BEFORE triggers are executed before the DBMS processes the
insert, update, or delete request.
§ INSTEAD OF triggers are executed in place of any DBMS processing
of the insert, update, or delete request.
§ AFTER triggers are executed after the insert, update, or delete
request has been processed.
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.35 Summary of SQL
81

Triggers by DBMS Product

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Four Common Uses of Triggers
82

To use SQL statements to create and use SQL user-


defined functions
• Four common uses of triggers include:
1. Providing default values.
2. Enforcing data constraints.
3. Updating SQL views.
4. Performing referential integrity actions.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Trigger Example
83

To use SQL statements to create and use SQL user-


defined functions

CREATE TRIGGER EMPLOYEE_BEFORE_UPDATE

BEFORE UPDATE ON EMPLOYEE

FOR EACH ROW

INSERT INTO employees_audit

SET action = 'update',

employeeNumber = OLD.employeeNumber,

lastname = OLD.lastname,

changedat = NOW();

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
SQL/PSM Stored Procedures
84

To use SQL statements to create and use SQL user-


defined functions
• A stored procedure is a program that is stored within the
database and compiled when used.
– They can be written in PL/SQL or in Java.
– Stored procedures can receive input parameters and
return results. Unlike triggers, which are attached to a
given table or view, stored procedures are attached to
the database.
– They can be executed by any process using the
database that has permission to use the procedure.
Differences between triggers and stored procedures
are summarized in Figure B-36.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.36 Triggers Versus Stored
85

Procedures

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure B.37 Advantages of Stored
86

Procedures

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Stored Procedures Example
87

To use SQL statements to create and use SQL user-


defined functions

DELIMITER //

CREATE PROCEDURE GetAllEmployeeNames()

BEGIN

SELECT FirstName, LastName

FROM EMPLOYEE;

END //

Use procedure: call GetAllEmployeeNames() ;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Working with Microsoft Access
88

To introduce the topic of using Microsoft Access 2019


as an application development platform
• The following slides deal with working with Microsoft
Access!

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Adding a Column to the CUSTOMER
89

Table
To introduce the topic of using Microsoft Access 2019 as an
application development platform
• Let’s take this one step at time. First, we add the NULL column
ReferredBy. To do this, we will use the SQL ALTER TABLE statement:
/* *** SQL-ALTER-TABLE-WA-ExtB-01 *** */
ALTER TABLE CUSTOMER
ADD ReferredBy INTEGER NULL;

• Then we use SQL UPDATE statements to add new data to the


column:
/* *** SQL-UPDATE-WA-ExtB-01 *** */
UPDATE CUSTOMER
SET ReferredBy = 3
WHERE CustomerID = 4;
/* *** SQL-UPDATE-WA-ExtB-02 *** */
UPDATE CUSTOMER
SET ReferredBy = 1
WHERE CustomerID = 5;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.1 WMCRM Database
90

Column Characteristics for the


CUSTOMER ReferredBy Column

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.2 WMCRM Database
91

Column Characteristics for the


CUSTOMER ReferredBy Column

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.3 The ReferredBy
92

Column in the CUSTOMER Table

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.4 Setting the Indexed
93

Field Property to Yes (No Duplicates)

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
94

Figure WA.B.5 The 1:1 Recursive


Relationship Within the CUSTOMER Table

Access 2019, Windows 10, Microsoft Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.6 The 1:1 Recursive
95

Relationship Is Confirmed

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
96

Figure WA.B.7 The SQL-Query-WA-ExtB-


02 QBE Design Window

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Creating a Microsoft Access Query
97

as a View Equivalent
To introduce the topic of using Microsoft Access 2019 as an application
development platform

• Follow these steps to creating a Microsoft Access Query as a View


Equivalent
1. Click the Create command tab to display the Create command groups.
2. Click the Query Design button.
3. The Query1 tabbed document window is displayed in Design view,
along with the Show Table dialog box.
4. Using either the SQL or QBE technique of creating queries, create the
query, and then click on Design View if needed to complete the query
in Design View as seen below:
SELECT FirstName, LastName, EmailAddress, PhoneNumber AS
CustomerPhoneNumber, PhoneType
FROM CUSTOMER INNER JOIN PHONE_NUMBER
ON CUSTOMER.CustomerID = PHONE_NUMBER.CustomerID
ORDER BY LastName, FirstName;

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
98

Figure WA.B.8 The viewCustomerPhone


Query in the Queries Pane

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
99

Figure WA.B.9 Queries Displayed in the


Show Table Dialog Box

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
100

Figure WA.B.10 The Completed QBE


Query

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
101

Figure WA.B.11 The Completed Query


Result

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
102

Figure WA.B.12 The Wallingford Motors


Gaia Specifications Worksheet

Excel 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
103

Figure WA.B.13 The Revised Wallingford


Motors Gaia Specifications Worksheet

Excel 2019, Windows 10, Microsoft Corporation.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.14 Importing Excel
104

Worksheet Data (1 of 2)

(a) The External Data – New Data Source Button


Access 2019, Windows 10, Microsoft Corporation.
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.14 Importing Excel
105

Worksheet Data (2 of 2)

(b) The Get External Data – Excel Spreadsheet Dialog Box


Access 2019, Windows 10, Microsoft Corporation.
Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.15 The Completed Get
106

External Data – Excel Spreadsheet


Dialog Box

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.16 The Import
107

Spreadsheet Wizard Dialog Box

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
108

Figure WA.B.17 The First Row Contains


Column Headings Check Box

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
109

Figure WA.B.18 The Field Options for the


EstMPG Column (Field)

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
110

Figure WA.B.19 Setting the Primary Key

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.20 Entering the New
111

Table Name

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Figure WA.B.21 The
112

SPECIFICATIONS_2019 Table –
Datasheet View

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
113

Figure WA.B.22 The SPECIFICATIONS_2019


Table – Design View

Access 2019, Windows 10, Microsoft Corporation.


Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved
Copyright
114

This work is protected by United States copyright laws and is


provided solely for the use of instructors in teaching their
courses and assessing student learning. Dissemination or sale of
any part of this work (including on the World Wide Web) will
destroy the integrity of the work and is not permitted. The work
and materials from it should never be made available to students
except by instructors using the accompanying text in their
classes. All recipients of this work are expected to abide by these
restrictions and to honor the intended pedagogical purposes and
the needs of other instructors who rely on these materials.

Copyright © 2020, 2017, 2015 Pearson Education, Inc. All Rights Reserved

You might also like