oracle sql plsql
DESCRIPTION
SQL AND PLSQL PROGRAMMING DOCUMENTTRANSCRIPT
CHAPTER I
Contents
Chapter 1Introduction to RDBMS and ORACLE
7Approaches to Database Management
7Database Management An Evolutionary phenomenon
8Introduction to DBMS
8Concept of DBMS
9Database Models
11Characteristics of Relational Database Management System
11The 12 rules for an RDBMS ( Codds Rule )
11Information Representation
13Application Development Cycle
14Database Designing
15ER Diagram
16Degree of relationship
17Normalization
17Need for normalization
18Steps in normalization
18Invoice Management System
20Invoice Table
20Customer Table
21Oracle as an Object Oriented DBMS
22Features of Oracle
Chapter 2Introduction to SQL *Plus
25Introduction to SQL
25Oracle Data Types
29Starting SQL* Plus editor
31Operators and Expressions
34Querying DataBase Tables
39RollUp Operation Getting sub totals
39Cube Operation Getting cross tabs
Chapter 3Querying Multiple tables42Multiple Table Queries
42EQUI Join
42CARTESIAN Join
43OUTER Join
44SELF Join
45Using Set Operators
46Sub Queries
46Single-Row Sub Queries
47Multiple-Row Sub Queries
47Correlated Subqueries
48Using special operators in subquery
Chapter 4Functions51Functions
51Single Row Function
54Group Functions
Chapter 5Data Definition and Manipulation Language
57Data Definition Language
57Creating Tables
58Working with Constraints
61Creating a table with data from another table
62Maintaining Database Objects
62Alter Table
64The ENABLED/DISABLED Clause
64Dropping / Renaming Tables
65Truncating table
66Insert values into a table
66Inserting result of a query into a table
66Inserting through parameter substitution
67Updating columns of a table
67Deleting rows from a table
68Introduction to Views
68Creating a view
68Manipulating Data through Views
69Creating a join view
69Key-preserved table
70Rules for DML statements on Join View
71Dropping a view
71Working with Sequences
Chapter 6Data Control Language75DataBase Security and Privileges
75Grant Command
76Revoke Command
76Application Privilege Management
76Oracle provides three standard ROLEs:
76Commit and RollBack
77Implicit COMMIT
77Auto ROLLBACK
77Savepoint
Chapter 7Introduction to PL/SQL80Introduction to PL/SQL
80Advantages of PL/SQL
80PL/SQL Architecture
81PL/SQL Block Structure
81Named and Anonymous block
82Conditional and Iterative Control
82IF THEN
83IF THENELSE
83IF THENELSIF
84LOOPEND LOOP
85WHILELOOP
85FORLOOP
86SQL within PL/SQL
86Writing a PL/SQL code
87Composite Data Types
87PL/SQL Records
87Record Assignment
88PL/SQL TABLES
Chapter 8PL/SQL - II92Cursor Management in PL/SQL
92Implicit Cursor
92Explicit Cursor
92Using Cursor
94Explicit cursor attributes
94FOR UPDATE clause within CURSOR
95WHERE CURRENT OF clause
95CURSOR with parameter
96CURSOR FOR LOOP
96CURSOR FOR LOOP Using a Query
97Exception, Errors, and PL/SQL
97Exception handling in PL/SQL
100Exception Propagation
Chapter 9Advanced Pl/SQL105Sub-Programs in PL/SQL
105Advantages of Sub-Programs
105Procedure
106Calling a Procedure
106Actual Vs. Formal parameter
106Argument Modes
108Functions
109Stored Package
110Advantages of package
110Creating a package body:
111Dropping Procedures, Function and Package
112DataBase Trigger
Chapter 10PL/SQL File Input - Output118PL/SQL File Input-Output
118Installation of UTL_FILE package
118Functions and Procedures of UTL_FILE package
Chapter 11Implementing Object Technology123What is Object Technology?
123What is an object?
123Existence of an Object
124Retrieving attribute from an object table
125REF and DEREF operator
128Object with Methods
129Calling a Method
Chapter 12Using Lobs132Large Objects (LOB)
132Creating table with LOBs
132Inserting values on the table
133Updating LOB values
133Data Manipulation in LOBs
134Working with DBMS_LOB package
Chapter 13Collections in Oracle 139Collections
139Nested Tables
139Creating table using Nested Table
140DML operations on Nested Table
140Nested Table in PL/SQL
141VARRAYs
141Creating VARRAYs
142DML operations with VARRAYs
142VARRAYs in PL/SQL
143Similarities and differences between Nested Table and VARRAYs
Appendix A
SQL Reserved Word
Page No : 144
Appendix B
Table Structure
Page No : 145
Appendix C
Hands On Session
Page No : 146
Project
Page No : 149(Snapshots Approaches to Database Management
Database Management An Evolutionary phenomenon
Introduction to DBMS
Concept of DBMS
Database Models
Characteristics of Relational Database Management System
The 12 rules for an RDBMS ( Codd's Rule )
Information Representation
Application Development Cycle
Database Designing
ER Diagram
Degree of relationship
Normalization
Need for normalization
Steps in normalization
Invoice Management System
Oracle as an Object Oriented DBMS
Features of Oracle
(ObjectivesAfter studying this chapter, the student should be able to :
Understand the features of an Object Oriented Database Management System
( OODBMS )
Design Database
Draw E-R Diagrams
Normalize Data Structure
Understand Oracle as an Object Oriented Database Management System ( OODBMS )
Approaches to Database Management
Manual methods of Data Management
Management of Data and Information
Convenient and efficient retrieval
Updating operations
Limitation of Manual Data Management
Physical volume of Data
Human processing of Data
Technological advancement in Data Management
Using computers to speed up processing of Data
Advancement of processing power
Using time-sharing for multiple users
High-speed storage device
Centralize to distributed Database
Centralize to distributed processing (Client-Server)
Database Management an Evolutionary phenomenon
The evolution of database management was accompanied and promoted by:
Advances in computing: Hardware, Operating Syatem and Networking
Drawbacks of the prevalent approach to data management
Data redundancy
Risk to data integrity
Data isolation
Difficult access to data
Unsatisfactory security measures
Poor support of parallel access of data
Data redundancy
Since the files and application programs are written over a long period of time, data in the files is likely to get repeated. This may also lead to inconsistency that is; the various copies of the same data may contain different information. Data redundancy could also occur due to duplication of data at different locations the need for the same data at physically different locations.
Risk to data integrity
The data value stored must satisfy certain integrity constraints. These constraints can be enforced in the system, by adding appropriate code in the application programs. The problem is compounded when constraints involves several data items for different files.
Data Isolation
Since data is scattered in various files, and files may be in different formats, it is difficult to write new application programs to retrieve the appropriate data.
Difficult access to data
Whenever there is a new request, that was not anticipated earlier, there are two possible solutions. Either extract the records manually by mentioning the indexes, access methods, or have the system programmer write the necessary application again with minor changes. This leads to the repeated task of programmer for daily requirements.
Unsatisfactory security measuresEvery user of the system should be allowed to view only that part of the data that is relevant to his department. Since application programs are added to the system in an ad-hoc manner, it is difficult to enforce such integrity constraints.
Concurrent accessMany systems allow multiple users to update the data simultaneously to improve the overall performance of the system and obtain a faster response. But in such an environment interaction of concurrent updates may result in inconsistent data. Since the application programs, which have not been previously coordinated, are used access data, supervision is very difficult to provide.
Database management addressed all this problems, though at the price of increased overheads and costs. However, with the advancement of technology and the all-round development made in hardware, software, networking and OS, the drawbacks of data management have been eliminated to a great extent.
Introduction to DBMS
A programmers productivity tool
Good User Interface
Powerful Database Structure
Advancement of Data Manipulations
Use of 4 GL Tools
A discipline towards data independence
Logical Data Independence
Physical Data Independence
Data View
External View
Conceptual View
Internal View
Concept of DBMSA Database is a collection of interrelated data from which some information can be extracted. A database is designed and built for a specific purpose, keeping in mind the needs of the applications that are going to use it and the end users of those applications. It is managed by a software package known as a Database Management System ( DBMS ).
A DBMS is a general-purpose software system that enables users to define and manipulate databases. It provides an environment, wherein data can be stored and retrieved from database easily and most efficiently. The DBMS is the software used to create and maintain the database.
Database Models
Hierarchical
Network
Relational
Hierarchical Model
This model was introduced in the Information Management System ( IMS ) developed by IBM in 1968. This model is like a hierarchical tree structure, used to construct a hierarchy of records in the form of nodes and branches. The data elements present in the structure have a Parent-Child relationship. A parent unit may have many child units, but a child is restricted to have only one parent. This leads to the repetition of same child record for different parents.
The drawbacks of this model are:
1. The hierarchical structure is not flexible enough to represent all the relationship proportions which occur in the real world.
2. It can not demonstrate the over all data model for the enterprise because of the non-availability of actual data at the time of designing the data model.
3. It can not represent the Many-to-Many relationship.
4. The hierarchical model is used only when the concerned data has a clearly hierarchical character with a single root, for example DOS directory structure.
Network ModelIt is improvement on the hierarchical model. Here multiple parent-child relationships are used. Rapid and easy access to data is possible in this model due to multiple access paths to the data elements.
Transaction is maintained using pointers and tracing the pointers is the drawback of this design.
Relational Model Data is organized in terms of rows and columns in a table known as relations.
The position of a row in a table is of no importance.
The intersection of a row and column must give a single value and not a set of values.
All values appearing in the columns are derived from the underlying schema.
Row must be unique.
Column name must be unique.
All column values are atomic.
In relational database, there are no hard-coded relationships defined between tables. A relationship can be specified at any time using any column names.
The publication of the paper A relational model of Data for large shared database by E.F. Codd in June, 1970 in the Communication of ACM, set a trend for vigorous and extensive investigation into a theoretical frame work to support further work in the area of data modeling. The end result is the Relational Database Management Systems.
SupplierScodeSnameSstatusSCity
S01Agarwal15Delhi
S02Patni20Pune
S03Chandra25Mumbai
S04Keshav15Patna
Parts
PcodePnameWeightPcity
P01Screw8Delhi
P02Nut16Pune
P03Bolt20Mumbai
P04Nut16Patna
Shipment
ScodePcodeQty
S01P01150
S01P02200
S02P03250
S02P04100
S03P01300
Consider the tables shown in the sample database. In table Shipment, each supplier status has a unique supplier code which uniquely identifies the entire row of the table and exactly one name, and city. Likewise each part has a unique Pcode and exactly one name, size and city and at any given time on more than one shipment exists for a given supplier/part combination.
The term Relation is used to describe these tables, which is more precise way of defining than the traditional data processing term File or Table. Rows of such table are referred to as Tuples, again a more precise definition than rows or records and columns are referred to as Attribute. In relational data structure is that association between tuples are represented solely by data values in columns.
Characteristics of Relational Database Management System
Relational database have the following three major characteristics that constitute a well defined RDBMS:
Structures
These are objects that store or access data from the database. Tables, views and indexes are examples of structures.
Operations
These are the actions used to defined the structures or manipulate data between the structures. SELECT or CREATE statements are examples of operations.
Integrity rules
These govern the kinds of actions allowed on data and the database structure. Integrity rules protect the data and the structure of the database. The primary keys and foreign keys are the example of integrity rules.
The 12 rules for an RDBMS ( Codds Rule )
Information Representation
Guaranteed Access
Systematic Treatment of null values
Database Description rule
Comprehensive Data Sub-language
View Updating
High Level Insert, Update and Delete
Physical Data Independence
Logical Data Independence
The Distribution rule
Non-subversion
Integrity rule
E.F. Codd formulated 12 rules for RDBMS in 1970. In addition to the 12 rules, there exists a rule, called rule ZERO, which states:
A relational system must be able to manage databases entirely through its relational capabilities. Any DBMS that advices users to the some non-relational methods to achieve acceptable performance should be interpreted as an apology by the vendor.
Information Representation
In the relational model all the information is explicitly and logically represented by the data values in the tables. This means that even such information as table, view, column names etc. should be contained somewhere as a table form. This makes it necessary for the provision of an active data dictionary that, itself, is relational in nature.
Guaranteed Access
This rule refers to the fact that the table can be taken as a storage structure and at the intersection of each column and row there will necessarily be only one value of data (or null). Every value of data must be logically addressable by using a combination of table name, primary key value and column name.
Systematic Treatment of null valuesIn database management system null values are supported for the representation of missing and in-applicable application. This support for null values must be consistent throughout the DBMS, an independent of data types ( for example, a null value in Char field must mean the same as in an Integer field ).
Database Description rule
A description of the database is stored and maintained the form of tables as is done while defining the data. This allows the uses with appropriate authority to query such information in same ways and using the same languages as they would any data in the database. This implies that a data dictionary should be present within the RDBMS that is constructed of tables and / or views that can be examined using the SQL.
Comprehensive Data Sub-languageThe RDBMS must be completely manageable through its own extension of SQL, although some systems still support SQL like language (e.g. INGRESS support QUEL). The SQL should support data definition, views, data manipulation, integrity constraints, authorization, and transaction boundary.
View Updating
It is a myth that all views that can be updated in theory, can also be updated by the system itself. Though it is possible to create views with all sort of aggregate and virtual columns, it is obviously not possible to update through some of them.
High Level Insert, Update and Delete
An RDBMS must do more than just be able to retrieve relational data sets. It has to be capable of inserting, updating and deleting data as a relational set. A database can not be called relational, if it uses a single record at time procedural technique when it comes to manipulating the data.
Physical Data Independence
User access to database, via monitors or application programs, must remain logically consistent even when changes to the storage representation, or access methods to the data are changed.
Logical Data Independence
Application programs must be independent of the changes made to the base tables. This rule allows many types of database design changes to be made dynamically, without the users being aware of them. A single table should be divisible into one or more other tables, provided it preserves all the original data (non-loss), and maintains the primary key in each and every fragment/table.
The Distribution rule
An RDBMS must have distribution independence. This use one of the most attractive aspects of the RDBMS. Database systems built on the relational framework are well suited to todays client-server database design.
Non-subversion
If an RDBMS supports a lower level language that permits for examples, row-at-a-time processing, then this language must not be able to bypass any integrity rules or constraints of the relational language. Thus, an RDBMS must be governed by relational rules as its primary laws.
Integrity rule
Integrity constraints specific to a particular relational database must be definable in the relational data sub-languages and storable in the catalogue, not in the application programs.
An RDBMS product has to satisfy at least six of the twelve rules of Codd to be accepted as a full fledged RDBMS.
Application Development Cycle
A well designed database makes the application programming and tuning much easier. Before going into the details of database design and modeling, lets review the stages involved in application development.
AnalysisThis is the first stage of an application development, and it should enable you to answer the following questions:
1. Why is the application being developed?
2. Who is going to use it?
3. How will the application benefit the users?
4. What business rules and needs should be addressed?
The complete functionalities of the system should be determined in requirement analysis. Typically, functional-level managers take care of this phase.
DesignThis is the most important phase of application development. After the application requirements are analyzed, the design phase begins. In this phase, the database design is performed using ER diagrams. The logical database design is converted to physical structures.
Development
In the development phase, coding is done based on the design; you use the end product of the design phase of the life cycle as a building block for the development process. The database design and the designed system requirements provide the basis for the development of the application.
TestingThe developed application is tested against its objectives to ensure that it is doing what it is supposed to do. System/Integration testing is done on the entire system. Any errors are corrected, and the application is tested again. Application users do the acceptance testing.
Implementation
Implementation is the final stage in the development cycle. Once the testing is complete, the application is ready to implement. Errors reported after implementation is fixed by going back to the appropriate stage.
Database Designing
Requirement, formulation and analysis
Collection and documentation of requirement
Analysis of requirement
Conceptual design
Data Modeling
1st Level-ER (Entity-Relationship) Modeling
2nd Level-Normalization
Physical Model
Requirement, formulation and analysis
The objective of this phase to answer the following question:
What are user views of the data (Present and Future)?
What data elements are required in these user views?
What are the entities and their primary keys?
What are the operational requirements regarding security, integrity and response time?
Conceptual Design
The major step in conceptual design is to identify the entities and relationships that reflect the organizations data. The objective of this step is to specify the conceptual structure of the data and is often referred to as data modeling. The ER model, with an emphasis on the top-down approach.
Data ModelingData modeling is achieved in two levels; the 1st level builds the conceptual model of the data, using ER modeling. The 2nd level organizes this model better, by removing redundancies, through a process called normalization. The normalized model is then converted into the physical database.
Physical Model
You create a physical model by using the logical model to assist in creating a database and database objects to represents to entities and relationships. In the physical model, each entity becomes a table, and attributes of the entity become columns of the table. The relationship between the entities is part of one or more constraints between the tables. Physical implementation might require you to combine, separate, or create completely new entities in order to best realize the logical model. The unique identifiers of an entity become the primary key of the table. You may create stored procedures, functions and triggers to enforce business rules.
ER Diagram
Entity Relationship modeling is a technique for analysis and logical modeling of the system data requirements. It uses three basic concepts, entities, their attributes and the relationship that exists between the entities. It uses graphical notation for representing these.
Graphical notation for ER diagram
NAMESYMBOLFUNCTION
EntityData object in the system uniquely identifiable by identifier has attributes that describe it.
Attribute
Describes an entity
Relationship
Relates two entities uniquely identified by the identifier
EntityAn entity is an object, place, person, concept, activity about which an enterprise records data. It is an object which can have instances or occurrences. Each instance should be capable of being uniquely identified. Each entity has certain properties or attributes associated with it and operation applicable to it. Entity type and entity instance are two important term related to entities. An entity type is a set of things which shares common properties. An entity type is usually denoted in upper case. An entity instance is a specific individual thing. An entity instance is usually denoted in lower case.
Example of entity type: STUDENT COURSE, COURSEWARE DEVELOPMENT TEAM etc.
Example of entity instance: sudipta, physics etc.
Attributes
Attributes are data element that describes an entity. If the attribute of an entity has more attributes that describe it, then it is not an attribute of that entity, but another entity. Attributes can either be listed next to the entities, or placed in circle and attached to the entity. Identifier is one or more attributes of an entity or relation, whose value uniquely identifies the entities or relationships.
Relationship
This is an association between entities. It is represented by a diamond in the ER diagram. Relationship can also have properties and attributes associated with it.
Degree of relationship
ONE to ONE (1:1)
ONE to MANY(1:N)
MANY to MANY(N:N)
The degree of relationship indicates the link between two entities for a specified occurrence of each. The degree of relationship is also called cardinality.
ONE to ONE
This relationship is one in which each occurrence of one entity is represented by single occurrence in another entity. For example, consider an individual and that individuals social security number: One person can have only one social security number, and a social security number can belong to only one person.
ONE to MANY
This relationship is one in which an occurrence of one entity may be represented by many occurrence in another entity. An example is department and employees: One department has one or more employees, and an employee belongs to only one department.
MANY to MANY
This relationship in which an occurrence from one entity may be represented by one or more occurrence in another entity, and an occurrence from second entity may be represented by one or more occurrence in the first entity. The relationship between Doctor and Patient is an example: A patient can visit many doctors, and a doctor can have many patients.
Note: MANY to MANY relationship should not exists in RDBMS because they can not be properly joined to represent a single row correctly. To solve this, create another entity that has a ONE to MANY relationship with the first entity and a ONE to MANY relationship with the second entity.
When you have established the relationship between entities, it is time to normalize the design.
Normalization
Refinement of the ER Model.
Segregation of data over many entities or tables.
Normalized model converted to physical database tables.
Normalization is the process of refining the data model built by the ER Diagram. The normalization technique, logically groups the data over a number of tables, with minimum redundancy of data.
The goal of the relational data base design is to generate a set of relation scheme that allows us to information with minimum redundancy of data and allow us to retrieve information easily and efficiently.
The first step towards normalization is to convert the ER model into tables or relations. The next step is to examine the tables for redundancy and if necessary, change them to non-redundant forms. This non-redundant model is then converted to a database definition.
Need for normalization
Improves database design.
Ensures minimum redundancy of data.
Reduces need to re-organize data when design is modified/enhanced.
Removes anomalies for database activities.
Un-Normalized Data Structure
Supplier CodeSupplier NameSupplier StatusCity SupplierPart CodePart NameWeightQtyCity Sold
S01Agarwal15Delhi101Screw8500Kolkata
S02Patni20Pune102Nut16250Meerut
S03Chandra25Mumbai103Bolt20250Ranchi
S04Keshav15Patna102Nut16300Silvasa
S05Bhushan25Kolkata104Bolt2050Pune
S06Menon15Guahati102Nut16200Patna
Above table structure presents several difficulties in operations like:
Insertion in fields If new field is introduced into the system, it can not be added to the database, until becomes related to another existing field, e.g. if supplier name is introduced its details can not be entered in the table unless a part name is represent for that supplier.
Updation of fields If the supplier code of a supplier is to be modified, it has to be changed throughout the table, in all occurrence of the supplier record. Missing out even a single correction, would result in incorrect data.
Deletion of fields If information related to a specific column is to be deleted, the entire row has to be deleted, which results in loss of required information. For example, if the row of the supplier Saleh is deleted, the information about the part name is lost. Deletion of supplier detail also deletes other details.
Steps in normalization
First Normal Form (1NF)
Identify a repeating fields
Remove repeating groups to a separate table
Identify the keys for the table
Key the parent table is brought as part of the concatenated key of the second table
Second Normal Form (2NF)
Check if all fields is dependent on the whole key
Remove fields that depend on part of the key
Group partially-dependent fields as a separate table
Name the tables
Identify key(s) to the table(s)
Third Normal Form(3NF)
Remove fields that
Depend on other non-key attribute
Can be calculated or derived from logic
Group independent fields as separate tables, identify the key and name of the table
Invoice Management System
An invoice management system accepts items and customer details from the user and prepares invoices. The item details include item description, quantity sold, rate and discount (if applicable). For each order the customer is given an invoice. Each invoice can have details of more than one item.
The raw table containing invoices details: Un-normalized
InvnoInvdateOrdnoChlnoCustnoCustnmItnoItdescQtyRateDisInval
11212/08/9711C1AshokeI1Pepsi28Nil16
11212/08/9721C1AshokeI2Butter122Nil22
11316/08/9711C4VipulI3Bread112Nil12
11416/08/9711C1AshokeI8Biscuit222Nil44
11416/08/9721C1AshokeI2Butter422Nil88
First Normal Form
The attributes invno, invdate, ordno, chlno, custno and inv_val are repeating groups in the invoice table. These attributes can be are split into a separate table called invoice table which contains the invno, invdate, ordno, chlno, custno and inval.
The identifier of this table is invno. The other table is called invoice items which contains invno, into, itdesc, qty, rate and dis. The identifier of this table is invno and into which identifies a single row.
Invoice Table
InvnoInvdateOrdnoChlnoCustnoCustnmInval
11212/08/9711C1Ashoke16
11212/08/9721C1Ashoke22
11316/08/9711C4Vipul12
11416/08/9711C1Ashoke44
11416/08/9721C1Ashoke88
Invoice Items
InvnoItnoItdescQtyRateDis
112I1Pepsi28Nil
112I2Butter122Nil
113I3Bread112Nil
114I8Biscuit222Nil
114I2Butter422Nil
Second Normal FormThe invoice item table is further split, by removing itdesc and rate which are not dependent on the full concatenated key (invno+itno). The new table is named as ITEMS table which contains itdesc, rate and itno as its primary key. The identifier of this table is itno, which identifies a single row.
The remaining attributes in the invoice item table consists only of, invno, itno, qty and dis. The identifier here is invno+itno which identifies a single row. Here each elements is dependant on full concatenated key.
Invoice TableInvnoInvdateOrdnoChlnoCustnoCustnmInval
11212/08/9711C1Ashoke16
11212/08/9721C1Ashoke22
11316/08/9711C4Vipul12
11416/08/9711C1Ashoke44
11416/08/9721C1Ashoke88
Invoice Items
InvnoItnoQtyDis
112I12Nil
112I21Nil
113I31Nil
114I82Nil
114I24Nil
Item Table
ItnoItdescRate
I1Pepsi8
I2Butter22
I3Bread12
I8Biscuit22
I2Butter22
Third Normal FormThe invoice table derived from the un-normalized table is now in the second form can be further normalized. There is still a dependency between non-key attributes: custnm depends upon custno, a non-key attribute. custnm is removed to the CUSTOMER table, with custno as the key. The remaining attributes remain in the INVOICE table with invno as the key.
Invoice TableInvnoInvdateOrdnoChlnoCustnoIn_val
11212/08/9711C116
11212/08/9721C122
11316/08/9711C412
11416/08/9711C144
11416/08/9721C188
Customer TableCustnoCustnm
C1Ashoke
C4Vipul
Invoice Items
InvnoItnoQtyDis
112I12Nil
112I21Nil
113I31Nil
114I82Nil
114I24Nil
Item Table
ItnoItdescRate
I1Pepsi8
I2Butter22
I3Bread12
I8Biscuit22
I2Butter22
Oracle as an Object Oriented DBMS
Oracle is an ORDBMS. It lets you define user defined object types in the relational database system. Object types are structures that consists of built-in or user-defined data types. For example, an address can be defined as an object type and can be referenced in tables:
Customer_Table
Cust_nameVarchar2(40)
Cust_addrAddress_Type
Cust_phoneVarchar2(12)
Cust_faxVarchar2(12)
Where Address_type is an object type defined as
Address_Type
StreetStreet_Type
CityVarchar2(30)
StateChar(2)
ZipNumber(5)
Where Street_Type is defined as :
Street_Type
Street_number
Number(6)
Street_name1
Varchar2(40)
Street_name2
Varchar2(40)
Apartment_no
Varchar2(5)
Now that the Address_Type is defined, it can be used in number of tables where addresses need to be stored. This small example shows the reusability of objects.
Features of Oracle
High transaction processing performance All the facilities for transaction and its recovery in case of any failure are supported in Oracle for better performance of transaction processing.
Industry accepted standards All the recent technologies like object oriented technology and distributed data processing are supported in Oracle .
Manageable Security Very strong security provisions are there inside Oracle to guard against malicious users.
Large database support In supporting large database, Oracle is more reliable compared to any other database packages.
Concurrent Processing More than one user can work simultaneously on the same database without any interference.
Client/Server environment It supports client server technology i.e. the server contains the main database and clients ( users ) can access the database to fetch and manage only that data for which they are given the authorization.
Distributed database system Oracle supports distributed environment i.e. applications made on different platforms and in different environments can exchange the data with the common interface language called Interface Definition Language ( IDL ).
Portability Runtime models made inside Oracle environment can run without any changes on other compatible platforms easily.
Compatibility It is compatible with all sorts of front ends although, Oracle has its own front end but still Oracle database can be used with other front ends like Visual Basic, VC++ etc. easily.
(Snapshots
Introduction to SQL
Oracle Data Types
Starting SQL* Plus editor
Operators and Expressions
Querying DataBase Tables
RollUp Operation - Getting sub totals
Cube Operation - Getting cross tabs
(Objectives
After studying this chapter, the student should be able to :
Understand the Structured Query Language ( SQL )
Understand the Datatypes supported by Oracle
Log on to Oracle
Query database tables using SQL statement
Understand how to use Aggregate Functions
Understand Order by and Group by clause
Understand ROLLUP and CUBE operation
Introduction to SQL
The language used to access data within Oracle database
Developed in a prototype RDBMS, System R, by IBM in mid 1970s
Oracle Corporation introduced the first commercially available implementation of SQL
ANSI adopted SQL as a standard language for RDBMS in October 1986
Key features of SQL are:
Non-procedural language
Unified language
Common language for relational database
SQL (Structured Query Language) pronounced as see-quell is made of three sub-languages such as:
Data Definition Language (DDL): Consists of commands Create, Alter, Drop to create or remove objects such as Tables, Views, and Indexes etc.
Data Manipulation Language (DML): Used for query, Insertion, Deletion and Updation of information stored in the database.
Data Control Language (DCL): Used for controlling data and access to the databases. Examples: Commit, Rollback.
SQL *Plus is a software product from Oracle Corporation that allows users to interactively use the SQL commands, produce formatted reports and support written command procedures to access Oracle database.
Through SQL *Plus a user can:
Enter, edit, store, retrieve and run SQL commands
Format, perform calculation, store, print query result in the form of reports
List column definition of any table
Access and copy data between SQL databases
Send messages to and accept responses from an end user
Oracle Data Types
When you create a table to store data in the database, you need to specify a datatype for all columns to define in the table. Oracle has different datatypes to suit your needs. The datatype are broadly classified into Character, Number, Date, LOB and RAW datatypes. Oracle lets you use user-defined datatypes, but they are constructed from the basic datatypes.
Character Datatypes
Character datatypes are used to store alphanumeric data. When you define character data in Oracle , you specify a length for the column, which is the maximum width of the column. In Oracle you can have different type of datatype to store alphanumeric value:
CHAR() The CHAR datatype is a fixed-length character string having a maximum length of size. Data stored in CHAR column is space-padded to fill the maximum length. The size can range from a minimum of 1 to maximum of 2000 characters.
When you create a column using the CHAR datatype, the database will ensure that all data placed in this column has the defined length. If data is shorter than the defined length, it is space-padded on right to the specified length. If the data is longer, an error is raised.
VARCHAR() A VARCHAR datatype in Oracle is synonymous with the VARCHAR2 datatype.
VARCHAR2() The VARCHAR2 datatype is a variable-length alphanumeric string having a maximum length of size bytes. VARCHAR2 variables only require the amount of space needed to store the data. VARCHAR2 database columns can store up to 4000 bytes and VARCHAR2 variables up to 32676 bytes. An empty VARCHAR2(2000) column takes up as much room in the database as an empty VARCHAR2(2) column.
The default size of the CHAR datatype is 1. In VARCHAR2, you must always specify the size.
LONG The LONG datatype is a legacy datatype that will no longer be supported in the future. It has been deprecated in favor of large object datatype. A LONG datatype column is of variable length and can take up to 2GB. There are many restriction on the use of LONG columns and variables. LONG columns can not appear in Where clause, Group By clause, Order By clause or with the Distinct operator in Select statements.
Numeric Datatype
Numeric datatype are used to store negative and positive integers: fixed-point and floating-point numbers with a precision of up to 38 digits. Specifying a number outside this range will raise an error.
Number(,) The number datatype stores numbers with a precision of p digits and a scale of s digits. The precision and the scale value are optional. Specifying the scale and precision does not force all inserted values to be a fixed length. If the number exceeds the precision, however, an Oracle error is returned. If the number exceed the scale, it is rounded to the scale. If the scale is negative, the number is rounded to the left of the decimal. Basically, a negative scale forces s number of zeros just to the left of the decimal.
Precision and scale example
Actual ValueDatatypeStored Value
1234567.89Number1234567.89
1234567.89Number(8)1234568
1234567.89Number(6)Numeric Error
1234567.89Number(9,1)1234567.9
1234567.89Number(9,3)Numeric Error
1234567.89Number(7,2)Numeric Error
1234567.89Number(5,-2)1234600
1234511.89Number(5,-2)1234500
1234567.89Number(5,-4)1230000
1234567.89Number(*,1)1234567.9
Date Datatype
The Date datatype is used to store date and time information. This datatype can be converted to other forms for viewing, and it has number of special functions and properties that makes date manipulation and calculation simple. The Date datatype occupies a storage space of 7 bytes. The following information is contained within each date datatype:
Century Year Month Day Hour Minute Second
The default format for Oracle Date datatype is DD-Mon-YY; this is the format shown whenever a date is selected within SQL *Plus.
LOB DatatypeLarge object datatypes store blocks of unstructured data, such as a binary file, a picture, or an external file. A LOB can store data up to 4GB. The data may be stored in the database or in an external file. LOB data maniputaion is done using the DBMS_LOB package.
Datatype PurposeDescription
BLOBBinary Large ObjectCan store up to 4GB of binary data in the database.
CLOBCharacter Large ObjectCan store up to 4GB of character data in the database. Oracle converts the data into Unicode format and stores it in the database.
BFILEBinary FileStores binary data up to 4GB in operating system files outside of the database. The size of the binary file must conform with operating system limitations on file size. A BFILE column stores a file locator that points to an external file containing the data. BFILE datatypes are read-only; You can not modify them.
Note : There may be more than one LOB datatype column in a table, but there can be only one LONG datatype column.
Other Datatypes
Oracle has RAW datatypes in addition to the character, numeric and date datatypes.
RAW RAW is unstructured, binary data that is not interpreted by the database. RAW columns can be up to 2000 bytes long.
LONGRAW Like the LONG datatype, LONGRAW is a legacy datatype that has been deprecated in favor of the LOB datatypes BLOB or BFILE. LONGRAWs can store up to 2GB of unstructured data. LONGRAW data cannot be indexed, but RAW data can be indexed.
Literals
Literals are values that represent a fixed value. There are three types of literals values:
Text
Integer
Number
Text literals must be enclosed in single quotes; integer and number literals need not be. You can use literals within many of the SQL functions, expressions and conditions.
Text The text literal must be enclosed in single quotation marks. Any character between the quotation marks is considered part of the text value. Oracle treats all text literals as though they were CHAR datatypes. The maximum length of a text literal is 2,000 characters. Single quotation marks can be included in the literal text value by preceeding it with another single quotation mark.
Here are some examples:
The quick brown fox
That mans suit is black
And I quote:This will never do.
Integer Integer literals can be any number of numerals, excluding a decimal separator and up to 38 digits long.
Examples follow:
24
-456
Number Number literals can include scientific notation, as well as digits and the decimal separator.
Here are some example:
24
-345.65
23E10
Starting SQL* Plus editor
Step I : Locate the Oracle short cut in your desktop. If it is not there try to get it from Start>Programs menu.
Step II : Double click or press on the short cut shown above.
Step III : Provide the User Name, Password and Connect String in the dialog shown. The Connect String is nothing but the Database name.
After providing the User Name, Password and Connect String click on the OK button. If all the information you have provided is correct then you will get the following screen.
Tables used in Examples
DEPT-Contains information about the departments in the company
EMP-Contains information about the employees of that company
Structure of DEPT table
Column namesType(Size)DescriptionConstraints
DEPTNONUMBER(2)Department numberPrimary Key
DNAMEVARCHAR2(20)Department nameNOT NULL
LOCVARCHAR2(10)Location of the departmentNOT NULL
Data of DEPT Table :
Structure of EMP table
Column namesType(Size)DescriptionConstraints
EMPNONUMBER(4)Employee numberPrimary Key
ENAMEVARCHAR2(20)Employee nameNOT NULL
JOBVARCHAR2(10)DesignationNOT NULL
MGRNUMBER(4)Respective managers EMPNO
HIREDATEDATEDate of JoiningNOT NULL
SALNUMBER(9,2)Basic SalaryNOT NULL
COMMNUMBER(7,2)Commission
DEPTNONUMBER(2)Department numberNOT NULL, Foreign Key
Data of EMP Table :
Operators and Expressions
An operator is a manipulator that is applied to a data item in order to return a result. Special characters represent different operations in Oracle. Operators may be classified into two types :
Unary Operators : A unary operator has only one operands. +2 and 5 are examples. They have the format < operator operand >
Binary Operators : Binary operators have two operands. 5+4 and 7 x 5 are examples. They have the format < operand1 operator operand2 >
Arithmetic Operators
Arithmetic operators operate on numeric datatypes.
OperatorPurposeExample
+ - Unary operators: Use to represent positive or negative data item. For positive items, the + is optional.-234.45
+Addition: Use to add two data items or expressions.3 + 7
-Subtraction: Use to find the difference between two data items or expressions.7 - 5
*Multiplication: Use to multiply two data items or expressions.5 * 10
/Division: Use to divide a data items or expression with another.8 / 4
Concatenation Operator
This operator is used to concatenate or join two character ( text ) strings. The result of concatenation is another character string. If one of the strings is NULL, the result is also NULL. Concatenating a zero-length string( ) with another string results in a string, not a NULL. Two vertical bars ( || ) are used as the concatenation operator. Here are a few examples:
Oracle || Database results in OracleDatabase Oracle || Database results in Oracle DatabaseComparison Operator
Comparison operators compare two values or expression and give a Boolean result of TRUE, FALSE, or NULL. Comparison operators are mainly used in the WHERE clause of the SQL statement.
OperatorPurposeExample
=Equality test SELECT * FROM emp WHERE ename=SCOTT;
!=
^=Inequality testSELECT * FROM emp WHERE ename!=SCOTT;
2000;
>=Greater than equal toSELECT * FROM emp WHERE sal>=2000;
ALL(SELECT sal FROM emp WHERE deptno=20);
The above will display all employees name whose salary is greater than the highest salary of all employee belonging to department 20.
(Snapshots
Functions
Single Row Function
Arithmetic Functions
Character Functions
Date Functions
General Functions
Group Functions
(Objectives
After studying this chapter, the student should be able to :
Understand what are Functions
Type of Functions
Understand the use of various column functions and group functions
Functions
Functions are programs that take zero or more arguments and return a single value. There are two significant classes of function:
Single Row Function
Group Function
Single Row Function
Single Row Function knows how many arguments they will have to process before data is fetched from the tables.
Can be used to manipulate data items
Accept arguments (number of arguments varies from function to function)
Always returns a single value
Act on each row returned
Can be used to modify the data type
Can be nested in other functions
To test all the following functions you can work with the table called dual. This table has only one column in its structure. The column name is dummy and it has only one row with a value x.Arithmetic functions
ABS (x)Absolute Value of x
CEIL (x)Smallest integer greater than or equal to x.
FLOOR (x)Largest integer less than or equal to x.
MOD (x,y)Returns the remainder of x divided by y
POWER (x,y)Returns x raised to the power of y. The 2nd argument must be an integer
SIGN (x)Returns 1 if x is negative, 1 if positive and 0 if it is zero
SQRT (x)Returns the square root value of x. If x is null or negative then null is returned
ROUND (x,[y])Rounds the value x, up to y decimal places. If y is omitted it is rounded to no decimal places. If y is negative number to left the decimal are rounded
TRUNC (x, n)Truncate x to n decimal places to the right of the decimal point.
Character functions
CHR (x)Character for ASCII value x.
ASCII (c)Returns the ASCII value of c
INITCAP (s)String s with the first letter of each word capitalized
LOWER (s)Converts string s to all lower case letters
UPPER (s)Converts string s to all upper case letters.
LPAD (s, x)Pads string s with x spaces to the left.
RPAD (s, x)Pads string s with x spaces to the right.
LTRIM (s)Removes leading spaces from s.
RTRIM (s)Removes trailing spaces from s.
REPLACE (s1, s2, s3)Replace occurrences of s1 with s2 in string s.
TRANSLATE (s1, s2, s3)Returns s1 with all occurrences of each character in s2 replaced by the corresponding character in s3.
SUBSTR (s, x1, x2)Return a portion of string s starting at position x1 and ending with position x2. If x2 is omitted, it's value defaults to the end of s.
INSTR (s1, s2, x)Returns the position of s2 in s1 where the search starts at position x.
LENGTH (s)Length of s
Date Functions
SYSDATEReturns the system date
ADD_MONTHS(d,n)Add or subtract months to or from a date. Returns a date as the result
MONTHS_BETWEEN(d1,d2)Returns number of months between two dates
LAST_DAY(d)Returns the date of the last day of the month specified. The result will be a date
NEXT_DAY(d,day)Returns the date of next specified day of the week after the date d
Conversionfunctions
TO_CHAR (date, format)Converts a date column to a string of characters. format is a set of Date formatting codes where:YYYY is a 4 digit year.MM is a month number.MONTH is the full name of the month.MON is the abbreviated month.DDD is the day of the year.DD is the day of the month.D is the day of the week.DAY is the name of the day.HH is the hour of the day (12 hour clock)HH24 is the hour of the day (24 hour clock)MI is the minutes.SS is the seconds.
TO_CHAR (number, format)Converts a numeric column to a string of characters. format is a set of number formatting codes where:9 indicates a digit position. Blank if position value is 0.0 indicates a digit position. Shows a 0 if the position value is 0.$ displays a leading currency indicator.
, used as a group separator
TO_DATE (s, format)Converts a character column (string s to a date. format is a set of Date formatting codes as above
TO_NUMBER (s, format)Converts a character column (string s to a Number. format is a set of Number formatting codes as above.
OtherfunctionsDECODE (s, search1, result1, search2, result2)Compares s with search1, search2, etc. and returns the corresponding result when there is a match.
NVL (s, expression)If s is NULL, return expression. If s is not null, then return s.
USERReturns the username of the current user.
Group Functions
Group function dont know how many arguments they will have to process until all the data extracted and grouped into categories. To use an aggregate function, a GROUP BY clause must be added to the SELECT statement. Group function do not process a null value and do not return a null value.
AVG (col)Returns the average of a group of rows for col
MAX (col)Returns the maximum of a group of rows for col
MIN (col)Returns the minimum of a group of rows for col
SUM (col)Returns the sum (total) of a group of rows for col
COUNT (columns)Returns the number of instances of a group of rows for (columns)
(Snapshots
Data Definition Language
Creating Tables
Working with Constraints
Creating a table with data from another table
Maintaining Database Objects
Alter Table
The ENABLED/DISABLED Clause
Dropping / Renaming Tables
Truncating table
Insert values into a table
Inserting result of a query into a table
Inserting through parameter substitution
Updating columns of a table
Deleting rows from a table
Introduction to Views
Creating a view
Manipulating Data through Views
Creating a join view
Key-preserved table
Rules for DML statements on Join View
Dropping a view
Working with Sequences
(Objectives
After studying this chapter, the student should be able to :
Understand how to create tables
Understand what are constraints
Understand how to alter a table
Understand how to insert values into a table
Understand how to update column(s) of a table
Understand how to delete row(s) from a table
Understand what are views
Understand how to manipulate base table(s) using views
Understand how to work with sequence
Data Definition Language
DDL is a subset of SQL commands used to create, modify or remove Oracle database structure.
Example: Tables, Views. These command have an immediate effect affect on the database, and also record information in the data dictionary.
Creating Tables
Tables are created using the CREATE TABLE command
Tables are owned by the user who creates them
The names of table owned by a given user must be unique
The column names in a table must be unique
Naming convention of a table
The table name must begin with a letter
It may contain letters, numerals and special character
It may be up to 30 characters long
A table name must not be a SQL reserved word
Table name is not case sensitive
Table names are stored in uppercase except those given in double quotes
Syntax:
CREATE TABLE
(
,
..
);
Example:
Create a table ITEM_MAST, which has the following columns:
Column NameTypeSizeDescription
ITNONumber4Item Number
ITNMVarchar220Item Name
CLASSChar1Category of item
QOHNumber5Quantity On Hand
RATENumber8,2Item Unit Price
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASSChar(1),
QOH
Number(5),
RATE
Number(8,2)
);
Working with Constraints
Constraints are used to enforce data integrity. Constraints are rules and as such dont take up space in a database as a table dose. Instead, constraints exist only in the data dictionary and are applied during the execution of SQL and PL/SQL. When constraints are enabled, they are enforced. When constraints are disabled, they are not enforced, but they still exist in the data dictionary. There are five varieties of constraints :
Check
NOT NULL
Unique
Primary key
Foreign key
Default
Check Constraints
Check constraints require a specific Boolean condition on a column or set of columns to be true or at least one of the column values to be NULL. Check constraints are enforce simple business rules about the content of data in your tables. Check constraints cannot protect columns of datatype LOB, object, nested table, VARRAY. If the check protects a single column, it can be created inline with the column in the CREATE TABLE statement. A check constraint can also be created or added as a table constraint. When it protects two or more columns, you must use the table constraint syntax. The constraints name is optional and, if this name is not present, Oracle will generate a unique name that begins with SYS_. You should not rely on system-generated names for constraints.
Example :
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS Char(1) constraint ch_class check (CLASS IN ( A, B, C ))
QOH
Number(5),
RATE
Number(8,2),
Constraint ch_classrate CHECK (( CLASS = A AND RATE VALUES ;
Example :
INSERT INTO ITEM_MAST
VALUES ( 111,Baby Food, A, 75,125.75);
While inserting data into table, the following points should be remembered:
Character data will be enclosed within quotes
Column values for date type of column are provided within single quotes. Oracle internally converts the character field to date type field
NULL values are given as NULL, without any quotes because null is a true value
If data is not available for all columns, then the column list must be included, following the table name.
Example :
INSERT INTO ITEM_MAST ( itno, itnm, class)
VALUES ( 111,Baby Food, A);
Inserting result of a query into a table
In order to use query with insert, the target table must fulfill the following conditions:
The table must be an existing one
It must have the columns retuned by the query and be of the same data type
Example:
INSERT INTO itmast SELECT itno, itnm, class FROM item_mast;
Inserting through parameter substitution
The parameter substitution provides an easier way to insert data into a table. The & sign is used as the substitution operator.
Example:
INSERT INTO itmast VALUES(&itno, &itnm,&class);
Updating columns of a table
UPADTE command is used to update the column values in a table Values of a single column or a group of columns can be updated
Updation can be carried out for all the rows in a table or selected rows
Syntax:
UPDATE SET =value
[,=value,] [WHERE ];
Example:
UPDATE itmast SET qty=100 WHERE into=111;
Deleting rows from a table
DELETE statement is used to delete rows from a table The entire row is deleted from the table
Specific column value can not be deleted from a table
CASCADE DELETE rule instructs DBMS to automatically set the foreign values to NULL in the child rows, if the parent row is deleted
Syntax:
DELETE FROM [WHERE ];
Example:
DELETE FROM emp;
DELETE emp;
Both the statements are same and will delete all the rows from the emp table.
Introduction to Views
A view is a customized representation of data from one or more tables. The view takes the result of a query and stores it in the database. A view can be considered to be as a stored query or a virtual table. Only the query is stored in the Oracle data dictionary; the actual data is not copied anywhere. So, creating views does not take any storage place, other than the space in the data dictionary. The views can have different column names than the base table. You may create a view to limit the data accessible to the other user.
Creating a view
A view can be created using the following syntax:
CREATE VIEW [] AS ;
Example:
CREATE VIEW empview AS SELECT empno,ename,deptno FROM emp WHERE deptno=20;
Now to select the rows from the view you can use the following statement:
SELECT * FROM empview;
Manipulating Data through Views
The INSERT, UPDATE and DELETE statements can also be used with views Using these commands with views is an indirect way of manipulating tables
WITH CHECK OPTION clause allows integrity constraints and data validation to be enforced on data being inserted or updated
Join view can also be modified
Key-preserved table is used to understand the restriction on modifying join views
The WITH CHECK OPTION clause
This clause specifies that inserts and updates performed through the view are not allowed to create rows which the view can not select. Let us consider the above view:
Suppose we insert the following:
INSERT INTO empview VALUES(1234,PAUL,30);
The row will be inserted without any error. But if we create that view with the following statement the above insert statement will generates an error:
CREATE VIEW empview AS SELECT empno,ename,deptno
FROM emp WHERE deptno=20 WITH CHECK OPTION;
Constraint name can also be assigned to the WITH CHECK OPTION:
CREATE VIEW empview AS SELECT empno,ename,deptno
FROM emp WHERE deptno=20 WITH CHECK OPTION CONSTRAINT mycons;
Creating a join view
CREATE VIEW myview AS SELECT empno, ename, dname
FROM emp, dept WHERE emp.deptno=dept.deptno;
Key-preserved table
A table is key-preserved if every key of the table can also be a key of the result of the join, so, a key-preserved table has its keys preserved through a join.
Criteria to be a key-preserved table
View should be based on more than one table and should be a join view
To satisfy key-preserved table at least one column should be a PRIMARY KEY in the join statement
Example:
CREATE VIEW myview AS SELECT empno, ename, dname, dept.deptno
FROM emp, dept WHERE emp.deptno=dept.deptno;
In the above example, table emp is a key-preserved table and table dept is a non-key-preserved table.
Following will the output when you will select from the view called myview:
Rules for DML statements on Join View
Any INSERT, UPDATE or DELETE statement a join view can modify only one underlying base table i.e., the emp table.
Examples:
INSERT INTO myview(empno, ename) VALUES(5678,JOHN);
UPDATE myview SET ename = McGILL WHERE empno=5678;
DELETE FROM myview WHERE ename=McGILL;
If we try to insert a row into the non-key-preserved table dept with the following statement:
INSERT INTO myview(deptno, dname) VALUES(50,PRODUCTION);
The statement would failed with an ORA-01776 error (can not modify more than one base table through a view)
UPDATE myview SET dname=ADMIN WHERE deptno=10;
This statement fails with an ORA-01779 error (can not modify a column which maps to a non-key-preserved table)
Dropping a view
The DROP VIEW command is used to remove a view from the database.Example:
DROP VIEW myview;
Working with Sequences
An Oracle SEQUENCE is a named sequential number generator. SEQUENCE are often used for artificial keys or to order rows that otherwise have no order. A SEQUENCE can be configured to increase or decrease.
A SEQUENCE can have the following parameters:
KEYWORDDESCRIPTION
START WITHDefines the 1st number that the sequence will generate. The default is 1.
INCREAMENT BYDefines the increase or decrease for subsequently generated number.
MINVALUEThe lowest number the sequence will generate. This is the bounding value in the decreasing sequence. The default MINVALUE is the keyword NOMINVALUE, which translates 1 for an increasing sequence and to minus -1026 for a decreasing sequence.
MAXVALUEThe largest number the sequence will generate. This is the bounding value by default for the increasing sequence. The default MAXVALUE is the keyword NOMAXVALUE, which translates to 1027 for an increasing sequence and to minus -1 for a decreasing sequence.
CYCLEConfigures the sequence to repeat numbers after reaching the bounding values.
When you create the sequence the START WITH value must be equal to or greater than MINVALUE. To access the next number in the SEQUENCE, you simply select from it, using the pseudo-column NEXTVAL. To get the last SEQUENCE number that your session has generated, you select from it using the pseudo-column CURRVAL. If your session has not yet generated a new sequence number, CURRVAL will be un-defined.
To Create a SEQUENCE:
CREATE SEQUENCE sq START WITH 1 INCREAMENT BY 5 MAXVALUE 50;
To fetch the NEXTVAL from a SEQUENCE:
SELECT sq.NEXTVAL FROM dual;
To fetch the CURRVAL from a SEQUENCE:
SELECT sq.CURRVAL FROM dual;
To alter a SEQUENCE:
ALTER SEQUENCE sq INCREAMENT BY 2;
To drop a SEQUENCE:
DROP SEQUENCE sq;
(Snapshots
DataBase Security and Privileges
Grant Command
Revoke Command
Application Privilege Management
Oracle provides three standard ROLEs:
Commit and RollBack
Implicit COMMIT
Auto ROLLBACK
Savepoint
(Objectives
After studying this chapter, the student should be able to :
Understand how to use GRANT command
Understand how to use REVOKE command
Assign and grant privileges to other users on database objects
Understand how to maintain database objects
Understand different transaction processing options
DataBase Security and Privileges
SQL is mostly executed in environments that require to recognize to differentiate between the various users of the system.
Each user in an Oracle database has a specific authorization.
Commands are interpreted and permitted (or prohibited) on the basis of information associated with the authorization associated with the ID of the user issuing the command.
The database administrator creates the users and assigns the privileges.
Privileges determine whether or not a user can execute a given command or a command when acting on specific groups of data.
Grant Command
The GRANT command is used to grant access to the database. A user can GRANT access to his/her database objects to another objects.
The syntax for GRANT command:
GRANT TO ;
GRANT
ON TO [WITH GRANT OPTION];
All tables, views, sequences that a user creates are owned by the user itself. Only the creator or DBA can access it.
The specifies the system level privileges to be granted to the users or roles (discussed later). This includes CREATE/ALTER/DROP any object of the system.
The specifies the actions such as SELECT, INSERT, DELETE, UPDATE, ALTER for tables.
indicates all the privileges. The privileges can be granted to the different users by specifying their names or to all users by using the PUBLIC option.
The WITH GRANT OPTION clause allows the recipient user to give further grant on the objects.
Examples:
GRANT ALL ON emp TO PUBLIC;
GRANT SELECT ON emp TO user1;
GRANT SELECT, INSERT ON emp TO user1, user2;
Revoke Command
Using REVOKE command a user can withdraw the privileges which has been granted earlier.Syntax:
REVOKE FROM
REVOKE ON FROM
Examples:
REVOKE ALL ON emp FROM PUBLIC;
REVOKE SELECT ON emp FROM user1;
REVOKE SELECT,INSERT ON emp FROM user1, user2;
Application Privilege Management
Roles are used to simplify the administrative tusks involved in the management of privileges.
Role is a collection of system privileges.
The syntax for creating ROLE is:
CREATE ROLE ;
Example:
CREATE ROLE myroll;
GRANT SELECT, INSERT ON emp TO myroll;
GRANT myroll TO user3;
Oracle provides three standard ROLEs:
CONNECT This ROLE only allows to use Oracle.
RESOURCE This ROLE only allows to create Oracle objects.
DBA This ROLE has the system privileges; such as Creating user, database.
When you are creating a new user, you must grant CONNECT and RESOURCE role to the newly created user.
Commit and RollBack
The COMMIT command is used to make changes to the data, permanently.
The ROLLBACK command is used to discard parts of all work the user has done in the current transaction.
SAVEPOINT statement are used to discard or commit all the changes up to a point.
SQL *Plus has the facility to automatically commit all the transactions without explicitly issuing the COMMIT command.
SET AUTOCOMMIT ONEnables autocommit feature.
SET AUTOCOMMIT OFFIs the default and disables the autocommit feature.
Implicit COMMIT
The actions that will force a commit to occur, even without issuing the COMMIT command are:
Exiting SQL *Plus
Creating any objects
Granting or Revoking resources
Altering objects
Connecting or disconnecting from Oracle
Auto ROLLBACK
After completion of any DML statement, if the user experiences serious difficulty such as: Hardware failure and no explicit COMMIT is made, Oracle will automatically rollback all un-committed work.
If there is no explicit COMMIT made and if the AUTOCOMMIT mode set to OFF then after the normal shut-down the server will commit all the un-committed transaction.
Savepoint
SAVEPOINT identifies a point in a transaction to which one can later rollback with the ROLLBACK statement. It is helpful when a transaction contain a large number of SQL statement and the user wants to commit only once when all are done.
If required one can rollback to a particular transaction. It works in a Last In Fast Out basis.
Example:
INSERT INTO dept VALUES(60,PURCHASE,DELHI);
SAVEPOINT sp1;
UPDATE emp SET deptno=60 WHERE ename=SMITH;
ROLLBACK TO SAVEPOINT sp1;
The ROLLBACK statement will undo the updation only. All transaction before the savepoint sp1 will remain unchanged, but not yet committed.
(Snapshots
Introduction to PL/SQL
Advantages of PL/SQL
PL/SQL Architecture
PL/SQL Block Structure
Named and Anonymous block
Conditional and Iterative Control
IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP
SQL within PL/SQL
Writing a PL/SQL code
Composite Data Types
PL/SQL Records
Record Assignment
PL/SQL TABLES
(Objectives
After studying this chapter, the student should be able to :
Understand PL/SQL block structure and architecture
Understand the Conditional and iterative control
IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP
Understand how to use SQL within PL/SQL
Understand How to write PL/SQL code
Understand Composite Datatype
Introduction to PL/SQL
PL/SQL is the procedural extension to the non-procedural SQL Combines data manipulation power of SQL and procedural power of standard procedural language
Provides performance improvements through blocking of RDBMS calls
Integrates well with SQL *Plus and other Application Development products of Oracle
Supports sub-programming features such as Procedures and Functions
PL/SQL is an extension to non-procedural SQL. It includes many features and designs of programming language. It combines the data manipulating power of SQL with the data processing power of procedural language. The PL/SQL engine resides within Oracle server so it is available from any application development tool that supports PL/SQL.
Advantages of PL/SQL
PL/SQL is a high performance transaction processing language. It is portable to any Oracle environment and supports all SQL data manipulation commands.
PL/SQL supports all SQL data types and all SQL functions. It also lets you use all Oracle object types. PL/SQL block can be named and stored in a Oracle server and reused as required in other PL/SQL program or from the SQL command line.
Security on PL/SQL structures stored in the server can be managed using the Oracle database objects syntax. You can grant and revoke privileges on these stored PL/SQL program to and from other user in the database.
PL/SQL code can be written using any ASCII text editor. So, it is portable to operating environment in which Oracle runs.
PL/SQL Architecture
PL/SQL Block Structure
PL/SQL block structured language. The units that constitute a PL/SQL program are logical blocks. A PL/SQL may contain one or more blocks. Each block may be divided into three sections as follows:
Declaration Section This section contains the data type and initial value of all variables and constant used in the executable section of the block. This section begins with the keyword DECLARE. This is an optional section. This section also declares CURSORs and used define EXCEPTIONs.
Executable Section This section is mandatory section in the PL/SQL block. This section begins with the keyword BEGIN. All the executable statements are given in this section. This section can also have other PL/SQL blocks inside.
Exception Section This section is an optional section, which has executable statement to handle an exception or error.
Here is the structure of a complete PL/SQL block:
[DECLARE]
-- Declaration Statements
BEGIN
-- Executable Statements
[EXCEPTION]
-- Exception Statements
END;
Each statement or declaration in a PL/SQL block is terminated with a semicolon. A statement may be broken down into multiple lines for readability, and the semicolon marks the end of the statement. More than one statement can appear in one line, separated by a semicolon. A single line of comment is preceded by two hyphens(--). A set of comments can be enclosed in /* and */.
Named and Anonymous block
A Pl/SQL block can be a Named block or an Anonymous block. Anonymous blocks can be used in the server side or in the client side. A Named block may appear in the declaration part of another block.
Conditional and Iterative Control
Control structures are lines of code that control the flow of the PL/SQL program. PL/SQL supports both conditional and iterative control structures.
Conditional and decision-control structures are used to perform an operation or statement based on the outcome of another statement or expression.
IFTHENELSEEND IF statement let you say, If this is true then do this; otherwise do that. Iterative control structure perform one or more statements repeatedly, either a certain number of times or until a condition is met. There are three forms of iterative structure.
LOOP
WHILELOOP
FORLOOP
Syntax and Usage
IF THEN
The IF statement evaluates a condition, and if the condition is satisfied, a set of statement are executed.
IF THEN
Statement 1;
Statement 2;
END IF;
The statements are executed only if the result of the condition is TRUE. The condition always evaluates to a Boolean result of TRUE/FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
END IF;
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END;
IF THENELSE
This is similar to IFTHEN statement but a set of statements can be executed if the condition evaluates to FALSE or NULL.
IF THEN
Statement 1;
ELSE
Statement 2;
END IF;
The statement between THEN and ELSE are executed only if the result of the condition is TRUE, and the statement between ELSE and END IF are executed only if the result of the condition is FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
ELSE
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END IF;
END;
IF THENELSIFUse this structure if you need to select an action from several mutually exclusive conditions.
IF THEN
Statement 1;
ELSIF THEN
Statement 2;
ELSE
Statement 3;
END IF;
If conditon1 is TRUE then statement1 will executes otherwise it will check condition2. If condition2 is TRUE then statement2 executes otherwise statement3 will executes.
Example :
DECLARE
age NUMBER;
BEGIN
age:=&age;
IF (age>=60) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 60 !!!');
ELSIF(age>=40 and age=30 and age100) THEN
EXIT;
END IF;
END LOOP;
END;
WHILELOOP
This loop has a condition associated with it. The condition is evaluate, and, if the result is TRUE, the statements inside the loop are executed. If the condition is FALSE, execution continues from the next statement to END LOOP.
WHILE
LOOP
Statements;
END LOOP;
Example :
DECLARE
no NUMBER :=10;
BEGIN
WHILE ( no THEN
RAISE my_exception2;
EXCEPTION
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION
WHEN my_exception2 THEN
Statements;
END;
Statements;
If there is no enclosing block for the current block, the exception si passed back to the environment that invoked the PL/SQL program.
DECLARE
my_exception1 EXCEPTION;
my_exception2 EXCEPTION;
my_exception3 EXCEPTION;
BEGIN
Statements;
BEGIN
IF < condition1 > THEN
RAISE my_exception3;
EXCEPTION
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION
WHEN my_exception2 THEN
Statements;
END;
Only one exception at a time can be active in the exception handling part of a block. Therefore, if an exception is raised inside a handler, the block that encloses the current block is the first block searched to find a handler for the newly raised exception.
Example 1 :
DECLARE
Enoemp.empno%type;
Enmemp.ename%type;
Esalemp.sal%type;
HsalEXCEPTION;
LsalEXCEPTION;
BEGIN
Eno := &Eno;
SELECT ename, sal into Enm, Esal FROM emp WHERE Eno = empno;
IF ( Esal 4000 ) THEN
RAISE Has;
END IF;
DBMS_OUTPUT.PUT_LINE(Enm|| ||Esal);
EXCEPTION
WHEN Lsal THEN
DBMS_OUTPUT.PUT_LINE(The salary is too Low!);
WHEN Hsal THEN
DBMS_OUTPUT.PUT_LINE(The salary is Standard);
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(Invalid Employee Code!!!);
END;
Example 2 :
DECLARE
BEGIN
FOR i IN ( SELECT empno, ename, sal FROM emp)
LOOP
DECLARE
Lsal EXCEPTION;
BEGIN
IF ( i.sal
( [ mode ] , . )
IS | AS
[ local declaration ]
BEGIN
Executable statements
[ EXCEPTION
exception handlers ]
END [ PROCEDURE_NAME ];
Calling a Procedure
To call the procedure from a block, the command is
PROCEDURE_NAME ( );
To invoked from the SQL prompt using the EXECUTE command
EXECUTE PROCEDURE_NAME( );
Example :
CREATE OR REPLACE PROCEDUR PR1 ( Eno NUMBER )
IS
Enmemp.ename%TYPE;
Esalemp.sal%TYPE;
BEGIN
SELECT ename,sal into Enm, Esal FROM emp WHERE Eno := emp.empno;
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;
Actual Vs. Formal parameter
The variable or expressions referenced in the parameter list of a subprogram all are actual parameters
The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters
The actual parameter and its corresponding formal parameter must to compatible datatype
Argument Modes
Argument modes are used to define the behavior of formal parameters. There are three argument modes to be used with any subprograms.
IN The IN parameter lets the user pass values to the called subprogram. Inside the subprogram, the IN parameter acts like a constant; therefore, it cannot be modified.
OUT The OUT parameter lets the user return values to the called subprogram. Inside the subprogram, the OUT parameter acts like a un-initialized variable. Therefore, it cannot be assigned to another variable or to itself.
IN OUT The IN OUT parameter lets the user pass initial values to the called subprogram and returns updated values to the calling block.
Example 1:
Creating the Procedure :
CREATE OR REPLACE
PROCEDUR PR1 ( eno IN NUMBER, enm OUT VARCHAR2, esal OUT NUMBER )
IS
BEGIN
SELECT ename,sal into enm, esal FROM emp WHERE eno := emp.empno;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;
Calling a Procedure :
DECLARE
Eno emp.empno%TYPE;
Enmemp.ename%TYPE;
Esalemp.sal%TYPE;
BEGIN
Eno := &Eno;
PR1 ( Eno, Enm, Esal );
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal);
END;
Example 2 :
Creating a Procedure
CREATE OR REPLACE PROCEDURE ad(aa IN OUT NUMBER) IS
bb NUMBER;
cc NUMBER;
BEGIN
cc:=aa;
bb:=10;
DBMS_OUTPUT.PUT_LINE(The value from the calling program : ||cc);
aa:=bb;
END;
Calling a procedure
DECLARE
bb NUMBER;
BEGIN
bb:=5;
ad(bb);
DBMS_OUTPUT.PUT_LINE(The changed value : ||bb);
END;Functions
A Function is a sub-program that returns a value. A function must have return clause. The syntax for the function is:
CREATE [ OR REPLACE ] FUNCTION < function_name >
(, . ) RETURN
IS
[ local declaration ]
BEGIN
Executable statements;
[ EXCEPTION
exception handlers ]
END [ function_name ];
Like a procedure, a function has two parts; the specification and the body. The function specification begins with the keyword FUNCTION and ends with the RETURN clause, which specifies the datatype of the result value. The function is exactly same as procedure body. The RETURN statement immediately returns control to the caller environment. Execution then resumes with the statement following the sub-program call.
Example 1:
Specifying a function
CREATE OR REPLACE
FUNCTION fn1 ( esal NUMBER, rate NUMBER) RETURN NUMBER
IS
da NUMBER(8,2);
BEGIN
da:= esal*(rate/100);
RETURN da;
END;
Calling a function from SQL prompt
SELECT empno, ename, sal, fn1(sal,20) as DA FROM emp;
Calling function from PL/SQL block
DECLARE
eno emp.empno%TYPE;
enmemp.ename%TYPE;
esalemp.sal%TYPE;
rtNUMBER(2);
daNUMBER(8,2);
BEGIN
rt:=&rt;
eno := &eno;
SELECT empno, ename, esal INTO eno, enm, esal
FROM emp WHERE empno=eno;
da:=fn1(esal, rt);
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal|| ||da);
END;
Stored Package
A Package is a database object that groups logically related PL/SQL objects. Package encapsulates related procedures, functions together as a logical unit in the database. Packages are made of two components; the specification and the body. A specification is the interface to applications and has declarative statements. The body of the package contains different procedures and functions.Package Specification
The specification is the interface to the application, it declares the procedures and functions. The package specification holds the public declarations, which are visible to the application.
Package Body
The body holds implementation details and private declaration, which are hidden from the application. The scope of these declarations is local to the package body. Unlike a package specification, the declarative part of a package body can contain sub-program bodies. Package can overload procedures and functions, declaring multiple programs with the same name. The correct program to be called is decided at runtime, based on the number or datatypes of the parameters. To create a package, you must first create the package specification. You cannot GRANT privileges on only one procedure or function within a package.
Advantages of package
Modularity
Packages encapsulates related procedures and functions together in a named PL/SQL module.
Easier application design
It is not important to compile the package body completely until the application is complete. When designing an application initially the information in the specification is required. A specification can be coded and compiled without its body. Once the specification has been compiled, stored sub-programs that reference the package can be compiled as well.
Information Hiding
The packages can be specified in which all sub-programs are public that is, visible and accessible or private that is hidden and in-accessible. By hiding implements details from users, integrity of package is protected.
Better Performance
The entire package is loaded into the memory when a procedure, within the package, is called for the first time. This reduce the un-necessary disk I/O and network traffic.
Specifying a package:
CREATE [OR REPLACE] PACKAGE AS
/* Procedures and function declarations */
END [ ];
Creating a package body:
CREATE [OR REPLACE] PACKAGE BODY AS
/* Private variable declarations
Sub-program bodies */
END [];
Example:
CREATE OR REPLACE PACKAGE pkg AS
PROCEDURE addition(a NUMBER, b NUMBER);
FUNCTION higher(a NUMBER, b NUMBER) RETURN NUMBER;
END pkg;
CREATE OR REPLACE PACKAGE BODY pkg AS
PROCEDURE addition(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE(The resultant value is : || c);
END addition;
FUNCTION hiegher(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
IF (a>b) THEN
c:=a;
ELSE
c:=b;
END IF
RETURN c;
END higher;
END pkg;
Dropping Procedures, Function and Package
To drop a procedure the syntax is : DROP PROCEDURE ;
To drop a function the syntax is : DROP FUNCTION ;
To drop a package the syntax is : DROP PACKAGE ;
DataBase Trigger
Triggers are programs that are executed automatically in response to a change in the database. Triggers can be configured to fire, or execute, either before or after the triggering event. The events that can be hooked with triggers include the following.
DML events
DDL events
Database events
DML event triggers can be statement or row triggers. The DML statement trigger fires before or after the triggering statement. The DML row trigger fires before or after each row affected by the statement is changed. You can define multiple triggers for a single event and type, but there is no way to enforce the order in which these multiple triggers will fire.
Trigger Events
EventTrigger Description
INSERTFires whenever a row is inserted into the table or view.
UPDATEFires whenever a row is updated in the table or view.
DELETEFires whenever a row is deleted from a table or view.
CREATEFires whenever a CREATE statement adds a new object to the database.
ALTERFires whenever a ALTER statement changes an object in the database.
DROPFires whenever a DROP statement removes an object from the database.
The syntax for creating a trigger :
CREATE [ OR REPLACE ] TRIGGER
{ BEFORE | AFTER | INSTEAD OF }
ON { table_name | view name }
[ FOR EACH ROW [ WHEN ]]
trigger body
In case of tables BEFORE and AFTER are used. In case of views INSTEAD OF is used.
Example :
CREATE OR REPLACE TRIGGER t1
BEFORE INSERT OR UPDATE OF empno ON emp FOR EACH ROW
BEGIN
:new.ename := UP