SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.

Slides:



Advertisements
Similar presentations
BACS 485—Database Management Advanced SQL Overview Advanced DDL, DML, and DCL Commands.
Advertisements

Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
11-1 Copyright © Oracle Corporation, All rights reserved. Different type of keys.
12-1 Copyright  Oracle Corporation, All rights reserved. What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Restricting and sorting data 16 May May May Created By Pantharee Sawasdimongkol.
Subqueries 11. Objectives After completing this lesson, you should be able to do the following: Describe the types of problems that subqueries can solve.
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
10 Copyright © 2004, Oracle. All rights reserved. Creating Other Schema Objects.
Copyright  Oracle Corporation, All rights reserved. 9 Manipulating Data: INSERT, UPDATE, DELETE.
Session 3: SQL (B): Parts 3 & 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
Logical Operators Operator AND OR NOT Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns.
o At the end of this lesson, you will be able to:  Describe the life-cycle development phases  Discuss the theoretical and physical aspects of a relational.
Copyright  Oracle Corporation, All rights reserved. I Introduction.
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Dr. Philip Cannata 1 Programming Languages Prolog Part 3 SQL & Prolog.
Copyright © 2004, Oracle. All rights reserved. Lecture 3: Creating Other Schema Objects Lecture 3: Creating Other Schema Objects ORACLE.
11 Copyright © 2007, Oracle. All rights reserved. Creating Other Schema Objects.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
Displaying Data from Multiple Tables (Join). EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS.
SQL (DDL & DML Commands)
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Introduction to Relational Databases &
1 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
Subqueries.
1 Information Retrieval and Use (IRU) CE An Introduction To SQL Part 1.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
7 Multiple-Column Subqueries. 7-2 Objectives At the end of this lesson, you should be able to: Write a multiple-column subquery Describe and explain the.
10 Creating and Managing Tables Objectives At the end of this lesson, you will be able to: Describe the main database objects Create tables Describe.
11 Copyright © Oracle Corporation, All rights reserved. Creating Views.
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
Copyright  Oracle Corporation, All rights reserved. 10 Creating and Managing Tables.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
Chapter 2 Views. Objectives ◦ Create simple and complex views ◦ Creating a view with a check constraint ◦ Retrieve data from views ◦ Data manipulation.
SQL: Part 1 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
SQL: Part 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
Manipulating Data. Objectives After completing this lesson, you should be able to do the following: Describe each DML statement Insert rows into a table.
9 Manipulating Data. 9-2 Objectives At the end of this lesson, you should be able to: Describe each DML statement Insert rows into a table Update rows.
Copyright  Oracle Corporation, All rights reserved. 12 Creating Views.
An Introduction To SQL Part 2 (Special thanks to Geoff Leese)
1 Information Retrieval and Use (IRU) An Introduction To SQL Part 2.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
Oracle CONNECT BY function JAVA WEB Programming. Emp 테이블의 내용 ( 상 / 하급자 계층구조 ) SQL> select * from emp; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
2-1 Limiting Rows Using a Selection “…retrieve all employees in department 10” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER.
Creating and Managing Tables 14. ObjectivesObjectives After completing this lesson, you should be able to do the following: After completing this lesson,
Creating Views Database Systems Objectives Explain the concept of a view. Create simple and complex views. Retrieve data through a view. Alter the.
Copyright س Oracle Corporation, All rights reserved. 12 Creating Views.
CSCI N311: Oracle Database Programming 5-1 Chapter 15: Changing Data: insert, update, delete Insert Rollback Commit Update Delete Insert Statement –Allows.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
SQL Statements SELECT INSERTUPDATEDELETECREATEALTERDROPRENAMETRUNCATECOMMITROLLBACKSAVEPOINTGRANTREVOKE Data Retrieval Language (DRL) Data Retrieval Language.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Relational Normalization Theory
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Creating Views Schedule: Timing Topic 20 minutes Lecture
Creating Other Schema Objects
Manipulating Data Schedule: Timing Topic 40 minutes Lecture
What Is a View? EMPNO ENAME JOB EMP Table EMPVU10 View
Chapter 2 Views.
(SQL) Manipulating Data
Chapter 2 Views.
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Restricting and Sorting Data
IST 318 Database Administration
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

SQL: Part 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute. Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute.

2 OUTLINE  Views  Cursors  Triggers  Views  Cursors  Triggers

Views

4 Database Objects Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object Object Table View Sequence Index Synonym

5 What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV BLAKE MANAGER MAY CLARK MANAGER JUN JONES MANAGER APR MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB FORD ANALYST DEC SMITH CLERK DEC SCOTT ANALYST DEC ADAMS CLERK JAN MILLER CLERK JAN EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV BLAKE MANAGER MAY CLARK MANAGER JUN JONES MANAGER APR MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB FORD ANALYST DEC SMITH CLERK DEC SCOTT ANALYST DEC ADAMS CLERK JAN MILLER CLERK JAN EMP Table EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV CLARK MANAGER JUN MILLER CLERK JAN JONES MANAGER APR SCOTT ANALYST DEC ADAMS CLERK JAN SMITH CLERK DEC FORD ANALYST DEC BLAKE MANAGER MAY MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV CLARK MANAGER JUN MILLER CLERK JAN JONES MANAGER APR SCOTT ANALYST DEC ADAMS CLERK JAN SMITH CLERK DEC FORD ANALYST DEC BLAKE MANAGER MAY MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB EMPNO ENAME JOB KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK EMPVU10 View EMPVU10 View

6 Why Use Views? To restrict database access To make complex queries easy To allow data independence To present different views of the same data To restrict database access To make complex queries easy To allow data independence To present different views of the same data

7 Simple vs. Complex Views FeatureSimple ViewsComplex Views Number of tablesOneOne or more Contain functionsNoYes Contain groups of dataNoYes DML through viewYesNot always FeatureSimple ViewsComplex Views Number of tablesOneOne or more Contain functionsNoYes Contain groups of dataNoYes DML through viewYesNot always

8 Creating a View You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. You embed a subquery within the CREATE VIEW statement. The subquery can contain complex SELECT syntax. The subquery cannot contain an ORDER BY clause. CREATE [OR ALTER] VIEW view [(alias[, alias]...)] [WITH ENCRYPTION] AS subquery [WITH CHECK OPTION] CREATE [OR ALTER] VIEW view [(alias[, alias]...)] [WITH ENCRYPTION] AS subquery [WITH CHECK OPTION]

9 Creating a View Create a view, EMPVU10, that contains details of employees in department 10. SQL> CREATE VIEW empvu10 2 AS SELECTempno, ename, job 3 FROMemp 4 WHEREdeptno = 10 View created.

10 Creating a View Create a view by using column aliases in the sub-query. Select the columns from this view by the given alias names. Create a view by using column aliases in the sub-query. Select the columns from this view by the given alias names. SQL> CREATE VIEW salvu30 2 AS SELECTempno EMPLOYEE_NUMBER, ename NAME, 3sal SALARY 4 FROMemp 5 WHEREdeptno = 30 View created.

11 Retrieving Data from a View EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. SQL> SELECT * 2 FROMsalvu30

12 Creating a Complex View Create a complex view that contains group functions to display values from two tables. SQL> CREATE VIEWdept_sum_vu 2 (name, minsal, maxsal, avgsal) 3 AS SELECTd.dname, MIN(e.sal), MAX(e.sal), 4AVG(e.sal) 5 FROMemp e, dept d 6 WHEREe.deptno = d.deptno 7 GROUP BY d.dname View created.

13 Rules for Performing DML Operations on a View You can perform DML operations on simple views. You cannot remove a row if the view contains the following: – Group functions – A GROUP BY clause – The DISTINCT keyword You can perform DML operations on simple views. You cannot remove a row if the view contains the following: – Group functions – A GROUP BY clause – The DISTINCT keyword

14 Rules for Performing DML Operations on a View You cannot modify data in a view if it contains: – Any of the conditions mentioned in the previous slide – Columns defined by expressions – The ROWNUM pseudocolumn You cannot add data if: – The view contains any of the conditions mentioned above or in the previous slide – There are NOT NULL columns in the base tables that are not selected by the view You cannot modify data in a view if it contains: – Any of the conditions mentioned in the previous slide – Columns defined by expressions – The ROWNUM pseudocolumn You cannot add data if: – The view contains any of the conditions mentioned above or in the previous slide – There are NOT NULL columns in the base tables that are not selected by the view

15 Removing a View Remove a view without losing data because a view is based on underlying tables in the database. SQL> DROP VIEW empvu10 View dropped. DROP VIEW view

16 Summary A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data

Cursors

18 Using Cursors Cursors provide a “handle” on query results for further processing; you need to Cursors provide a “handle” on query results for further processing; you need to – DECLARE the cursor with the SELECT statement –OPEN the cursor –FETCH rows from the cursor –USE the rows –CLOSE the cursor –DEALLOCATE the cursor Cursors provide a “handle” on query results for further processing; you need to Cursors provide a “handle” on query results for further processing; you need to – DECLARE the cursor with the SELECT statement –OPEN the cursor –FETCH rows from the cursor –USE the rows –CLOSE the cursor –DEALLOCATE the cursor

19 General Syntax for Cursors DECLARE cursorname CURSOR DECLARE cursorname CURSOR FOR SELECT column FROM table [condition] OPEN cursorname FETCH NEXT FROM cursorname INTO variable USE (The values in the variable can now be used) CLOSE cursorname DEALLOCATE cursorname DECLARE cursorname CURSOR DECLARE cursorname CURSOR FOR SELECT column FROM table [condition] OPEN cursorname FETCH NEXT FROM cursorname INTO variable USE (The values in the variable can now be used) CLOSE cursorname DEALLOCATE cursorname

20 Example 1 declare top_emp cursor for select FirstName+" "+LastName from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 open top_emp char(20) fetch next from top_emp declare top_emp cursor for select FirstName+" "+LastName from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 open top_emp char(20) fetch next from top_emp

21 Example (contd.) print "Employees with Sales > 100" print " " while begin fetch next from top_emp end close top_emp deallocate top_emp print "Employees with Sales > 100" print " " while begin fetch next from top_emp end close top_emp deallocate top_emp

22 Results Equivalent To select FirstName+" "+LastName [Employees with Sales > 100] from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100 select FirstName+" "+LastName [Employees with Sales > 100] from Employees inner join Orders on Orders.EmployeeID=Employees.EmployeeID group by FirstName, LastName having count(OrderID)>100

Triggers

24 Triggers Defines an action to be taken when a specified event occurs Defines an action to be taken when a specified event occurs Events Events –INSERT –UPDATE –DELETE Defines an action to be taken when a specified event occurs Defines an action to be taken when a specified event occurs Events Events –INSERT –UPDATE –DELETE

25 Triggers: How They Work When an INSERT trigger occurs, a temporary INSERTED table is created When an INSERT trigger occurs, a temporary INSERTED table is created When a DELETE trigger occurs, a temporary DELETED table is created When a DELETE trigger occurs, a temporary DELETED table is created These tables may be accessed by the trigger UPDATE triggers work via UPDATE triggers work via IF UPDATE(column) When an INSERT trigger occurs, a temporary INSERTED table is created When an INSERT trigger occurs, a temporary INSERTED table is created When a DELETE trigger occurs, a temporary DELETED table is created When a DELETE trigger occurs, a temporary DELETED table is created These tables may be accessed by the trigger UPDATE triggers work via UPDATE triggers work via IF UPDATE(column)

26 Triggers: Limits on Syntax Cannot contain the following statements CREATE, ALTER, DROP GRANT, REVOKE, DENY LOAD and RESTORE RECONFIGURE TRUNCATE TABLE UPDATE STATISTICS SELECT INTO (because it creates a table) Cannot contain the following statements CREATE, ALTER, DROP GRANT, REVOKE, DENY LOAD and RESTORE RECONFIGURE TRUNCATE TABLE UPDATE STATISTICS SELECT INTO (because it creates a table)

27 Triggers: Syntax CREATE TRIGGER triggername ON table [WITH ENCRYPTION] FOR [DELETE|INSERT|UPDATE] [WITH APPEND] [NOT FOR REPLICATION] AS sqlstatement[, …n] CREATE TRIGGER triggername ON table [WITH ENCRYPTION] FOR [DELETE|INSERT|UPDATE] [WITH APPEND] [NOT FOR REPLICATION] AS sqlstatement[, …n]

28 Triggers: An Example (This trigger prompts the order clerk to award first time customers a 10% discount.) create trigger InsertCustomerOrders on Orders for insert ‑‑ Triggering event as char(30) CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID) if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1 begin print 'This is first order placed by ' print 'This is first order placed by ' print 'Please give this customer a 10% discount on all purchases made today.' print 'Please give this customer a 10% discount on all purchases made today.'end (This trigger prompts the order clerk to award first time customers a 10% discount.) create trigger InsertCustomerOrders on Orders for insert ‑‑ Triggering event as char(30) CompanyName from Customers inner join Inserted on Customers.CustomerID=Inserted.CustomerID) if (select count(p.CustomerID) from Orders p inner join inserted i on p.CustomerID=i.CustomerID)=1 begin print 'This is first order placed by ' print 'This is first order placed by ' print 'Please give this customer a 10% discount on all purchases made today.' print 'Please give this customer a 10% discount on all purchases made today.'end

29 Invoking the Insert Trigger Doing the following: insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, ) Will result in: This is first order placed by University. Please give this customer a 10% discount on all purchases made today. Doing the following: insert into Orders (CustomerID, EmployeeID, OrderDate) values (‘OU', 4, ) Will result in: This is first order placed by University. Please give this customer a 10% discount on all purchases made today.

30 A Delete Trigger (This trigger automatically increments the inventory in the Products table when an order is cancelled.) create trigger DeleteOrders on [Order Details] for delete as smallint p.UnitsInStock from Products p inner join Deleted d on p.ProductID=d.ProductID) d.Quantity from Deleted d) set ProductID from deleted) (This trigger automatically increments the inventory in the Products table when an order is cancelled.) create trigger DeleteOrders on [Order Details] for delete as smallint p.UnitsInStock from Products p inner join Deleted d on p.ProductID=d.ProductID) d.Quantity from Deleted d) set ProductID from deleted)

31 Delete Trigger (contd.) begin update Products set where print 'Updating inventory for print 'Initial units in stock print 'Restoring from cancelled order' print 'Current units in stock endbegin update Products set where print 'Updating inventory for print 'Initial units in stock print 'Restoring from cancelled order' print 'Current units in stock end

32 Invoking the Delete Trigger Doing the following: delete from [Order Details] where OrderID=11084 Will result in: Updating inventory for 11 Initial units in stock 65 Restoring 15 from cancelled order Current units in stock 80 Doing the following: delete from [Order Details] where OrderID=11084 Will result in: Updating inventory for 11 Initial units in stock 65 Restoring 15 from cancelled order Current units in stock 80

33 Another Insert Trigger This trigger implements a new business rule requiring all order quantities to exceed 5 units. create trigger InsertOrderDetail on [Order Details] for insert as if (select Quantity from Inserted)<5 begin print 'This is a wholesale business.' print 'All order quantities must be at least 5 units. ' rollback transaction end This trigger implements a new business rule requiring all order quantities to exceed 5 units. create trigger InsertOrderDetail on [Order Details] for insert as if (select Quantity from Inserted)<5 begin print 'This is a wholesale business.' print 'All order quantities must be at least 5 units. ' rollback transaction end

34 Invoking the Trigger Doing the following: insert into [order details] values (11084, 11, 14, 2, 0) Will result in: The following being displayed: This is a wholesale business. All order quantities must be at least 5 units. Order Details table – No record added Doing the following: insert into [order details] values (11084, 11, 14, 2, 0) Will result in: The following being displayed: This is a wholesale business. All order quantities must be at least 5 units. Order Details table – No record added

35 Viewing Information on Triggers Listing of trigger code SP_HELPTEXT triggername Listing objects referenced by trigger SP_DEPENDS triggername Listing triggers on a table SP_HELPTRIGGER tablename Listing of trigger code SP_HELPTEXT triggername Listing objects referenced by trigger SP_DEPENDS triggername Listing triggers on a table SP_HELPTRIGGER tablename