<<

CS317 File and Systems

http://dilbert.com/strips/comic/1995-10-11/

Lecture 5 – Completion of SQL and Intro to Stored Procedures

September 26, 2016  Sam Siewert SQL Theory and Standards

Completion of SQL (Connolly-Begg Chapters 7 & 8) Part-1

 Sam Siewert

2 For Discussion… SQL is An Evolving ISO Standard – SQL:2011 1. What We’ve Learned So Far is SQL:1992 – Core SQL 2. Better integration of Procedural Language with SQL – PL/SQL 3. Extensions for Convenience? Other? 4. Security Issues? 5. OO Support? – Two Positions (Object RDBMS, New OO DBMS)

Assignment #3 – SQL Advanced Features and Extensions Beyond Core, More Core SQL, ODBMS – Import DreamHome Schema and Data – I will do on PRClab – Do on your own for VB-Linux MySQL – Goal is to Practice SQL for Proficiency – Practice with Stored Procedures that work with MySQL – Start OO with ERD and ODBMS work using SQL:2011 Features  Sam Siewert 3 Connolly-Begg Chapter 7

SQL RDBMS Wrap-Up (Data Types & Schema Level Commands)

 Sam Siewert

4 DreamHome Schema Page 112, Figure 4.3

Chapter 7, Problem 7.21, 7.22

Create (s) for schema loaded on Bb with tab delimited data

Can be Used to Verify Examples in Chapter 5 & 6

 Sam Siewert 5 ISO SQL Data Types

Pearson Education © 2014 6 Integrity Enhancement Feature

Required Data position VARCHAR(10) NOT NULL

Domain Constraints (a) CHECK sex CHAR NOT NULL CHECK (sex IN (‘M’, ‘F’))

Pearson Education © 2014 7 Integrity Enhancement Feature

(b) CREATE DOMAIN CREATE DOMAIN DomainName [AS] dataType [DEFAULT defaultOption] [CHECK (searchCondition)]

For example: CREATE DOMAIN SexType AS CHAR CHECK (VALUE IN (‘M’, ‘F’)); sex SexType NOT NULL

Pearson Education © 2014 8 Integrity Enhancement Feature

searchCondition can involve a table lookup:

CREATE DOMAIN BranchNo AS CHAR(4) CHECK (VALUE IN (SELECT branchNo FROM Branch));

Domains can be removed using DROP DOMAIN:

DROP DOMAIN DomainName [RESTRICT | CASCADE]

Pearson Education © 2014 9 IEF - Entity Integrity

Primary key of a table must contain a unique, non- value for each . ISO standard supports clause in CREATE and ALTER TABLE statements: PRIMARY KEY(staffNo) PRIMARY KEY(clientNo, propertyNo) Can only have one PRIMARY KEY clause per table. Can still ensure uniqueness for alternate keys using UNIQUE: UNIQUE(telNo)

Pearson Education © 2014 10 IEF -

FK is or set of columns that links each row in child table containing foreign FK to row of parent table containing matching PK. Referential integrity means that, if FK contains a value, that value must refer to existing row in parent table. ISO standard supports definition of FKs with FOREIGN KEY clause in CREATE and ALTER TABLE: FOREIGN KEY(branchNo) REFERENCES Branch

Pearson Education © 2014 11 Relational Keys

Superkey – An attribute, or set of attributes, that uniquely identifies a tuple within a .

Candidate Key – (K) such that no proper subset is a superkey within the relation. – In each tuple of R, values of K uniquely identify that tuple (uniqueness). – No proper subset of K has the uniqueness property (irreducibility).

Pearson Education © 2014 12 Relational Keys

Primary Key – selected to identify tuples uniquely within relation.

Alternate Keys – Candidate keys that are not selected to be primary key.

Foreign Key – Attribute, or set of attributes, within one relation that matches candidate key of some (possibly same) relation.

Pearson Education © 2014 13 IEF - Referential Integrity

Any INSERT/UPDATE attempting to create FK value in child table without matching CK value in parent is rejected. Action taken attempting to / a CK value in parent table with matching rows in child is dependent on referential action specified using ON UPDATE and ON DELETE subclauses:

– CASCADE - SET NULL – SET DEFAULT - NO ACTION

Pearson Education © 2014 14 IEF - Referential Integrity

CASCADE: Delete row parent and delete matching rows in child, and so on in cascading manner. SET NULL: Delete row from parent and set FK column(s) in child to NULL. Only valid if FK columns are NOT NULL. SET DEFAULT: Delete row from parent and set each component of FK in child to specified default. Only valid if DEFAULT specified for FK columns. NO ACTION: Reject delete from parent. Default.

Pearson Education © 2014 15 IEF - Referential Integrity

FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL

FOREIGN KEY (ownerNo) REFERENCES Owner ON UPDATE CASCADE

Pearson Education © 2014 16 Data Definition

SQL DDL allows database objects such as schemas, domains, tables, views, and indexes to be created and destroyed.

Main SQL DDL statements are: CREATE SCHEMA DROP SCHEMA CREATE/ALTER DOMAIN DROP DOMAIN CREATE/ALTER TABLE DROP TABLE CREATE VIEW DROP VIEW

Many DBMSs also provide:

CREATE INDEX DROP INDEX

Pearson Education © 2014 17 CREATE TABLE

CREATE TABLE TableName {(colName dataType [NOT NULL] [UNIQUE] [DEFAULT defaultOption] [CHECK searchCondition] [,...]} [PRIMARY KEY (listOfColumns),] {[UNIQUE (listOfColumns),] […,]} {[FOREIGN KEY (listOfFKColumns) REFERENCES ParentTableName [(listOfCKColumns)], [ON UPDATE referentialAction] [ON DELETE referentialAction ]] [,…]} {[CHECK (searchCondition)] [,…] })

Pearson Education © 2014 18 Example 7.1 - CREATE TABLE

CREATE TABLE PropertyForRent ( propertyNo PNumber NOT NULL, …. rooms PRooms NOT NULL DEFAULT 4, rent PRent NOT NULL, DEFAULT 600, ownerNo OwnerNumber NOT NULL, staffNo StaffNumber Constraint StaffNotHandlingTooMuch …. branchNo BranchNumber NOT NULL, PRIMARY KEY (propertyNo), FOREIGN KEY (staffNo) REFERENCES Staff ON DELETE SET NULL ON UPDATE CASCADE ….);

Pearson Education © 2014 19 ALTER TABLE

Add a new column to a table. Drop a column from a table. Add a new table constraint. Drop a table constraint. Set a default for a column. Drop a default for a column.

Pearson Education © 2014 20 Example 7.2(b) - ALTER TABLE

Remove constraint from PropertyForRent that staff are not allowed to handle more than 100 properties at a time. Add new column to Client table.

ALTER TABLE PropertyForRent DROP CONSTRAINT StaffNotHandlingTooMuch; ALTER TABLE Client ADD prefNoRooms PRooms;

Pearson Education © 2014 21 DROP TABLE

DROP TABLE TableName [RESTRICT | CASCADE]

e.g. DROP TABLE PropertyForRent;

Removes named table and all rows within it. With RESTRICT, if any other objects depend for their existence on continued existence of this table, SQL does not allow request. With CASCADE, SQL drops all dependent objects (and objects dependent on these objects).

Pearson Education © 2014 22 Views

View Dynamic result of one or more relational operations operating on base relations to produce another relation.

• Virtual relation that does not necessarily actually exist in the database but is produced upon request, at time of request.

Pearson Education © 2014 23 Example 7.3 - Create Horizontal View

Create so that manager at branch B003 can only see details for staff who work in his or her office. CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchNo = ‘B003’;

Pearson Education © 2014 24 Example 7.4 - Create Vertical View

Create view of staff details at branch B003 excluding salaries. CREATE VIEW Staff3 AS SELECT staffNo, fName, lName, position, sex FROM Staff WHERE branchNo = ‘B003’;

25 Pearson Education © 2014 Example 7.5 - Grouped and Joined Views Create view of staff who manage properties for rent, including branch number they work at, staff number, and number of properties they manage.

CREATE VIEW StaffPropCnt (branchNo, staffNo, cnt) AS SELECT s.branchNo, s.staffNo, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffNo = p.staffNo GROUP BY s.branchNo, s.staffNo;

Pearson Education © 2014 26 SQL - DROP VIEW

DROP VIEW ViewName [RESTRICT | CASCADE]

Causes definition of view to be deleted from database. For example:

DROP VIEW Manager3Staff;

Pearson Education © 2014 27 Advantages of Views

Data independence Currency Improved security Reduced complexity Convenience Customization

Pearson Education © 2014 28 Disadvantages of Views

Update restriction Structure restriction Performance

Pearson Education © 2014 29 Reading Advice

Read View Resolution, but Just Scan for Highlights

Understand Restrictions on Views – Scan

Experiment Using Views and Understand they are Normally Stored Queries Rather than New Tables

IGNORE View Materialization

Transactions – Autocommit - Understand that SQL is All or None with and Roll-back on Modifications to Base Schema (to Avoid Corruption – Partial Update, Readers/Writers Issues from OS) With Simple Commands – For Complex Updates Requiring Multiple Commands, We Can Wrap in Formal Transaction

 Sam Siewert 30 Privileges

Actions user permitted to carry out on given base table or view: SELECT Retrieve data from a table. INSERT Insert new rows into a table. UPDATE Modify rows of data in a table. DELETE Delete rows of data from a table. REFERENCES Reference columns of named table in integrity constraints. USAGE Use domains, collations, character sets, and translations.

Pearson Education © 2014 31 GRANT

GRANT {PrivilegeList | ALL PRIVILEGES} ON ObjectName TO {AuthorizationIdList | PUBLIC} [WITH GRANT OPTION]

PrivilegeList consists of one or more of above privileges separated by commas. ALL PRIVILEGES grants all privileges to a user.

Pearson Education © 2014 32 Example 7.7/8 - GRANT

Give Manager full privileges to Staff table.

GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION;

Give users Personnel and Director SELECT and UPDATE on column salary of Staff.

GRANT SELECT, UPDATE (salary) ON Staff TO Personnel, Director;

Pearson Education © 2014 33 Example 7.10/11 - REVOKE Specific Privileges

Revoke privilege SELECT on Branch table from all users. REVOKE SELECT ON Branch FROM PUBLIC; Revoke all privileges given to Director on Staff table.

REVOKE ALL PRIVILEGES ON Staff FROM Director;

Pearson Education © 2014 34 Connolly-Begg Chapter 8

SQL RDBMS Wrap-Up (Advanced SQL – Stored Procedures)

 Sam Siewert

35 Focus

1. More Practice with SQL

1. Stored Procedures – SQL/PSM (General ISO Standard 9075- 4:1996 – Persistent Stored Modules) – PL/SQL (Oracle only) Close to SQL/PSM, – MySQL Stored Procedures for PRClab also Similar (http://dev.mysql.com/doc/refman/5.1/en/stored-programs- views.html )

2. Trigger Basics (MySQL Ref Manual 19.3)

3. IGNORE Recursion in SQL

 Sam Siewert 36 Notes

PL/SQL from the Book does not work on MySQL on PRClab – You will not be held accountable for syntax and semantics, just awareness of PL/SQL – We will look at basic Stored Programs in MySQL in Assignment #3

Today, Focus on Concepts and Read Examples in Chapter 19 of MySQL Reference Manual

I will Provide Simple MySQL Stored Program Examples Today

 Sam Siewert 37 The SQL Programming Language

Impedance mismatch – Mixing different programming paradigms – SQL is a declarative language – High-level language such as C is a procedural language – SQL and 3GLs use different models to represent data

“Impedance is the opposition by a system to the flow of energy from a source.” [wikipedia] “opposition to blood flow in the circulatory system” [webster, 3rd definition]

By mismatch, this implies that some of the power of SQL is limited by the Java or C++ embedding and some of the power of Java or C++ is perhaps limited by SQL (they were not designed to be combined – not orthogonal, not at same level) – E.g. assigning a variable or object to contain tuples returned from .

[Idea - instead of embedding SQL in say C/C++ or Java, rather build in Procedural Extensions to SQL that can be Stored, Like any Other Data] 38 MySQL SQL/PSM

The “;” is default use ;

delimiter, so we delimiter $$ need to redefine to enter a stored drop procedure if exists helloworld$$

procedure on the create procedure helloworld() command line Begin select ‘hello world’; end$$ Select is like printf in MySQL delimiter ;

Helloworld is in table proc

 Sam Siewert 39 Simple MySQL Example Classic C/C++ Hello World is Entered into mysql schema in the proc table (relation) It is Stored like any other tuple Any number of procedures using SQL/PSM can be stored They are Invoked with Call

 Sam Siewert 40 Examine mysql DB and tables

SQL Procedures are Stored at Tuples in “proc”

 Sam Siewert 41 Declarations (PL/SQL)

Variables and constant variables must be declared before they can be referenced Possible to declare a variable as NOT NULL %TYPE – variable same type as a column – vStaffNo Staff.staffNo%TYPE; %ROWTYPE – variable same type as an entire row – vStaffNo1 Staff%ROWTYPE;

42 Assignments (PL/SQL)

Variables can be assigned in two ways: – Using the normal assignment statement (:=):

vStaffNo := ‘SG14’;

– Using an SQL SELECT or FETCH statement:

SELECT COUNT(*) INTO x FROM PropertyForRent WHERE staffNo = vStaffNo;

43 Control Statements (PL/SQL)

Conditional IF statement Conditional CASE statement Iteration statement (LOOP) Iteration statement (WHILE and REPEAT) Iteration statement (FOR)

44 MySQL PSM Example

Note SET

REPEAT

= for Assignment, but := OK too

Does Not Agree with PL/SQL, but Equivalent Capability

 Sam Siewert 45 Conditional IF Statement (PL/SQL) IF (position = ‘Manager’) THEN salary := salary*1.05; ELSE salary := salary*1.05; END IF;

46 Conditional CASE Statement – PL/SQL UPDATE Staff SET salary = CASE WHEN position = ‘Manager’ THEN salary * 1.05 ELSE salary * 1.02 END;

47 Iteration Statement (LOOP) – x:=1; PL/SQL myLoop: LOOP x := x+1; IF (x > 3) THEN EXIT myLoop; --- exit loop now END LOOP myLoop; --- control resumes here y := 2;

48 Iteration Statement (WHILE and REPEAT) – PL/SQL WHILE () DO END WHILE [labelName];

REPEAT UNTIL (condition) END REPEAT [labelName];

49 Iteration Statement (FOR) – PL/SQL myLoop1: FOR iStaff AS SELECT COUNT(*) FROM PropertyForRent WHERE staffNo = ‘SG14’ DO ….. END FOR myLoop1;

50 Subprograms, Stored Procedures, Functions, and Packages Subprograms – Named PL/SQL blocks that can take parameters and be invoked Two types: – Stored procedures – Functions (returns a single value to caller) Can take a set of parameters – Each has name and data type – Can be designated as IN, OUT, IN OUT

51 Triggers

Trigger – Defines an action that the database should take when some event occurs in the application – Based on Event-Condition-Action (ECA) model Types – Row-level – Statement-level Event: INSERT, UPDATE or DELETE Timing: BEFORE, AFTER or INSTEAD OF Advantages and disadvantages of triggers

52 MySQL Trigger Example

INSERT Trigger to Sum Debit/Credit for all Accounts

 Sam Siewert 53 MySQL Trigger Example

UPDATE Trigger to Range Limit Data 0…100 – Can’t use CALL in Trigger – Can’t begin or end a transaction

 Sam Siewert 54 Triggers – Advantages

Elimination of redundant code Simplifying modifications Increased security Improved integrity Improved processing power Good fit with client-server architecture

55 Triggers – Disadvantages

Performance overhead Cascading effects Cannot be scheduled Less portable

56 Discussion Goal of RDBMS is Minimal Redundant Data – Foreign Keys are Ideally the Only Redundant Data – Used for Hierarchical Relations – Goal of Normalization is to Eliminate Redundancy (Chapter 14) Insertion Anomalies Deletion Anomalies Modification Anomalies

Recall E.F. Codd’s Concerns with Redundancy

So, Not Just Efficiency Issues

OOA/OOD and OOP Have Redundancy Often – Refinement of Classes and Instantiation (Chapter 9)

 Sam Siewert 57