Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Training – Advanced Course (Oracle Database)

Similar presentations


Presentation on theme: "SQL Training – Advanced Course (Oracle Database)"— Presentation transcript:

1 SQL Training – Advanced Course (Oracle Database)
Duration: 1 Day Thursday

2 Greetings Instructor: Angelina Villa
Web page:

3 Schedule 8:00 am - 4:30pm Lab Sessions: 9:00 am, 1:00 pm, 3:00 pm
Lunch Break: 11:30-12:30 pm 10 minute breaks: 10:00 am, 2:30 pm

4 Goals of the Course Purpose: Using DDL Statements
Creating Schema Objects Advanced PL/SQL Scripting Techniques

5 Oracle DBMS

6 Logical Structures Tablespaces
A database is divided into logical storage units called tablespaces, which group related logical structures together. One or more datafiles are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. Oracle Data Blocks At the finest level of granularity, Oracle database data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk. The standard block size is specified by the DB_BLOCK_SIZE initialization parameter. Tablespaces A database is divided into logical storage units called tablespaces, which group related logical structures together. For example, tablespaces commonly group together all application objects to simplify some administrative operations. One or more datafiles are explicitly created for each tablespace to physically store the data of all logical structures in a tablespace. Every Oracle database contains a SYSTEM tablespace. Oracle creates them automatically when the database is created. Oracle Data Blocks At the finest level of granularity, Oracle database data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk. The standard block size is specified by the DB_BLOCK_SIZE initialization parameter. A database uses and allocates free database space in Oracle data blocks. Oracle reads and writes data in blocks, so a larger block size could lead to more data transfer per I/O call. The default block size depends on the system architecture, but is generally 8k for UNIX systems. A larger block size is sometimes used for data warehouse systems which access data in larger chunks.

7 Logical Structures (cont)
Schema Overview A schema is a collection of database objects. A schema is owned by a database user and has the same name as that user. Schema objects are the logical structures that directly refer to the database's data. Schema objects include structures like tables, views, and indexes. Schema Overview A schema is a collection of database objects. A schema is owned by a database user and has the same name as that user. Schema objects are the logical structures that directly refer to the database's data. Schema objects include structures like tables, views, and indexes. There is no relationship between a tablespace and a schema. Objects in the same schema can be in different tablespaces, and a tablespace can hold objects from different schemas.

8 Oracle Instance An Oracle database server consists of: Oracle database
The combination of the background processes and memory buffers

9 Instances PGA is a memory buffer that contains data and control information for a server process. A server process is a process that services a client’s requests. A PGA is created by oracle when a server process is started. The information in a PGA depends on the oracle configuration. The PGA area is a non-shared area of memory created by oracle when a server process is started. The basic difference between SGA and PGA is that PGA cannot be shared between multiple processes in the sense that it is used only for requirements of a particular process whereas the SGA is used for the whole instance and it is shared.

10 Creating/Altering Objects

11 Database Objects

12 Database Objects

13 Schemas and Tablespaces

14 Schemas and Tablespaces

15 Data Concepts

16 Data Independence Logical Data Independence: The capacity to change the conceptual schema without having to change the external schemas and their application programs. Physical Data Independence: The capacity to change the internal schema without having to change the conceptual schema.

17 The Relational Database model
Developed by E.F. Codd, C.J. Date (70s) Table = Entity = Relation Table row = tuple = instance Table column = attribute Table linkage by values Entity-Relationship Model

18 The Relational Model Each attribute has a unique name within an entity
All entries in the column are examples of it Each row is unique Ordering of rows and columns is unimportant Each position (tuple) is limited to a single entry.

19 Structured Query Language (SQL)
Data Control (DCL) Grant Revoke User Privileges Data Definition (DDL) Create Alter Drop Tables, Views, Constraints Data Manipulation (DML) Select Insert Update Delete Retrieve and Manipulate Data

20 SQL Style Guidelines Some recommendations:
¤ Use lowercase names for tables, columns, etc. ¤ Put a descriptive comment above every table ¤ Write all SQL keywords in uppercase ¤ Follow standard indentation scheme e.g. indent columns in table declarations by 2-4 spaces ¤ Keep lines to 80 characters or less! wrap lines in reasonable places

21 SQL Database Objects A SQL Server database has lot of objects like
Tables Views Stored Procedures Functions Rules Defaults Cursors Triggers

22 Managing Objects Object Definition Creating Objects Altering Objects
Dropping Objects MetaData Object Permissions

23 Data Definition Language (DDL)

24 Data Definition Commands
These commands alter the structure of a database CREATE create a Table, Index, or Database ALTER modify structure of a Database or Table DROP delete an entire Table, Index, or Database RENAME rename a Table

25 Creating Objects CREATE Statement Example: CREATE TABLE customers(
customerID int identity, customer varchar(50) )

26 Alter statements Used to modify table structure Add new column
Change data type of existing column Delete a column Add or remove constraints like foreign key, primary key Add new column: Alter table test add grade char(1); Modify a column data type: Alter table test alter column grade varchar(10); Delete a column: Alter table test drop column grade;

27 Altering Objects ALTER Statement
Example: “Alter a table column to not allow null values.” UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL; ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL;

28 Altering Objects (cont)
ALTER Statement Example: “Add a customer phone number to the table” ALTER TABLE customers ADD customerPhone varchar(40);

29 Dropping Objects DROP Statement Example: DROP TABLE customers;

30 DROP Statement Destroys object forever Object can not be in use
Examples: DROP TABLE Customers DROP PROC pr_salesreport

31 Truncate statement TRUNCATE TABLE tablename
Removes all rows in a table Resets the table Truncate does the following, where as delete statement does not Releases the memory used Resets the identity value Does not invoke delete trigger

32 How the Programmer Sees the DBMS
Start with DDL to create tables: Continue with DML to populate tables: CREATE TABLE Students ( Name CHAR(30) SSN CHAR(9) PRIMARY KEY NOT NULL, Category CHAR(20) ) INSERT INTO Students VALUES(‘Charles’, ‘ ’, ‘undergraduate’)

33 Constraints

34 Constraint Types Domain Entity Referential Integrity

35 Constraints on a Single Relation
not null unique  primary key  check (P ), where P is a predicate

36 Not Null Constraint CREATE TABLE account ( acct_id CHAR(10) not null,
branch_name CHAR(20) not null, balance NUMERIC(12, 2) );

37 Unique Constraint CREATE TABLE account ( acct_id CHAR(10),
branch_name CHAR(20), balance NUMERIC(12, 2), unique(acct_id, branch_name) ); The unique specification states that the attributes acct_id and branch_name form a candidate key. Candidate keys are permitted to be null (in contrast to primary keys).

38 Referential Integrity
Ensures that a value that appears in one relation for a given set of attributes also appears for a set of attributes in another relation. The primary key clause lists primary key (PK) attributes. The unique key clause lists candidate key attributes The foreign key clause lists foreign key (FK) attributes and the name of the relation referenced by the FK. By default, a FK references PK attributes of the referenced table.

39 Relational Database Management System (RDBMS)
Name Address Parcel # John Smith 18 Lawyers Dr T. Brown 14 Summers Tr Table A Table B Parcel # Assessed Value ,000 ,000

40 Database Table Keys Definition:
A key of a relation is a subset of attributes with the following attributes: Unique identification Non-redundancy

41 Types of Keys PRIMARY KEY FOREIGN KEY
Serves as the row level addressing mechanism in the relational database model. It can be formed through the combination of several items. Indicates uniqueness within records or rows in a table. FOREIGN KEY A column or set of columns within a table that are required to match those of a primary key of a second table. the primary key is the only way join relationships can be established.

42 Primary Key Constraint
CREATE TABLE account ( acct_id CHAR(10), branch_name CHAR(20), balance NUMERIC(12, 2), PRIMARY KEY (acct_id) ); ¤ Database won’t allow two rows with same account ID

43 Primary Key Constraint (cont)
A primary key can have multiple attributes CREATE TABLE depositor ( customer_name VARCHAR(30), acct_id CHAR(10), PRIMARY KEY (customer_name, acct_id) ); ¤ Necessary because SQL tables are multisets A table cannot have multiple primary keys

44 Foreign Key Constraint
CREATE TABLE location ( l_number INT PRIMARY KEY, l_name CHAR(200) ); CREATE TABLE department ( d_name CHAR(200), d_number INT PRIMARY KEY d_location REFERENCES location(l_number)

45 Enforcing Foreign Keys
If there is a foreign-key constraint from attributes of relation Department to a key of relation Location, two violations are possible: An insert or update to Department introduces values not found in Location. A deletion or update to Location causes some tuples of Department to “dangle.”

46 Handling Violations Default : Reject the modification.
Cascade : Make the same changes in department. Deleted Location : delete department tuple. Updated Location : change values in department. Set NULL : Change the department location to NULL.

47 Choosing a Policy When we declare a foreign key, we may choose policies SET NULL or CASCADE independently for deletions and updates. Follow the foreign-key declaration by: ON [UPDATE, DELETE][SET NULL CASCADE] Two such clauses may be used. Otherwise, the default (reject) is used.

48 Foreign Key Example CREATE TABLE department ( d_name CHAR(200),
d_number INT PRIMARY KEY); CREATE TABLE locations ( l_number INT l_locations CHAR(200), FOREIGN KEY (l_department) REFERENCES department(d_number) ON DELETE SET NULL ON UPDATE CASCADE);

49 Attribute Constraints
Constraints on the value of a particular attribute. Add: CHECK( <condition> ) to the declaration for the attribute. The condition may use the name of the attribute, but any other relation or attribute name must be in a subquery.

50 Check Constraint CREATE TABLE paycheck ( checkno INT, ename CHAR(20),
amount FLOAT, CHECK ( ename IN (SELECT name FROM employee)), CHECK ( amount >= 0.00 ) );

51 Timing of Checks Attribute-based checks performed only when a values are inserted or updated. Example: CHECK (amount >= 0.00) checks new amount and rejects the modification if the amount is not a defined positive value. CHECK (ename IN (SELECT name FROM Employee)) not checked if a name is deleted from Employee (unlike foreign-keys).

52 Assertions An assertion is a predicate expressing a condition that we wish the database always to satisfy. create assertion <assertion-name> check <predicate>  When an assertion is made, the system tests it for validity, and tests it again on every update that may violate the assertion may introduce a significant amount of overhead;  Asserting for all X, P(X) is achieved in a round-about fashion using not exists X such that not P(X)

53 Assertion Example “Every loan has at least one borrower who maintains an account with a minimum balance or $ ” CREATE ASSERTION balance_constraint CHECK (NOT EXISTS (SELECT * FROM loan WHERE NOT EXISTS (SELECT * FROM borrower, depositor, account WHERE loan.loan_number = borrower.loan_number AND borrower.customer_name = depositor.customer_name AND depositor.account_number = account.account_number AND account.balance >= 1000)))

54 Assertion Example 2 “The salary of an employee must not be greater than the salary of the manager of the department that the employee works for’’ CREAT ASSERTION SALARY_CONSTRAINT CHECK (NOT EXISTS (SELECT * FROM employee e, employee m, department d WHERE e.salary > m.salary AND e.dno =d.number AND d.mgrssn = m.ssn))

55 Views

56 Defining Views Views are relations, except that they are not physically stored. For presenting different information to different users Employee(ssn, name, department, project, salary) Payroll has access to employee, others only to developers CREATE VIEW developer AS SELECT name, project FROM employee WHERE department = “Development”

57 A Different View Person(name, city)
Purchase(buyer, seller, product, store) Product(name, maker, category) We have a new virtual table: Seattle-view(buyer, seller, product, store) CREATE VIEW Seattle-view AS SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer

58 A Different View We can later use the view: SELECT name, store
FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes”

59 What Happens When We Query a View ?
SELECT name, Seattle-view.store FROM Seattle-view, Product WHERE Seattle-view.product = Product.name AND Product.category = “shoes” SELECT name, Purchase.store FROM Person, Purchase, Product WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer AND Purchase.poduct = Product.name AND Product.category = “shoes”

60 Types of Views Virtual views: Materialized views Used in databases
Computed only on-demand – slower at runtime Always up to date Materialized views Used in data warehouses Precomputed offline – faster at runtime May have stale data

61 Updating Views How can I insert a tuple into a table that doesn’t exist? Employee(ssn, name, department, project, salary) CREATE VIEW Developers AS SELECT name, project FROM Employee WHERE department = “Development” If we make the following insertion: INSERT INTO Developers VALUES(“Joe”, “Optimizer”) INSERT INTO Employee VALUES(NULL, “Joe”, NULL, “Optimizer”, NULL) It becomes:

62 Non-Updatable Views CREATE VIEW Seattle-view AS
SELECT seller, product, store FROM Person, Purchase WHERE Person.city = “Seattle” AND Person.name = Purchase.buyer How can we add the following tuple to the view? (“Joe”, “Shoe Model 12345”, “Nine West”) We need to add “Joe” to Person first, but we don’t have all its attributes

63 Answering Queries Using Views
What if we want to use a set of views to answer a query. Why? The obvious reason… Answering queries over web data sources.

64 Reusing a Materialized View
Suppose I have only the result of SeattleView: SELECT buyer, seller, product, store FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer and I want to answer the query SELECT buyer, seller Person.per-name = Purchase.buyer AND Purchase.product=‘gizmo’. Then, I can rewrite the query using the view.

65 Query Rewriting Using Views
Rewritten query: SELECT buyer, seller FROM SeattleView WHERE product= ‘gizmo’ Original query: FROM Person, Purchase WHERE Person.city = ‘Seattle’ AND Person.per-name = Purchase.buyer AND Purchase.product=‘gizmo’.

66 Sequences

67 Sequences This creates an auto increment for a column
If a table has a column with sequence or auto increment, the user need not insert data explicitly for the column Sequence is implemented using the concept of Identity

68 Identity Identity(1,2) Identity has
A seed: initial value An increment: value by which we skip to fetch next value Identity(1,2) will generate sequence numbers 1,3,5,7…

69 Identity (cont) CREATE TABLE table1 ( id integer identity(1,1),
name varchar(10) ) It is enough if we insert like this: INSERT INTO table1(name) VALUES(‘Ram’); Ram will automatically assigned value 1 for id

70 Indexing

71 Table Indexing An Index is a means of expediting the retrieval of data. Indexes are “built” on a column(s). Indexes occupy disk space; occasionally a lot. Indexes aren’t technically necessary for operation and must be maintained by the database administrator.

72 Table Indexing An Index is a means of expediting the retrieval of data. Indexes are “built” on a column(s). Indexes occupy disk space; occasionally a lot. Indexes aren’t technically necessary for operation and must be maintained by the database administrator.

73 Index-Organized Tables
Regular table access IOT access Table access by ROWID Non-key columns Index-Organized Tables Unlike an ordinary (heap-organized) table whose data is stored as an unordered collection (heap), data for an index-organized table (IOT) is stored in a B-tree index structure in a primary key–sorted manner. Besides storing the primary key column values, each index entry in the IOT B-tree stores the non-key column values as well. Index-organized tables have full table functionality. They support features such as constraints, triggers, LOB and object columns, partitioning, parallel operations, online reorganization, and replication. You can even create indexes on an index-organized table. Index-organized tables are ideal for OLTP applications, which require fast primary key access and high availability. Queries and DML on an orders table used in online order processing are predominantly primary-key based, and a heavy volume of DML causes fragmentation that results in a frequent need to reorganize. Because an index-organized table can be reorganized online and without invalidating its secondary indexes, the window of unavailability is greatly reduced or eliminated. An index-organized table is an alternative to: A table indexed on the primary key by using the CREATE INDEX statement A cluster table stored in an indexed cluster, which has been created using the CREATE CLUSTER statement that maps the primary key for the table to the cluster key Key column Row header Oracle Database 10g: Administration Workshop II

74 Index Types Clustered index Non-Clustered Index
Controls the physical order of rows Does not require disk space One per table (may inc. multiple columns) Created by default on tables’ Primary Key column Non-Clustered Index Physical data structures that facilitate data retrieval Can have many indexes Indexes may include many columns

75

76 Index CREATE INDEX indexname ON tablename(columnname)
This creates a non clustered index on a table CREATE UNIQUE CLUSTERED INDEX index_name ON Student(sname); This creates a unique and clustered index on the Column Sname.

77 Indexes Create an index on name:
B+ trees have fan-out of 100s: max 4 levels ! Adam Betty Charles …. Smith

78 B-Tree Index Example Commonly used with “attribute” tables as well as “graphic-attribute” tables (CAD data structures) Binary coding reduces the search list by streaming down the “tree”. A “balanced” tree is best. 37 12 49 59 19 44 3 Number High Low Primary Key #

79 Clusters Unclustered orders and order_item tables
ORD_NO PROD QTY 101 A 102 A 102 G 102 N 101 A 101 W Cluster Key (ORD_NO) 101 ORD_DT CUST_CD 05-JAN-97 R01 PROD QTY A A W ORD_DT CUST_CD 07-JAN-97 N45 A G N ORD_NO ORD_DT CUST_CD JAN R01 JAN N45 Definition of Clusters A cluster is a group of one or more tables that share the same data blocks because they share common columns and are often used together in join queries. Storing tables in clusters offers the DBA a method to denormalize data. If you implement clustered tables in your database, you do not need to change any application code that accesses the tables. Clusters are transparent to the end user and programmer. Performance Benefits of Clusters Disk I/O is reduced and access time improved for joins of clustered tables. Each cluster key value is stored only once for all the rows of the same key value; therefore, it uses less storage space. Performance Consideration Full table scans are generally slower on clustered tables than on nonclustered tables. Unclustered orders and order_item tables Clustered orders and order_item tables Oracle Database 10g: Administration Workshop II

80 Cluster Types Hash cluster Sorted hash cluster Index cluster
Hash function Hash function 1 2 3 Cluster Types Index Clusters An index cluster uses an index, known as the cluster index, to maintain the data within the cluster. The cluster index must be available to store, access, or maintain data in an index cluster. The cluster index is used to point to the block that contains the rows with a given key value. The structure of a cluster index is similar to that of a normal index. Although a normal index does not store null key values, cluster indexes store null keys. There is only one entry for each key value in the cluster index. Therefore, a cluster index is likely to be smaller than a normal index on the same set of key values. Hash Clusters A hash cluster uses a hash algorithm (either user-defined or system-generated) to calculate the location of a row, both for retrieval and for DML operations. For equality searches that use the cluster key, a hash cluster can provide greater performance gains than an index cluster because there is only one segment to scan (no index access is needed). Oracle Database 10g: Administration Workshop II

81 Sorted Hash Cluster SIZE Cluster key 1 Block chain starting points
HASHKEYS Cluster key n Rows sorted by sort key in each block chain Sorted Hash Cluster: Basic Architecture In the example in the previous slide, only one table is stored in the sorted hash cluster. Also, the hash function is very simple and no collision is expected. This is because the hash function is determined by the cluster key itself, and each cluster key value is unique. Basically, HASHKEYS represents the number of different originating telephone numbers, and SIZE represents the number of bytes used to store each cluster key metadata. As you can see, the first part of the sorted hash cluster segment is reserved to store the metadata entries. Each metadata entry contains a link to the list of its corresponding rows. Each list is made up of a series of Oracle blocks that are linked together. Each list is sorted according to the sort key columns. Whenever you want to retrieve the rows for a corresponding cluster key value, the cluster key value is hashed to its metadata entry location, which gives the sorted list of rows that you are selecting. Oracle Database 10g: Administration Workshop II

82 Indexing Overview Index Considerations Best Practices Scenarios:
Can dramatically increase query performance Adds overhead for index maintenance Best Practices Base design on real-world workloads Scenarios: Retrieving ranges of data Retrieving specific values

83 Synonyms

84 Synonyms Allows an alias for :
table, view, sequence, procedure, stored function, package, materialized view, Java class schema object, user-defined object type, or another synonym. New CREATE SYNONYM syntax

85 Create Synonym

86 Synonym USE tempdb; GO CREATE SYNONYM MyEmployee
FOR Mydb.HumanResources.Employee; SELECT OBJECTPROPERTYEX(OBJECT_ID('MyEmployee'), 'BaseType') AS BaseType;

87 Public and Private Synonyms
To create a private synonym in your own schema, you must have the CREATE SYNONYM system privilege. To create a private synonym in another user's schema, you must have the CREATE ANY SYNONYM system privilege. To create a PUBLIC synonym, you must have the CREATE PUBLIC SYNONYM system privilege.

88 Public Synonyms Public synonyms are accessible to all users.
If dependent tables or dependent valid user- defined object types exist, then you cannot create object of the same name as the synonym in schema. Do not to create a public synonym with the same name as an existing schema. PL/SQL units that use that name will be invalidated.

89 Public Synonyms (cont)
CREATE PUBLIC SYNONYM customers FOR oe.customers; If the user sh issues the following statement, then the database returns the count of rows from sh.customers: SELECT COUNT(*) FROM customers;

90 Public Synonyms (cont)
CREATE PUBLIC SYNONYM customers FOR oe.customers; If the user sh issues the following statement, then the database returns the count of rows from sh.customers: SELECT COUNT(*) FROM customers;

91 Public Synonyms (cont)
To retrieve the count of rows from oe.customers, (The user sh must have select permission on oe.customers as well.) SELECT COUNT(*) FROM oe.customers; If the user hr's schema does not contain an object named customers, and if hr has select permission on oe.customers: SELECT COUNT(*) FROM customers;

92 Triggers Associated with a particular table
Automatically executed when a particular event occurs Insert Update Delete Others

93 Triggers vs. Procedures
Procedures are explicitly executed by a user or application Triggers are implicitly executed (fired) when the triggering event occurs Triggers should not be used as a lazy way to invoke a procedure as they are fired every time the event occurs

94 Triggers

95 Triggers The trigger specification names the trigger and indicates when it will fire The trigger body contains the PL/SQL code to accomplish whatever task(s) need to be performed

96 Triggers

97 Triggers Timing A triggers timing has to be specified first
Before (most common) Trigger should be fired before the operation i.e. before an insert After Trigger should be fired after the operation i.e. after a delete is performed

98 Trigger Events Three types of events are available DML events
DDL events Database events

99 Trigger Level Two levels for Triggers Row-level trigger
Requires FOR EACH ROW clause If operation affects multiple rows, trigger fires once for each row affected Statement-level trigger DML triggers should be row-level DDL and Database triggers should not be row-level

100 Event Examples

101 Triggers Conditions Available So Multiple Operations Can Be Dealt With In Same Trigger Inserting, Updating, Deleting Column Prefixes Allow Identification Of Value Changes New, Old

102 PL/SQL

103 PL/SQL Features Tight integration with SQL Increased performance
Supports data types, functions, pseudo-columns, etc. Increased performance A block of statements sent as a single statement Increased productivity Same techniques can be used with most Oracle products Portability Works on any Oracle platform Tighter security Users may access database objects without granted privileges

104 PL/SQL Program Structure
DECLARE Variable declarations BEGIN Program statements EXCEPTION Error-handling statements END; Variable Declarations Body Exception Section

105 PL/SQL Program Structure (cont)
Execution section Required Comment statements for multi-line comments /* between */ for single line comments - - after /* Script: Student register Purpose: to enroll students in class */ -- Script: Student register -- Purpose: to enroll students 105

106 PL/SQL Program Structure (cont)
106

107 PL/SQL Program Lines May span multiple text editor lines
Each line ends with a semicolon Text is not case sensitive

108 PL/SQL Variables Variables are local to the code block
Names can be up to 30 characters long and must begin with a character Declaration is like that in a table Name then data type the semi-colon Can be initialized using := operator in the declaration Can be changed with := in the begin section Can use constraints Variables can be composite or collection types Multiple values of different or same type

109 Common PL/SQL Data Types
CHAR ( max_length ) VARCHAR2 ( max_length ) NUMBER ( precision, scale ) BINARY_INTEGER – more efficient than number RAW ( max_length ) DATE BOOLEAN (true, false, null) Also LONG, LONG RAW and LOB types but the capacity is usually less in PL/SQL than SQL

110 PL/SQL Variable Constraints
NOT NULL Can not be empty CONSTANT Can not be changed

111 PL/SQL Variables Examples
Age number; Last char ( 10 ); DVal Date := Sysdate; SID number not null; Adjust constant number := 1; CanLoop boolean := true

112 Composite Variables Data object made up of multiple individual data elements Composite variable data types include: RECORD (multiple scalar values similar to a table’s record) TABLE (tabular structure with multiple columns and rows) VARRAY (variable-sized array. Tabular structure that can expand or contract based on data values) A R R A Y 112

113 Reference Variables Directly reference specific database column or row
Assume data type of associated column or row %TYPE data declaration syntax: variable_name tablename.fieldname%TYPE; %ROWTYPE data declaration syntax: variable_name tablename%ROWTYPE; 113

114 Arithmetic Operators Parentheses are used to force PL/SQL interpreter to evaluate operations in a certain order total_hours_worked - 40 * over_time_rate (total_hours_worked – 40) * over_time_rate 114

115 Numeric Functions ABS(Number) CEILING(Number) FLOOR(Number)
Fetches the modulo value of a number CEILING(Number) Fetches the closest integer greater than the number FLOOR(Number) Fetches the closest integer smaller than the number EXP(Number) Fetches the exponent of a number

116 Data Type Conversion Functions
Implicit data conversions Interpreter automatically converts value from one data type to another If PL/SQL interpreter unable to implicitly convert value error occurs Explicit data conversions Convert variables to different data types Using data conversion functions 116

117 Data Type Conversion Functions (cont)
TO_DATE: character string to DATE TO_DATE(‘07/14/01’, ‘MM/DD/YY’); TO_NUMBER: character string to NUMBER TO_NUMBER(‘2’); TO_CHAR: NUMBER or DATE to character string TO_CHAR(2); TO_CHAR(SYSDATE, ‘MM/DD/YYYY HH:MI’);

118 Q: What is the final value of variable2?
Assignment Operation Assigns value to variable Operator: := Syntax: variable_name := value; String literal within single quotation mark DECLARE variable1 NUMBER := 0; variable2 NUMBER := 0; BEGIN variable2 := variable1 +1; END; Q: What is the final value of variable2? 118

119 Assignment Operation (cont)
String literal within single quotation mark Examples: current_s_first_name := ‘Tommy’; current_student_ID NUMBER := 1111; Result of adding a value to a NULL value is another NULL value DEFAULT keyword can be used instead of assignment operator current_grade NUMBER := DEFAULT; 119

120 NULL Values Until a value is assigned to a variable, the variable’s value is NULL Performing an operation on a NULL value always results in a NULL value Advice: Always initialize variable values

121 String Operations Concatenating Joining two separate strings
Operator: || (i.e. double bar) Syntax: new_string := string1 || string2; s_fullname := s_first || s_last; 121

122 String Operations (cont)
Parse Separate single string consisting of two data items separated by commas or spaces s_fullname := s_first ||‘ ’|| s_last; 122

123 String Operations (cont)
Variable Data type Value Bldg_code VARCHAR2 LH Room_num 101 Room_capacity NUMBER 150 room_message := bldg_code || ‘ Room ’ || room_num || ‘ has ’ || TO_CHAR(room_capacity) || ‘seats.’; Question: Write down the value of room_message after the above Assignment statement is executed. 123

124 Arithmetic Operators Example Result

125 String Functions LTRIM function RTRIM function
Remove blank leading spaces string := LTRIM(string_variable_name); RTRIM function Remove blank trailing spaces string := RTRIM(string_variable_name); 125

126 String Functions (cont)
DECLARE s_address CHAR(20) := ‘951 Rainbow Dr’; BEGIN s_address := RTRIM(s_address); END; Question: How many characters will be removed from the string assigned to the s_address variable when the RTRIM function in the avove PL/SQL block is executed 126

127 String Functions (cont)
LENGTH function syntax string_length := LENGTH(string_variable_name); Example: code_length AS NUMBER(3):= LENGTH(bldg_code); Question 1: What will be the value of code_length if bldg_code’s value is ‘CR’? Question 2: What will be the value of code_length if bldg_code’s value is ‘BUS ’? 127

128 String Functions (cont)
Modify case of character strings UPPER function syntax: string := UPPER(string_variable_name); LOWER function syntax string := LOWER(string_variable_name); INITCAP function syntax string := INITCAP(string_variable_name); Example: s_full_name := UPPER(s_full_name); 128

129 String Functions (cont)
INSTR function Searches string for specific substring Returns an integer representing starting position of the substring within the original string Syntax: start_position := INSTR(original_string, substring); Example: blank_position := INSTR(curr_course_no, ‘ ’); 129

130 String Functions (cont)
starting_position := INSTR(greet_messg,'Hello'); blank_position := INSTR(‘Sarah Miller’, ‘ ’);

131 String Functions (cont)
SUBSTR function Extracts specific number of characters from character string starting at given point. Syntax: extracted_string := SUBSTR(string_variable,starting_point, number_of_characters); Example: curr_dept := SUBSTR(curr_course_no, 1, 3); 131

132 String Question 1 Q1: Assuming that curr_course_no contains ‘MIS 4200’, what will be the value of curr_number when the following statement is executed? blank_space := INSTR(curr_course_no, ‘ ’); curr_number := SUBSTR(curr_course_no, (blank_space + 1), (LENGTH(curr_course_no) - blank_space)); 132

133 String Question 2 Q2: Assuming that curr_course_no contains ‘MIS 4200’, what will be the value of curr_dept when the following statement is executed? blank_space := INSTR(curr_course_no, ‘ ’); curr_dept := SUBSTR((curr_course_no, 1, (blank_space – 1)); 133

134 PL/SQL Comparison Operators

135 PL/SQL Selection Structures
IF/THEN IF/END IF: IF condition THEN program statements END IF; IF/ELSE/END IF: ELSE alternate program statements

136 PL/SQL Selection Structures (cont)
IF/ELSIF: IF condition1 THEN program statements; ELSIF condition2 THEN alternate program statements; ELSIF condition3 THEN . . . ELSE END IF;

137 Evaluating NULL Conditions in IF/THEN Structures
If a condition evaluates as NULL, then it is FALSE How can a condition evaluate as NULL? It uses a BOOLEAN variable that has not been initialized It uses any other variable that has not been initialized

138 PL/SQL Loops Loop: repeats one or more program statements multiple times until an exit condition is reached Pretest loop: exit condition is tested before program statements are executed Posttest loop: exit condition is tested after program statements are executed

139 LOOP … EXIT Loop LOOP … EXIT LOOP program statements IF condition THEN
END IF; more program statements END LOOP; Pretest OR Posttest

140 LOOP … EXIT WHEN Loop LOOP program statements EXIT WHEN condition;
END LOOP; Posttest

141 WHILE Loop WHILE … LOOP WHILE condition LOOP program statements
END LOOP; Pretest WHILE … LOOP

142 Numeric FOR Loop FOR counter_variable IN start_value .. end_value LOOP
program statements END LOOP; Preset number of iterations

143 Using SQL Commands in PL/SQL Programs

144 Cursor

145 Cursor A pointer to memory location on database server Used to:
Retrieve and manipulate database data in PL/SQL programs Types: Implicit cursor Explicit cursor

146 Number of rows processed
Cursors Database Server Memory Cursor Number of rows processed Parsed command statement context area active set

147 Implicit Cursors Created automatically every time you use an INSERT, UPDATE, DELETE, or SELECT command Doesn’t need to be declared Can be used to assign the output of a SELECT command to one or more PL/SQL variables Can only be used if query returns one and only one record

148 Implicit Cursors (cont)
Context area A memory location created by INSERT, UPDATE, DELETE, or SELECT Contains information about query (# rows, etc.) Active set Set of data rows that query retrieves from SELECT Implicit cursor A pointer to the context area Used to assign output of SELECT query to PL/SQL program variables when query will return only one record* * Error occurs if query returns no records or more than one record

149 Implicit Cursors (cont)
To retrieve data using implicit cursor in PL/SQL, you add an INTO clause to the SELECT query SELECT field1, field2, ... INTO variable1, variable2, ... FROM table1, table2, ... WHERE join_conditions AND search_condition_to_retrieve_1_record; Variables must be declared in Declaration section Variables must have same data types as fields To avoid errors, %TYPE reference data type should be used

150 Explicit Cursors Retrieve and display data in PL/SQL programs for query that might: Retrieve multiple records Return no records at all Must explicitly write the code to: Declare cursor Open cursor Fetch data rows Close cursor

151 Explicit Cursors (cont)
Must be declared in program DECLARE section Can be used to assign the output of a SELECT command to one or more PL/SQL variables Can be used if query returns multiple records or no records

152 Explicit Cursors (cont)
Declare explicit cursor syntax: CURSOR cursor_name IS select_query; Open explicit cursor syntax: OPEN cursor_name; Fetch values using LOOP…EXIT WHEN loop: LOOP FETCH cursor_name INTO variable_name(s); EXIT WHEN cursor_name%NOTFOUND; Close cursor syntax: CLOSE cursor_name; Note: When the cursor is declared, system doesn’t check errors in the query. It creates the memory structure to store the active set. The PL/SQL interpreter checks for error and interprets the query when opening the cursor

153 Using an Explicit Cursor
Declare the cursor Open the cursor Fetch the cursor result into PL/SQL program variables Close the cursor

154 Declaring an Explicit Cursor
DECLARE CURSOR cursor_name IS SELECT_statement;

155 Opening an Explicit Cursor
OPEN cursor_name;

156 Fetching Explicit Cursor Records
FETCH cursor_name INTO variable_name(s);

157 Closing an Explicit Cursor
CLOSE cursor_name;

158 Processing an Explicit Cursor
LOOP ..EXIT WHEN approach: OPEN cursor_name; LOOP FETCH cursor_name INTO variable_name(s); EXIT WHEN cursor_name%NOTFOUND: END LOOP; CLOSE cursor_name;

159 Processing an Explicit Cursor (cont)
Cursor FOR Loop approach: FOR variable_name(s) in cursor_name LOOP additional processing statements; END LOOP;

160 Using Reference Data Types in Explicit Cursor Processing
Declaring a ROWTYPE reference variable: DECLARE reference_variable_name cursor_name%ROWTYPE; Referencing a ROWTYPE reference variable: reference_variable_name.database_field_name

161 Explicit Cursor Attributes

162 Error Handling

163 Runtime Errors in PL/SQL Programs
Occur when an exception (unwanted event) is raised Cause program to fail during execution Possible causes (exceptions): Division by zero - inserting incompatible data Constraint violation - retrieving 0/several rows with implicit cursor

164 Handling Runtime Errors in PL/SQL Programs
Exception handling Programmers place commands in EXCEPTION section Handle exception options Correct error without notifying user of problem Inform user of error without taking corrective action After exception handler executes Program ends DECLARE variable declarations BEGIN program statements EXCEPTION error-handling statements END;

165 Types of Errors in PL/SQL Programs
Handling error procedure depends the type of exception: Predefined exception undefined exception User-defined exception

166 Predefined Exceptions
Common errors that have been given predefined names that appear instead of error numbers

167 Exception Handler Syntax For Predefined Exceptions
WHEN exception1_name THEN exception handling statements; WHEN exception2_name THEN WHEN OTHERS THEN

168 Undefined Exceptions Less-common errors that have not been given predefined names ORA- error code appears Exception handler tests for ORA- error code and provides alternate error message

169 User-Defined Exceptions
Errors that will not cause a run-time error, but will violate business rules Programmer creates a custom error message

170 Nested PL/SQL Program Blocks
An inner program block can be nested within an outer program block DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; Outer block DECLARE variable declarations BEGIN program statements EXCEPTION error handling statements END; Inner block

171 Exception Handling in Nest Program Blocks
If an exception is raised and handled in an inner block, program execution resumes in the outer block

172 Exception Handling in Nested Program Blocks (cont)
DECLARE variable declarations BEGIN program statements additional program statements EXCEPTION error handling statements END; DECLARE exception_A BEGIN RAISE exception_A EXCEPTION exception_A error handler END; Exception is raised and handled in inner block Program execution resumes here

173 Exception Handling in Nested Program Blocks (cont)
Exceptions raised in inner blocks can be handled by exception handlers in outer blocks

174 Structure of Exception Section

175 Stored Procedures

176 Stored Procedures The first line is called the Procedure Specification
The remainder is the Procedure Body A procedure is compiled and loaded in the database as an object Procedures can have parameters passed to them

177 Stored Procedures Run a procedure with the PL/SQL EXECUTE command
Parameters are enclosed in parentheses

178 Stored Functions Like a procedure except they return a single value

179 PL/SQL Tables Key Value 1 Shadow 2 Dusty 3 Sassy
Data structure that contains multiple data items that are the same data type Each table item has a key and a value Key values do not need to be sequential Used to create a lookup table that is stored in memory to improve processing speed

180 PL/SQL Tables Key Value 1 Shadow 2 Dusty 3 Sassy
Data structure that contains multiple data items that are the same data type Each table item has a key and a value Key values do not need to be sequential Used to create a lookup table that is stored in memory to improve processing speed

181 PL/SQL Table of Records
PL/SQL table that can store multiple values that are referenced by a key Usually used to store database records that need to be processed by a PL/SQL program Improves performance by limiting number of database retrievals

182 Using SQL Commands in PL/SQL Programs

183 DML Events Changes to data in a table Insert Update Delete

184 Using SQL Queries Use SQL action query
Put query or command in PL/SQL program Use same syntax as the syntax used to execute query or command in SQL*Plus Can use variables instead of literal values like ‘Tammy’ To specify data values 184

185 Batching SQL and deferring fetching
Execute SQL queries in Stored Procedures Fetch as needed from the client You want to “batch SQL” – multiple SQL statements in one PL/SQL anonymous block Solution: Use REF CURSORS and Anonymous PL/SQL

186 REF Cursors Characteristics Advantages
Pointer to result set on server side Read only Forward only Advantages Input REF Cursor parameters Retrieve multiple REF Cursors in a single round trip

187 Anonymous PL/SQL Executes multiple SQL statements in a single batch
Saves DB round trips Execute as CommandType.Text Generate dynamically based on application requirements // C# string cmdtxt = "BEGIN " + "OPEN :1 for select * from emp where deptno = 10; " + "OPEN :2 for select * from dept where deptno = 20; " + "INSERT INTO DEPT VALUES (50, ‘IT', ‘SAN FRANCISCO');" + "END;";

188 Using Pre-Defined PL/SQL Packages
DB server provides PL/SQL packages to all of Oracle’s key functionality Can be used from ODP.NET, similar to any other PL/SQL call Sample pre-packaged functionality DBMS_AQ DBMS_OLAP DBMS_STREAMS SDO_GEOM

189 VARRAYs and NESTED TABLES
Newly supported in ODAC 11g Use Custom Class Code Generation wizard Check out code samples in directory <OH>\odp.net\samples\2.x\UDT MyVarrayCustomClass pa = new MyVarrayCustomClass(); pa.Array = new Int32[] { 1, 2, 3, 4 }; pa.StatusArray = new OracleUdtStatus[] { OracleUdtStatus.NotNull…. param.OracleDbType = OracleDbType.Array; param.Direction = ParameterDirection.Input; param.UdtTypeName = “MYVARRAY"; param.Value = pa;

190 Commands at Oracle SQL>
To list all commands: SQL>help index To list all tables: SELECT * FROM case; To display a table structure: DESCRIBE tableName To run a DOS command from Oracle: HOST DOSCommand Example: HOST dir 190

191 Creating SQL Command Batch File
Creating a batch file with .sql extension Syntax: SQL>Edit filename SQL>edit c:\batch1.sql Use START command to execute the batch SQL> START c:\batch1.sql See the batch file contents at SQL> SQL>host type c:\batch1.sql 191


Download ppt "SQL Training – Advanced Course (Oracle Database)"

Similar presentations


Ads by Google