Lecture 6 Structured Query Language (SQL)

Similar documents
Lecture 5 Data Definition Language (DDL)

Standard Query Language. SQL: Data Definition Transparencies

Example 1 - Create Horizontal View. Example 2 - Create Vertical View. Views. Views

3ISY402 DATABASE SYSTEMS

Lecture 07. Spring 2018 Borough of Manhattan Community College

DB Creation with SQL DDL

Transforming ER to Relational Schema

STRUCTURED QUERY LANGUAGE (SQL)

ADVANCED QUERY AND VIEWS

Chapter 6. SQL Data Manipulation

CS317 File and Database Systems

CS317 File and Database Systems

CMP-3440 Database Systems

COMP102: Introduction to Databases, 5 & 6

COSC 304 Introduction to Database Systems. Views and Security. Dr. Ramon Lawrence University of British Columbia Okanagan

CS317 File and Database Systems

Relational Algebra and Relational Calculus. Pearson Education Limited 1995,

Views. COSC 304 Introduction to Database Systems. Views and Security. Creating Views. Views Example. Removing Views.

Chapter 6. SQL: SubQueries

Lecture 03. Spring 2018 Borough of Manhattan Community College

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

Slides by: Ms. Shree Jaswal

Relational Data Model ( 관계형데이터모델 )

Institute of Southern Punjab, Multan

Conceptual Database Design

Basic SQL. Basic SQL. Basic SQL

Chapter 3. The Relational database design

Chapter 5. Relational Algebra and Relational Calculus

Lecture 03. Fall 2017 Borough of Manhattan Community College

CS317 File and Database Systems

Chapter 1 SQL and Data

Data Definition Language (DDL)

CMP-3440 Database Systems

RELATIONAL DATA MODEL

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

OBJECTIVES. How to derive a set of relations from a conceptual data model. How to validate these relations using the technique of normalization.

Database Technologies. Madalina CROITORU IUT Montpellier

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Lab # 4. Data Definition Language (DDL)

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

CMP-3440 Database Systems

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Physical Database Design

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Database Systems. A Practical Approach to Design, Implementation, and Management. Database Systems. Thomas Connolly Carolyn Begg

A <column constraint> is a constraint that applies to a single column.

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Solved MCQ on fundamental of DBMS. Set-1

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement


Lecture 08. Spring 2018 Borough of Manhattan Community College

The Relational Model

Database Technologies. Madalina CROITORU IUT Montpellier

Logical Database Design. ICT285 Databases: Topic 06

Chapter 4. The Relational Model

Data about data is database Select correct option: True False Partially True None of the Above

CSC 261/461 Database Systems Lecture 6. Fall 2017

Query Processing Transparencies. Pearson Education Limited 1995, 2005

More SQL: Complex Queries, Triggers, Views, and Schema Modification

SQL STRUCTURED QUERY LANGUAGE

Database design process

Concepts of Database Management Seventh Edition. Chapter 4 The Relational Model 3: Advanced Topics

q Ø v v v v v v v v IBM - 2

CMP-3440 Database Systems

Lecture 05. Spring 2018 Borough of Manhattan Community College

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

Where are we? Week -4: Data definition (Creation of the schema) Week -3: Data definition (Triggers) Week -1: Transactions and concurrency in ORACLE.

Introduction to SQL. ECE 650 Systems Programming & Engineering Duke University, Spring 2018

5 Integrity Constraints and Triggers

CS317 File and Database Systems

Lecture4: Guidelines for good relational design Mapping ERD to Relation. Ref. Chapter3

Lecture2: Database Environment

SQL: A COMMERCIAL DATABASE LANGUAGE. Complex Constraints

The Structured Query Language Get Started

More SQL: Complex Queries, Triggers, Views, and Schema Modification

Data Modelling and Databases. Exercise Session 7: Integrity Constraints

SQL. Char (30) can store ram, ramji007 or 80- b

COSC 304 Introduction to Database Systems SQL DDL. Dr. Ramon Lawrence University of British Columbia Okanagan

CS317 File and Database Systems

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

Data analysis and design Unit number: 23 Level: 5 Credit value: 15 Guided learning hours: 60 Unit reference number: H/601/1991.

SQL: The Query Language Part 1. Relational Query Languages

Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Structured Query Language (SQL)

Objective. The goal is to review material covered in Chapters 1-5. Do the following questions from the book.

Lecture5 Functional Dependencies and Normalization for Relational Databases

SQL: A COMMERCIAL DATABASE LANGUAGE. Data Change Statements,

SQL Data Definition Language

Visit for more.

More SQL: Complex Queries, Triggers, Views, and Schema Modification

CHAPTER4 CONSTRAINTS

ECE 650 Systems Programming & Engineering. Spring 2018

Using DDL Statements to Create and Manage Tables. Copyright 2006, Oracle. All rights reserved.

Relational Model. Rab Nawaz Jadoon DCS. Assistant Professor. Department of Computer Science. COMSATS IIT, Abbottabad Pakistan

COSC344 Database Theory and Applications. Lecture 6 SQL Data Manipulation Language (1)

CS2300: File Structures and Introduction to Database Systems

CSE 530A. ER Model to Relational Schema. Washington University Fall 2013

CS317 File and Database Systems

Transcription:

ITM661 Database Systems Lecture 6 Structured Query Language (SQL) (Data Definition) T. Connolly, and C. Begg, Database Systems: A Practical Approach to Design, Implementation, and Management, 5th edition, Addison-Wesley, 2009. ISBN: 0-321-60110-6, ISBN-13: 978-0-321-60110-0 (International Edition). T. Connolly, and C. Begg, Database Systems: A Practical Approach to Design, Implementation, and Management, 4th edition, Addison-Wesley, 2004. ISBN: 0-321-21025-5. R. Elmasri and S. B. Navathe, Fundamentals of Database Systems, 5th ed., Pearson, 2007, ISBN: 0-321-41506-X.

Objectives Integrity Enhancement Feature How to use the integrity enhancement feature in the CREATE and ALTER TABLE statements. How to create and delete views using SQL. How the DBMS performs operations on views. Under what conditions views are updatable. Advantages and disadvantages of views. How to use GRANT/REVOKE statements as a level of security. ITS322 DBMS Lecture 5: SQL (Data Definition) 2

Integrity Enhancement Feature Consider five types of integrity constraints: Required data. Domain constraints. Entity integrity. Referential integrity. Enterprise constraints. ITS322 DBMS Lecture 5: SQL (Data Definition) 3

CREATE TABLE CREATE DOMAIN OwnerNumber AS VARCHAR(5) CHECK (VALUE IN (SELECT ownerno FROM PrivateOwner)); CREATE DOMAIN StaffNumber AS VARCHAR(5) CHECK (VALUE IN (SELECT staffno FROM Staff)); CREATE DOMAIN PNumber AS VARCHAR(5) CREATE DOMAIN PRooms AS SMALLINT; CHECK (VALUE BETWEEN 1 AND 15); CREATE DOMAIN PRent AS DECIMAL(6,2) CHECK (VALUE BETWEEN 0 AND 9999.99); 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.); ITS322 DBMS Lecture 5: SQL (Data Definition) 4

Integrity Enhancement Feature (Required Data and Domain Constraints) Required Data Domain Constraints (a) CHECK position VARCHAR(10) NOT NULL (b) CREATE DOMAIN sex CHAR NOT NULL CHECK (sex IN ( M, F )) CREATE DOMAIN SexType AS CHAR CHECK (VALUE IN ( M, F )); sex SexType NOT NULL ITS322 DBMS Lecture 5: SQL (Data Definition) 5

Integrity Enhancement Feature (Domain Constraints Continued) 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] ITS322 DBMS Lecture 5: SQL (Data Definition) 6

Integrity Enhancement Feature (Entity Integrity) Primary key of a table must contain a unique, nonnull value for each row. ISO standard supports PRIMARY KEY 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) ITS322 DBMS Lecture 5: SQL (Data Definition) 7

Integrity Enhancement Feature (Referential Integrity) FK is column 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 ITS322 DBMS Lecture 5: SQL (Data Definition) 8

Integrity Enhancement Feature (Referential Integrity Constraint Types) Any INSERT/UPDATE that attempts to create FK value in child table without matching candidate key value in parent is rejected. Action taken that attempts to update/delete a candidate key 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 ITS322 DBMS Lecture 5: SQL (Data Definition) 9

Integrity Enhancement Feature (Referential Integrity - Detail) CASCADE Delete row from 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. ITS322 DBMS Lecture 5: SQL (Data Definition) 10

Integrity Enhancement Feature (Referential Integrity How to use) How to use referential integrity FOREIGN KEY (staffno) REFERENCES Staff ON DELETE SET NULL FOREIGN KEY (ownerno) REFERENCES Owner ON UPDATE CASCADE ITS322 DBMS Lecture 5: SQL (Data Definition) 11

Integrity Enhancement Feature (Enterprise Constraints) Could use CHECK/UNIQUE in CREATE and ALTER TABLE. CREATE ASSERTION AssertionName CHECK (searchcondition) which is very similar to the CHECK clause. An example CREATE ASSERTION StaffNotHandlingTooMuch CHECK (NOT EXISTS ( SELECT staffno FROM PropertyForRent GROUP BY staffno HAVING COUNT(*) > 100)) ITS322 DBMS Lecture 5: SQL (Data Definition) 12

ALTER TABLE (I) 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. ALTER TABLE table_name [ADD [COLUMN] column_name data_type [NOT NULL] [UNIQUE] [DEFAULT default_option] [CHECK (search_condition)] [DROP [COLUMN] column_name [RESTRICT CASCADE]] [ADD [CONSTRIANT [constraint_name]] table_constraint] [DROP CONSTRAINT constraint_name [RESTRICT CASCADE]] [ALTER [COLUMN] SET DEFAULT default_option] [ALTER [COLUMN] DROP DEFAULT] ITS322 DBMS Lecture 5: SQL (Data Definition) 13

ALTER TABLE (II) Change Staff table by removing default of 'Assistant' for Position column and setting default for Sex column to female ('F'). ALTER TABLE staff ALTER position DROP DEFAULT; ALTER TABLE staff ALTER sex SET DEFAULT 'F'; Removing constraint that staff not allowed to handle more than 10 properties at a time from Property_for_Rent. ALTER TABLE property_for_rent DROP CONSTRAINT staff_not_handling_too_much; Add new column to Renter representing preferred area for accommodation. ALTER TABLE renter ADD pref_area VARCHAR(15); ITS322 DBMS Lecture 5: SQL (Data Definition) 14

View Dynamic result of one or more relational operations operating on the base relations to produce another relation. Virtual relation that does not actually exist in the database but is produced upon request, at time of request. Contents of a view are defined as a query on one or more base relations. Any operations on view are automatically translated into operations on relations from which it is derived. ITS322 DBMS Lecture 5: SQL (Data Definition) 15

SQL - Create View CREATE VIEW view_name [ (column_name [,...]) ] AS subselect [WITH [CASCADED LOCAL] CHECK OPTION] Can assign a name to each column in view. If list of column names is specified, it must have same number of items as number of columns produced by subselect. If omitted, each column takes name of corresponding column in subselect. WITH CHECK OPTION ensures that if a row fails to satisfy WHERE clause of defining query, it is not added to underlying base table. Need SELECT privilege on all of tables referenced in the subselect and USAGE privilege on any domains used in referenced columns. ITS322 DBMS Lecture 5: SQL (Data Definition) 16

Create Horizontal View Create a view so that the manager at branch B3 can only see details for staff who work in his or her office. CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchno = 'B003'; ITS322 DBMS Lecture 5: SQL (Data Definition) 17

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 ; CREATE VIEW Staff3 AS SELECT staffno, fname, lname, position, sex FROM Manager3Staff; ITS322 DBMS Lecture 5: SQL (Data Definition) 18

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; ITS322 DBMS Lecture 5: SQL (Data Definition) 19

SQL - DROP VIEW DROP VIEW view_name [RESTRICT CASCADE] Causes definition of view to be deleted from the database. DROP VIEW Manager3Staff; With CASCADE, all related dependent objects are deleted; i.e. any views defined on view being dropped. With RESTRICT (default), if any other objects depend for their existence on continued existence of view being dropped, command is rejected. ITS322 DBMS Lecture 5: SQL (Data Definition) 20

View Resolution Count number of properties managed by each member at branch B003. SELECT staffno, cnt FROM StaffPropCnt WHERE branchno = B003 ORDER BY staffno; 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; ITS322 DBMS Lecture 5: SQL (Data Definition) 21

View Resolution (a) View column names in SELECT list are translated into their corresponding column names in the defining query: SELECT s.staffno AS staffno, COUNT(*) AS cnt (b) View names in FROM are replaced with corresponding FROM lists of defining query: FROM Staff s, PropertyForRent p (c) WHERE from user query is combined with WHERE of defining query using AND: WHERE s.staffno = p.staffno AND branchno = 'B003 (d) GROUP BY and HAVING clauses copied from defining query: GROUP BY s.staffno, s.branchno (e) ORDER BY copied from query with view column name translated into defining query column name ORDER BY s.staffno ITS322 DBMS Lecture 5: SQL (Data Definition) 22

View Resolution Final merged query is now executed to produce the result: SELECT s.staffno, COUNT(*) FROM Staff s, PropertyForRent p WHERE s.staffno = p.staffno AND s.branchno = 'B003' GROUP BY s.staffno, s.branchno ORDER BY s.staffno; SELECT staffno, cnt FROM StaffPropCnt WHERE branchno = 'B003' ORDER BY staffno; 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; ITS322 DBMS Lecture 5: SQL (Data Definition) 23

Restrictions on Views SQL-92: several restrictions on creation and use of views. (a) If column in view is based on an aggregate function: Column may appear only in SELECT and ORDER BY clauses of queries that access view. Column may not be used in WHERE nor be an argument to an aggregate function in any query based on view. For example, following query would fail: SELECT COUNT(cnt) FROM StaffPropCnt; SELECT * FROM StaffPropCnt WHERE cnt > 2; ITS322 DBMS Lecture 5: SQL (Data Definition) 24

Restrictions on Views (b) Grouped view may never be joined with a base table or a view. For example, StaffPropCnt view is a grouped view, so any attempt to join this view with another table or view fails. The following statement fails. SELECT COUNT(cnt) FROM StaffPropCnt c, Staff s WHERE c.staffno =s.staffno; ITS322 DBMS Lecture 5: SQL (Data Definition) 25

View Updatability All updates to base table reflected in all views that encompass base table. Similarly, may expect that if view is updated then base table(s) will reflect change. However, consider view StaffPropCnt: 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; ITS322 DBMS Lecture 5: SQL (Data Definition) 26

View Updatability If tried to insert record showing that at branch B3, SG5 manages 2 properties: INSERT INTO StaffPropCnt VALUES ('B003', 'SG5', 2); Have to insert 2 records into Property_for_Rent showing which properties SG5 manages. However, do not know which properties they are; i.e. do not know primary keys! ITS322 DBMS Lecture 5: SQL (Data Definition) 27

View Updatability If change definition of view and replace count with actual property numbers: CREATE VIEW StaffPropList(branchNo,staffNo,propertyNo) AS SELECT s.branchno, s.staffno, p.propertyno FROM Staff s, PropertyForRent p WHERE s.staffno = p.staffno; Trying to insert the record: INSERT INTO staffproplist VALUES ('B003', 'SG5', 'PG19'); Still problem, because in PropertyForRent all columns except postcode/staffno are not allowed nulls. However, have no way of giving remaining non-null columns values. ITS322 DBMS Lecture 5: SQL (Data Definition) 28

View Updatability SQL-92 specifies the views that must be updatable in system that conforms to standard. Definition given is that a view is updatable iff: DISTINCT is not specified. Every element in SELECT list of defining query is a column name and no column appears more than once. FROM clause specifies only one table, excluding any views based on a join, union, intersection or difference. WHERE clause does not include any nested SELECTs that reference the table in FROM clause. There is no GROUP BY or HAVING clause in the defining query. Every row added through view must not violate integrity constraints of base table. Be able to trace back to its row and column in the source tables. ITS322 DBMS Lecture 5: SQL (Data Definition) 29

Update WITH CHECK OPTION (I) Rows exist in a view because they satisfy WHERE condition of defining query. If a row changes and no longer satisfies condition, it disappears from the view. New rows appear within view when insert/update on view cause them to satisfy WHERE condition. Rows that enter or leave a view are called migrating rows. WITH CHECK OPTION prohibits a row migrating out of the view. CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchno = 'B003' WITH CHECK OPTION; ITS322 DBMS Lecture 5: SQL (Data Definition) 30

Update WITH CHECK OPTION (II) LOCAL/CASCADED apply to view hierarchies. With LOCAL, any row insert/update on view and any view directly or indirectly defined on this view must not cause row to disappear from view unless row also disappears from derived view/table. With CASCADED (default), any row insert/update on this view and on any view directly or indirectly defined on this view must not cause row to disappear from the view. ITS322 DBMS Lecture 5: SQL (Data Definition) 31

Update WITH CHECK OPTION (III) CREATE VIEW Manager3Staff AS SELECT * FROM Staff WHERE branchno = 'B003' WITH CHECK OPTION; UPDATE Manager3Staff SET branchno = B005 WHERE staffno = SG37 ; Cannot update branch number of row B003 to B005 as this would cause row to migrate from view. Specification of WITH CHECK OPTION would prevent following insert through row: INSERT INTO Manager3Staff VALUES('SL15','Mary','Black','2 Hillcrest, London NW2', '0181-554-3426', 'Assistant', 'F', '21-Jun-67', 8000, 'WM787850T', 'B002'); ITS322 DBMS Lecture 5: SQL (Data Definition) 32

Update WITH CHECK OPTION (IV) If Manager3_Staff is defined not on Staff directly but on another view of Staff: CREATE VIEW LowSalary AS SELECT * FROM Staff WHERE salary > 9000; CREATE VIEW HighSalary AS SELECT * FROM LowSalary WHERE salary > 10000 WITH LOCAL CHECK OPTION; CREATE VIEW Manager3Staff AS SELECT * FROM HighSalary WHERE branchno = 'B003'; UPDATE Manager3Staff SET salary = 9500 WHERE staffno = 'SG37'; Update would fail: although update would cause row to disappear from HighSalary, row would not disappear from LowSalary. However, if update tried to set salary to 8000, update would succeed as row would no longer be part of LowSalary. ITS322 DBMS Lecture 5: SQL (Data Definition) 33

Update WITH CHECK OPTION (V) If HighSalary had specified WITH CASCADED CHECK OPTION, setting salary to 9500 or 8000 would be rejected because row would disappear from HighSalary. To prevent anomalies like this, each view should be created using WITH CASCADED CHECK OPTION. ITS322 DBMS Lecture 5: SQL (Data Definition) 34

Pros and Cons of Views Data Independence Currency Security Reduced Complexity Convenience Customization Data Integrity Update Restriction Structure Restriction Performance Advantages Disadvantage ITS322 DBMS Lecture 5: SQL (Data Definition) 35

Access Control (Authorization Identifiers and Ownership) Authorization identifier is normal SQL identifier used to establish identity of a user. Usually, has an associated password. Used to determine which objects user may reference and what operations may be performed on those objects. Each object created in SQL has an owner, as defined in AUTHORIZATION clause of schema to which the object belongs. Owner is only person who may know about it. ITS322 DBMS Lecture 5: SQL (Data Definition) 36

Privileges Actions allowed 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 a table in integrity constraints. USAGE Use domains, collations, character sets, and translations. Can restrict INSERT/UPDATE/REFERENCES to columns. Owner of table must grant other users the necessary privileges using GRANT statement. To create view, user must have SELECT privilege on all tables that make up view and REFERENCES privilege on the named columns. ITS322 DBMS Lecture 5: SQL (Data Definition) 37

GRANT (I) GRANT {PrivilegeList ALL PRIVILEGES} ON ObjectName TO {AuthorizationIdList PUBLIC} [WITH GRANT OPTION] privilege_list consists of one or more of the above privileges separated by commas. SELECT DELETE INSERT [(col_name [, ])] UPDATE [(col_name [, ])] REFERENCES [(col_name [, ])] USAGE ALL PRIVILEGES grants all privileges to a user. ITS322 DBMS Lecture 5: SQL (Data Definition) 38

GRANT (II) PUBLIC allows access to be granted to all present and future authorized users. object_name can be a base table, view, domain, character set, collation or translation. WITH GRANT OPTION allows privileges to be passed on. Ex.: give Manager full privileges to Staff table. GRANT ALL PRIVILEGES ON Staff TO Manager WITH GRANT OPTION; ITS322 DBMS Lecture 5: SQL (Data Definition) 39

GRANT Specific Privileges Give Admin SELECT and UPDATE on column Salary of Staff. GRANT SELECT, UPDATE (salary) ON Staff TO Admin; Give users Personnel and Deputy SELECT on Staff table. GRANT SELECT ON Staff TO Personnel, Deputy; Give all users SELECT on Branch table. GRANT SELECT ON Branch TO PUBLIC; ITS322 DBMS Lecture 5: SQL (Data Definition) 40

REVOKE (I) REVOKE takes away privileges granted with GRANT. REVOKE [GRANT OPTION FOR] {PrivilegeList ALL PRIVILEGES} ON ObjectName FROM {AuthorizationIdList PUBLIC} [RESTRICT CASCADE] ALL PRIVILEGES refers to all privileges granted to a user by user revoking privileges. ITS322 DBMS Lecture 5: SQL (Data Definition) 41

REVOKE (II) GRANT OPTION FOR allows privileges passed on via WITH GRANT OPTION of GRANT to be revoked separately from the privileges themselves. REVOKE fails if it results in an abandoned object, such as a view, unless the CASCADE keyword has been specified. (such as a view cannot be created if no privilege) Privileges granted to this user by other users are not affected by REVOKE but we can use CASCADE. ITS322 DBMS Lecture 5: SQL (Data Definition) 42

REVOKE (III) ITS322 DBMS Lecture 5: SQL (Data Definition) 43

REVOKE Specific Privileges Revoke privilege SELECT on Branch table from all users. REVOKE SELECT ON Branch FROM PUBLIC; Revoke all privileges given to Deputy on Staff table. REVOKE ALL PRIVILEGES ON Staff FROM Deputy; ITS322 DBMS Lecture 5: SQL (Data Definition) 44

Exercise 5-1 : View Resolution What is the difference between a view and a base relation? Show the view solution result of the following view definition and query. SELECT bname, maxsal FROM BranchMaxMinSalary WHERE bno LIKE %B0% ORDER BY bname; CREATE VIEW BranchMaxMinSalary (bno, bname, maxsal, minsal) AS SELECT b.branchno, b.branchname, MAX(s.salary), MIN(s.salary) FROM Staff s, Branch b WHERE s.branchno = b.branchno GROUP BY b.branch.id, b.branchname ; ITS322 DBMS Lecture 5: SQL (Data Definition) 45

Exercise 5-2 : Restrictions on View Given the following view CREATE VIEW BranchMaxMinSalary (bno, bname, maxsal, minsal) AS SELECT b.branchno, b.branchname, MAX(s.salary), MIN(s.salary) FROM Staff s, Branch b WHERE s.branchno = b.branchno GROUP BY b.branch.id, b.branchname ; Are the following queries valid based on SQL-92? SELECT bname, maxsal FROM BranchMaxMinSalary WHERE maxsal >=100 ORDER BY bname; SELECT bname, minsal FROM BranchMaxMinSalary b, PropertyForRent p WHERE b.branchno=p.branchno AND p.propertyno= PG14 ITS322 DBMS Lecture 5: SQL (Data Definition) 46

Exercise 5-3 : View Updatability What is view updatability? Explain the result of the following view update. CREATE VIEW BranchSum (bno, sumsal) AS SELECT b.branchno, SUM(s.salary) FROM Staff s, Branch b WHERE s.branchno=b.branchno; UPDATE BranchSum SET sumsal = sumsal*1.05 WHERE bno = B002'; Explain the result of the following view update. CREATE VIEW StaffB01 (sno, fn, sal) AS SELECT s.staffno, s.fname, s.salary FROM Staff s WHERE s.branchno LIKE %B01% ; UPDATE StaffB01 SET sal = sal*1.05 WHERE sal < 1000; ITS322 DBMS Lecture 5: SQL (Data Definition) 47

Exercise 5-4 : Privileges Let the following privilege-related SQL statements be executed. UserA (1) UserB (2) UserC (3) UserD (5) (4) UserE (1) GRANT ALL PRIVILEGES ON TableA TO UserB WITH GRANT OPTION (2) GRANT SELECT, UPDATE ON TableA TO UserC WITH GRANT OPTION (3) GRANT SELECT, UPDATE ON TableA TO UserD (4) GRANT SELECT ON TableA TO UserC (5) REVOKE SELECT ON TableA FROM UserB CASCADE Describe the privileges of UserB, UserC and UserD on TableA Fill Y if the user has a privilege and fill N if the user has no privilege ITS322 DBMS Lecture 5: SQL (Data Definition) 48