Anda di halaman 1dari 122

Database Management System Concepts RDBMS CONCEPTS Introduction: RDBMS is the acronym for Relational Database Management System.

The concept of relational database is known since 1980s but the idea of database Management System is definitely quite old. The most famous RDBMS packages are Oracle, Sybase, and Informix. Before we move to the RDBMS it would be helpful if we first have a brief idea about DBMS and the reason for RDBMS being preferred to DBMS. Database Management System: A database management system is essentially a collection of interrelated data and a set of programs to access the data. This collection of data is called database. The primary objective of a DBMS is to provide a convenient environment to retrieve and store database information. Database System supports single user and multi-user. While DBMS lets only one person to access the database at a given time, RDBMS allows many users to simultaneously access the database. A database system consists of two parts namely the Database Management System and the Database Application. Database Management System is the program that organizes and maintains the information whereas the Database application is the program that lets us view, retrieve and update information stored in the database. DBMS has to protect database against unintentional changes that could be caused by users and application like disk crash etc. in case of multi-user system, it must be capable of notifying any database changes to the other user. Database Management System Services: 1. Data definition: It is a method of data definition and storage. 2. Data Maintenance: It checks whether each record has fields containing all information about one particular item. For example if an employee table is considered, it is seen that all information about the employee like name, address, designation, salary, dept-name are recorded. 3. Data Manipulation: allows data in the database to be inserted, updated, deleted and stored. 4. Data display: this ensures the accuracy of the data. 5. Data Integrity: this ensures the accuracy of the data. Before proceeding further, it is necessary to be familiar with certain terms of DBMS.

1 / 122

By Naveen Jaiswal

Database Management System Concepts Entity: an entity is any object, place, person, concept, or activity about which an enterprise records data. The below table gives an idea about an entity. Name Biscuits Pen price 12.00 8.00 description food item stationary

A vendor has to maintain a list of all the items that he sells like name price, description etc. These are called entity types. For instance, the values that they store may be Biscuits, 12.00, food item respectively. These are called entity instances. Each of these is termed as an entity and Entity is always identified by a rectangle. There exists a relation ship between two entities. For example, a vendor sells many items and many vendors can sell a particular item. Attribute: an attribute is the characteristic property of an existing entity. The difference between attribute type and attribute instance has to be understood. Attribute type is the property of entity type, and attribute instance of entity instance. An ellipse always represents the attributes. Ex: suppose a student is an entity then student name, number, address would be the attributes of the entity student and the specific- Rama, no-15, S.V.nagar etc. are the attribute instances. Below figure illustrates this with an e-r diagram.


Address Student


Roll no.


Name Name Any attribute or set of attributes can be uniquely identify a row in a table. This attribute acts as a candidate for a primary key and is referred to as the candidate key. Candidate key can be chosen as primary key depending on factors like uniqueness, usage etc. the relations among data must be suited in detail before proceeding further with certain things. Relationship among data: A relationship is defined as an association among entities. A relationship type is an association of entity types, while a relationship instance is an association of entity instances. A relationship may associate an entity with itself. Several relationships may exist between the same entities. The three different types of relationships recognized among various data stored in the database are:

2 / 122

By Naveen Jaiswal

Database Management System Concepts One-to-one One-to-many(or many-to-one) Many-to-many

One-to-one: Consider for example a set of students in a class. Each student can have only one roll number. Similarly, each roll number can be associated only with one student. This is the case of one-to-one relation ship. Below shows the relationship.

Student 1



Student 2



Many-to-one A student can register for only one particular course at a time. Where as many students could register for that particular course. Below figure gives the details

Student1 Regist Student 2 Student 3 Course.

Many-to-many A vendor can sell many items and many vendors can sell a particular item. This can be understood from the below figure Vendor 1 Item 1 3 / 122 By Naveen Jaiswal

Database Management System Concepts

Vendor 2 Database Models:

Item 2

Database models are broadly classified into two categories. They are Object-based logical models. Record-base logical models.

The object-base logical model can be defined as a collection of conceptual tools for describing data, data relationships, and data constraints. The record-base logical model describes the data structures and access techniques of a DBMS. There are three types of record-based logical models. They are the hierarchical model, the network model, and the relational model. Consider an example of a company. There are many employees who work in various departments earning a different salary. EMPLOYEE, DEPARTMENT, SALARY Represents the entities about which data has to be recorded. It would be really meaningless if the data just exist in the database. Hence it is necessary that these data should be related to each other. Therefore a database should maintain information about these data and relationships. File management system: The File management system was the first method used to store data in a computerized database. The data item is stored sequentially in one large file. A particular relation ship cannot be drawn between the items other than the sequence in which it is stored. If one has to locate a particular data item, the search starts at the beginning and each item is checked subsequently till the required item is found. These drawbacks in the system necessitated improvisation. Locating a record is tedious. If data has to be inserted the whole file has to be read and rewritten. This can be overcome by adopting an indexing system. An index file contains a subset of the data files based on one or more key fields. There is a pointer to each record in the database. It satisfies ones requirement at the earliest. Any changes in the database have to be updated. The process of updation is also quite tedious. For ex: adding the age to each employees record would require the DBMS to read each record. Then the DBMS writes in to a temporary file and adds the new information after the last field of each record. After the new file is written, the original file is deleted and the temporary file is renamed. The necessity for establishing a relationship among records and 4 / 122 By Naveen Jaiswal

Database Management System Concepts quicker way to access the records led to the development of another model called hierarchical database model. Hierarchical database systems: DBMS Root


Dept 2

Dept 3


Id 1.1

Id 2

Id 2.2

Id 3

Id 3.3







This can be said to have parent-child relationship. The origin of the data tree is the root. Data located at different levels along a particular branch from the root is called the node. The lat node in the series is called leaf. This model supports one-to-many relationship. From the figure above it ca be seen that the nodes in the third level are interrelated. Each child has pointers to numerous siblings and there is just one pointer to the parent thus proving a one-to-many relationship. Proceeding to how to access the data- suppose an information is required, id2, it is not necessary for the DBMS to search the entire file to locate the data. Instead, it first follows the dept2 branch and fetches the data. If an index were used in the HDS as in the FMS the process would definitely he hastened. Here the index would be on a particular level of data. It is not possible to insert a new level in the table without alerting the structure. FMS does not support many-to-many relationship. Suppose a new level is required between the root and the department, the only alternative is to frame an entirely new structure. To set this relationship, multiple copies of the same data must be stored at multiple levels that could cause redundancy of data. To overcome this drawback, the network database model was introduced.

Network database system: This model comes under record-based logical model. The main idea behind this model is to bring about many-to-many relationships. The relationship between the different data 5 / 122 By Naveen Jaiswal

Database Management System Concepts items is called as the sets. This system also uses a pointer to locate a particular record. Let us consider the item-vendor example as shown in figure.

Vendor 1

Vendor 2

Vendor 3

Item 1

Item 2

Item 3

Item 4

If one has to know which vendor(s) is selling a particular item or which particular item the vendor sells, it is completely dependent on the pointer to map out the relationship. But even here in case of large volumes of data it is very difficult to locate the item because it will increase the complexity as it uses pointers, the mapping of data would become very difficult. Since all the models use pointers it increases complexity. To overcome all the drawbacks the idea of relational database system came up. Relational database model: Dr. E.F. Codd first introduced the relational database model in 1970. This model allows data to be represented in a simple row-column format. Each data field is considered as a column and each record is considered as a row of a table. Taking the example of a vendor, the vendors are grouped in one table as given table below. Vendor_details Vno V1 V2 V3 V4 company company1 company2 company3 company4

The description of items is given in the below table.

Item Pno P1 item desc desc1 6 / 122 vno v1 By Naveen Jaiswal

Database Management System Concepts P2 P3 P4 The other table is cost table. Cost Pno P1 P2 P3 P2 vno v1 v1 v2 v3 price 1500 2000 1000 2200 desc2 desc3 desc4 v2 v1 v3

Different relationships between the various tables are achieved by mathematical set functions namely JOIN and UNION. It can also be seen from the above tables that each table has one or more columns with same names as in other table. To get details about a particular item from a particular vendor, the DBMS searches the item table for the name of the item and matches the vno column of the vendor_details table to get the name of the company. The price of the item can be found out by comparing the pno and vno columns in the item and cost tables. Any changes will invoke adding and deleting columns to/from the existing tables. It is not necessary to build the entire database from the scratch. Relational operators: The relational model is based on the solid foundation of relational algebra. Relational algebra consists of a collection of operators that operate on relations. Each operator takes one or two relations as its input and produces a new relation as its output. The main objective of relational algebra is data retrieval. Some of such operators are defined below. Restrict: It extracts specified rows from a given relation based on certain conditions. Consider for example a students table from which records of similar ages are fetched, then the results will as be given in the table below. Table result Rno 15 20 22 30 name Rama saritha suresh raja age 22 22 26 30 7 / 122 rno 12 20 name age

Rama 22 saritha 22

By Naveen Jaiswal

Database Management System Concepts

Project: Extracts specified attributes or columns from a given relation. For ex: if only name and age of the student is to be extracted then the resultant is as shown below. Table Rno 15 30 Product: All possible relations from two existing relationships can be obtained as is illustrated below. Rno 15 name Rama 20 saritha 22 suresh Results Rno 15 15 20 20 22 22 Union: Data present in more than one table can be fetched without join operator. Data present in one table and absent in the other table is also fetched as shown below. Table1 Name rno table 2 Name rno result Name rno name Rama Rama saritha saritha suresh suresh sub maths eng maths eng maths eng sub maths eng name age rno 12 30 result name Rama 20 saritha 22 suresh raja

Rama 22 20 saritha 22 22 suresh 26 raja 30

8 / 122

By Naveen Jaiswal

Database Management System Concepts Asha Rama Saritha Niranjan 1 15 20 10 Anu Anil Saritha Niranjan 11 17 20 10 Asha Rama Saritha Niranjan Anu Annil 1 15 20 10 11 17

Intersect: Common records resent in the described tables alone are fetched. Considering the same example as above, when intersect is performed the result would be as shown below. Result Name Saritha Niranjan Difference: Data from table1 is fetched provided it is not present in table 2. The result would be as given below. Table1 Deptno 10 20 35 name accounts sales computers Results Deptno 15 35 Join: name Marketing Computers. deptno 15 10 20 Table2 name marketing accounts sales rno 20 10

9 / 122

By Naveen Jaiswal

Database Management System Concepts The data from one or more tables that have some data in common are fetched. The following example illustrates a join the ecode. Column of table 1 and table 2 is identical. Table1 Ecode name 25 20 30 basic table1 dept-code 101 201 301 Result Ecode 25 20 30 Divide This operator returns those rows from the divided table that has occurrences that match those in the division table as given below. Table 1 X A B C A E y a b c d e table 2 x a d result x A name Rama saritha venu dept-code 101 201 301 ecode dept-name 25 20 30 sales marketing computers

Rama 3000 saritha 3500 venu 4000

Normalization: Normalization theory is built around the concept of normal forms. Normalization reduces redundancy. Redundancy is unnecessary repetition of data. It can cause problems with storage and retrieval of data. During the process of normalization, dependencies can be identified, which can cause problems during deletion and updation. Normalization theory is based on the fundamental notation of functional dependency. Normalization helps in simplifying the structure of tables.

10 / 122

By Naveen Jaiswal

Database Management System Concepts Suppose for an entity customer if attributes like custno, name, address are required, then it can be perceived that for a particular custno, only one name and address is possible. Hence the attribute name, address are said to be functionally dependent on the attribute custno. There are four levels of normalization. First normal form: For easier understanding of first normal form, consider an example. One employee has different project codes. Hence the projcode is said to be functionally dependent on the attribute ecode. Now consider an unnormalized data that is represented below. Ecode 101 dept accounts projcode 20 40 41 56 78 20 45 hours 90 101 60 40 92 84 22

111 244

computers sales

A relational model does not permit or support such unnormalized tables. The data must be present at least n the first normal form, which appears as shown in below table.

Ecode 101 101 101 111 111 244 244

dept accounts accounts accounts computers computers sales sales

projcode 20 42 60 56 92 20 22

hours 90 101 43 40 23 84 32

11 / 122

By Naveen Jaiswal

Database Management System Concepts Second normal form: In the previous normal form it was noted that there was redundancy of data, and hence the table was decomposed without any lose of information. The problems encountered here were: Insertion: employee details cannot be recorded until the employee is assigned a project. Updation: the employee code and department is repeated. Hence if an employee is transferred to another department, these changes must be reflected everywhere. Any omission will lead to inconsistence. Deletion: if an employee completes his project, his record will be deleted and details pertaining to the employee are lost.

From the table given below easier understanding is enabled. Ecode 101 111 244 dept Accounts computers sales ecode 101 101 101 111 111 244 244 projcode 20 42 60 56 92 20 22 hours 90 101 43 40 23 84 32

It should be noted that for a table to be in the second normal form is should also be in first normal from and every attribute in the record should functionally dependent on the primary key.

Third normal from: A table is said to be in third normal form if it is in second normal form and every non-key attribute is functionally dependent on just the primary key. The primary key here is ecode. The attribute dept-code is dependent on dept. there is an indirect dependence on the primary key, which has to be noticed. It is illustrated below. Ecode 101 303 400 500 dept finance sales sales computers deptcode 909 906 906 908 12 / 122 By Naveen Jaiswal

Database Management System Concepts 600 700 accounts finance 907 909

Even here it was noted that there were problems during insertion, updation and deletion. The relation is thus reduced as shown below. Ecode 101 303 400 500 600 700 dept finance sales sales computers accounts finance dept finance sales computers accounts dept-code 909 906 908 907

Each non-key attribute is wholly dependent only on the primary key. Even the third normal form did not satisfy the needs. Hence, a new form called Boyce-Codd normal form was introduced. Boyce-Codd normal form: The third normal form was not satisfactory for relations that had multiple candidate keys. Hence Boyce-Codd introduced another form. Consider the table below. Custnno 100 101 211 custname Rama Saritha Jyoshna

Here the candidate keys are custcode and custname. The attribute custcode and custname are unique for each row. Consider that another table that has few other details, as shown below. Custnno 100 101 211 100 custname Rama Saritha Jyoshna Rama item code 19 16 29 33 qty 4 6 2 3

The attributes custcode, and custname of the above two tables can be used to link these tables. These act as a foreign key in the second table. These tables can be reduced in order to minimize redundancy. The tables are shown below. 13 / 122 By Naveen Jaiswal

Database Management System Concepts

Custcode 100 101 211 100

itemcode 19 16 29 33

qty 4 6 2 3

custcode 100 101 211

custname Rama saritha jyoshna

Denormalization: Normalization helps in reducing redundancy. But at times when information is required from more than one table, at a faster rate, it is wiser to introduce some amount of redundancy in the table. This intentional introduction of redundancy in to the table is called denormalisation. For example, if the query were used to display the names of students and their marks obtained in each subject, then it would be advised to maintain information about the two tables. For the sake of better performance some amount of redundancy has to be introduced. The language widely used in relational database is structured query language, more popularly known as SQL. It is the standard relational database access language. They can be roughly divided into three categories base on their functions namely data definition language (DDL), data manipulation language (DML), and data control language (DCL).

Data integrity: This ensures the corrective ness and completeness of the data in the database. When the contents of the database are modified the integrity of the database is lost. To maintain the consistency of data, integrity constraints are imposed. They restrict and validate the data values that are inserted or updated in the database. Some of the constraints are: Domain constraint Validation integrity Entity integrity Referential integrity Domain constraints: 14 / 122 By Naveen Jaiswal

Database Management System Concepts This integrity is the simplest data integrity constraint. For example, while creating a table if a column is declared to be NOT-NULL then each time while entering data care should be taken to see that the particular column on which the constraint is imposed has a NOTNULL value. A NOT-NULL constraint can be specified only at the time of table creation. Validity integrity This checks if the data entered in the database matches the column data type. For example, if a column name NAME is defined to be of character type and if one tries to enter a numeric value, then it will display an error message. Most commercial products do not provide a way to restrict a column to a specific data value. A DBMS checks this rule each time an insert or update attempt is made on the column. Entity integrity: An entity refers to any data recorded in the database. The primary key is used as the identifier of the row. Duplication of data is not possible. No component of the primary key is allowed to accept a NULL value. Consider fro example a table having attributes as RNO and name here the attribute RNO is the primary key. Numbers cannot be duplicated. It should have a unique character. Referential integrity: Referential integrity, as its name implies, establishes a parent-child relationship between tables. A foreign key is defined on a column to declare this constraint. Consider an employee table for better understanding.

Parent table Deptno 10 20 30 40 deptname Sales Accounts Computers finance

child table deptno 10 30 40 40 ename niranjan saritha rama Mohan

The deptno of the parent table is the primary key and the deptno of the child table is the foreign key. When a new row is inserted into the child table, its foreign key value must match with one of the primary key values of the parent table. The same rule holds good for updating and deleting rows. To put it in a simplified form any changes in the parent table should reflect in the child table also. This is the rule of referential integrity. 15 / 122 By Naveen Jaiswal

Database Management System Concepts Codds rules A DBMS should obey Codds twelve rules for it to be relational. These twelve rules are given below. The information rule: all information is explicitly and logically represented in tables as data values. The rule of guaranteed access: Every item of data must be logically addressable with help of a table name, primary key value and column name. From this it is understood that any individual item or record can be retrieved with the use of a table name, primary key value of the row and the column name where it is to be found. The systematic treatment of all null values: the DBMS must be able to support null values to represent missing or inapplicable information. They must be distinct from zeros and spaces. Null values for all data types must be same. One of the most important aspects that must be noted hare is that there is a vast difference between a null value and zero or a space. The database description rule. A description of database is maintained using the same logical structure with which data was defined by the DBMS. These are accessible to users with appropriate authority and are stored in the data dictionary. Comprehensive data sub language According to this rule, the system must support the following Data definition View definition Data manipulation Integrity constraints Authorization Transaction management operations

The view updating rule All views that are theoretically updateable must also be updateable by the system. The insert and update rule A single operand must hold good for all retrieval, update delete and insert activities. This rule implies that all the data manipulation commands must be operational on sets of rows in relation rather than on a single row. 16 / 122 By Naveen Jaiswal

Database Management System Concepts

The physical independence rule Application programs must remain unimpaired when any changes are made in storage representation or access methods. The logical data independence rule. The changes that are made should not effect the users ability to work with the data. The change can be splitting the table into many more tables. The integrity independence rule The integrity constraints should be stored in the system catalog or in the database as a table. The distribution rule The system must be able to access or manipulate the data that is distributed in other systems. This is the distribution rule. The nonsubdivision rule. The nonsubdivision rule states that different levels of the language cannot subvert or bypass the integrity rules and constraints. To put it in simple words, if an RDBMS supports a lower level language than it should not bypass any integrity constraints defined in the higher level.

About oracle: All the business organizations maintain large volumes of data for its operations. With more and more people accessing this data for their work the need to maintain its integrity, relevance etc increases. Normally, with the traditional methods of storing data and information in files, the changes that the data loses its integrity and validity are very high. With the birth of new concepts of data storage and manipulation known as database and database management, today, it is possible to maintain data pertaining to any operation with security. A Database is an aggregation of data in contiguous locations in some organized fashion. This organized fashion normally involves storing the data in the form of tables. A table is a unit of storage, which holds data in the form of rows and columns. Thus, a collection of all tables with their inter-relationships could be termed a database. A program or software that can help us to access data and perform certain predefined operations on it is called a Database management system or a DBMS as it is popularly called. The DBMS whose design is based on the relational theory in mathematics is

17 / 122

By Naveen Jaiswal

Database Management System Concepts called the relational database management system or RDBMS. Some of the products in the IT industry based on the RDBMS concepts are Oracle, Sybase etc. Oracle 8.0 is an Object Relational Database Management System (ORDBMS). This offers capabilities of both relational and object-oriented database systems. It supports very large databases that could contain hundreds of terabytes of information. It also provides access to many concurrent users to the order of thousands or ten thousands users. Managing large amounts of data could present administrative and performance challenges. Oracle 8s data partitioning features help to minimize the problem. A large table that is partitioned can enhance performance because accessing can be done on multiple partitions in parallel. Even if one or more partitions fail then the other partitions are available to applications. Each of the partition can be managed individually, thereby allowing more efficient management of the database. Object Relational Database Management System. Oracle 8 is not a pure object oriented database nor is it a pure relational database. It is a hybrid database that has been evolved. It supports both object-oriented concepts and relational database concepts. It supports object-oriented concepts such as encapsulation, polymorphism, and Inheritence. Encapsulation is where the data is bounded to the object so that access to the data can only happen through the behavior accepted by the object. Polymorphism is the ability of an object to react differently to an identical message. Any object reacts differently based on the information supplied and understands the context of the information that has been input. Inheritance is a form of code sharing. New classes are defined on the basis of the classes that already exist. The class that already exists is known as the base class. Extensibility is the ability to add new objects and their associated behavior without affecting the other objects and applications. Oracle products are based on a concept called client/server technology. This concept involves segregate the processing of an application between two systems. One performs all activities related to the database (server) and the other performs activities that help the user to interact with the application (client). A client or front-end application also interacts with the database by requesting and receiving information from the database server. It acts as an interface between the user and the database. Further, it also checks for validation against the data entered by the user. The commonly used front-end tools of Oracle are SQL *Plus, oracle forms, and reports. The database server or back end is used to manage the database tables optimally among multiple clients who concurrently request the server for the same data. It also enforces data integrity across all client applications and controls database and other security requirements.

18 / 122

By Naveen Jaiswal

Database Management System Concepts

Chapter 2 SQL *plus

SQL stands for Structured Query Language. It is able to control relational databases. The SQL implemented by Oracle Corporation is cent present compliant with the ANSI/ISO standard SQL data language. Oracles database language is SQL, which is used for storing and retrieving information in Oracle. A table is a primary database object of SQL that is used to store data. A table holds data in the form of rows and columns. To communicate with the database, SQL supports the following commands. DDL (data definition language): this includes statements like create, alter, drop, grant, revoke etc. commands which are useful to define the data. DML (data manipulation language): this includes commands like insert, select, delete, update which are useful to manipulate the data. 19 / 122 By Naveen Jaiswal

Database Management System Concepts TCL (transaction control language): this includes commands like commit, rollback, savepoint used to control the transactions.

Benefits of using the SQL *plus are listed below: 1. Non-procedural language, because more that one record can be accessed rather than one record at a time. 2. It is the common language for all relational databases. (i.e.) portable and it requires only small modification to make use of in other database. 3. Very simple commands for querying, inserting, deleting and modifying data and objects. Data types: In order to create a table we need to specify a datatype to individual columns in the create table command. In order to fulfill the above requirements, Oracle supports the following data types. Character datatype Again in character data types there are different data types. 1. Char datatype: this type is used when a fixed length character string is required. It can store alphanumeric values. The column length of such a datatype can vary between 12000 bytes. By default it is one byte. If the user enters a value shorter that the specified length then the database would blankpad to the fixed length. In case, if the user enters a value larger than the specified length then the database would return an error. 2. Varchar2 datatype It supports a variable length character string. It also stores alphanumeric values. Maximum size for this datatype would be from 1-4000 bytes. While defining this datatype we should specify the size. Using varchar2 we can save disk space when compared to char. This statement can be justified with the help of an example. Considering a column assigned with varchar2 datatype of size 30 bytes, if user enters 10 bytes of character, then the column length in that row would only be 10 bytes and not 30 bytes. In the case of char, it would still occupy 30 bytes because the remaining would be blank padded. 3. Long data type: this datatype is used to store variable character length. Maximum size is 2 GB. Long datatye has several characters similar to varchar2 datatype. Its length would be restricted based on the memory space available in the computer. The following

20 / 122

By Naveen Jaiswal

Database Management System Concepts restriction needs to be fulfilled when a long datatype attribute is cast on a column in a table. Only one column in a table can have long datatype, which should not contain unique or primary key constraint. The column cannot be indexed Procedures or stored procedures cannot accept long datatype as arguments. Number datatypes: This data type can store positive numbers, negative numbers, zeros, fixed point numbers, floating point numbers of magnitude ranging between 1.0*10^-130 to 9.9*10^125 with a precision of 38. Column_name number Column_name number (p) Column_name (p, s) (p=38,s=0) (fixed point) (floating point)

Where p is the precision, which refers to the total number of digits, it varies between 138, s is the scale, which refers to number of digits to the right of the decimal point, which varies between 84 to 127. Date datatypes: Date datatype is used to store date and time in a table. Oracle database makes use of its own format to store date in a fixed length of 7 bytes each for century, month, day, year, hour, minute and second. Default date datatype is dd-mon-yy. To view systems date and time we can use the SQL function called sysdate (). Valid date is from Jan 1, 4712 BC to DEC 31, 4712 AD. Raw (size): raw datatype is used to store byte-oriented data like binary or byte strings and the maximum size of this datatype is 255 bytes. While using this datatype the size should be mentioned because by default it does not specify any size. Only storage and retrieval of data are possible, manipulations of data cannot be done. Raw datatype can be indexed. Longraw: long datatye is used to store binary data of variable length, which can have a maximum size of 2 GB. This datatype cannot be indexed. Further all limitations faced by long datatype also holds good for long raw datatype. Other datatypes in oracle 8 are LOB: this is otherwise known as Large Object data types. This can store unstructured information such as sound clips, video files etc., up to 4 gigabytes in size. They allow efficient, random, piece-wise access to the data. The LOB types store values, which are known as locators. These locators store the location of the large objects. The location may be stored out-of-line or in an external file. LOB values can be operated upon through the use of the locators.

21 / 122

By Naveen Jaiswal

Database Management System Concepts CLOB: a column with its data type as CLOB stores character objects with single byte character set of varying widths. A table can have multiple columns with its data type as CLOB. BLOB: a column with its data type as BLOB can store large binary objects such as graphics, video clips and sound files. A table can have multiple columns with BLOB as its data type. BFILE: a BFILE column stores file pointers to LOBs managed by file systems external to the database. A BFILE column may contain filenames for photos stored on a CD_ROM. Advantages of LOB datatypes: 1. A table stores small locators for the LOBs in a column in place of the actual objects. In contrast a table stores the LONG column within the table itself. 2. A LOB column can have storage characteristics different from those for the table. It is possible to separate the primary table data from those of the LOB columns to different physical locations. 3. Access of the LOB column returns a locator. 4. Applications can manipulate and access pieces of the LOB. However, for LONG the entire data must be accessed. User defined data types: Besides the oracle internal data types user can defined some data types known as user defined data types. These model the structure and behavior of data in applications. These new data types can be used in tables and other database objects. User defined types make it possible to carry more of the structure into the schema. Rather than having unrelated columns in relational tables, the object relational approach defines types to represent them. When we define the data type we use the create or replace command. See the syntax given below Create or replace type <type name> as object (column1 datatype, column2 datatype.) In the syntax that is given above, the create or replace command is given so that the type could be created or replaced. The keyword precedes the name of the data type itself. Since the type is a database object the keyword object follows it. Following this the column manes and the datatypes are given in the order required by the user. This command is processed as a PL/SQL statement and hence there will not be a semi-colon following the SQL statement. Instead, a black slash is given. Ex: Create or replace type address as object (add1 number(5), add2 varchar2(10), add3 varchar2(5), add4 number(7)) /

22 / 122

By Naveen Jaiswal

Database Management System Concepts The above command creates an object type for us. The object types that are created could be made public. Creating the object types in a schema and granting it to the other users does this. This type could be used in other database objects such as tables, procedures etc. a row could be inserted using the select command. The standard dot notation is used to represent the data type that has been defined by the user. An example of the same will be dealt later, while using the select command. It is possible to nest the user defined types i.e., a type can be enclosed within another type. Ex: create or replace type emp as object (eno number (2), ename varchar2 (10), eadd address) / The above example shows us how we can nest objects. These objects can be used further in other database objects as and when required. Data definition language: The data definition language is used to create an object i.e. a table, alter the structure of an object and also to drop the object created. Now let us look at the concepts related to Data definition language. Table definition: a table is a unit of storage, which holds data in the form of rows and columns. The data definition languages used for table definition can be classified into the following four categories. Create table command: The syntax for creating a table is Crate table <table name> (column definition1, column definition 2); In a table we should specify a unique column name, we should specify proper datatype along with its width, we can include NOT NULL condition when needed, by default it is NULL. Ex: Create table customer (custid number (6), name character (45), address varchar2 (30), city varchar2 (20), repid number (2)); The above statement when executed successfully the message table created will appear. The table name should follow some norms. While naming a table the first letter should be an alphabet. 23 / 122 By Naveen Jaiswal

Database Management System Concepts Oracle reserved words cannot be used to name a table. Maximum length foe a table name is 30 characters Two different tables should not have the same name. Underscore, numerals and letters are allowed but not blank space and single quotes. If the user uses double quotes fro naming his table like inf the upper and lowercase are not equivalent. Fro instance inf and INF and inF are not the same. The additional feature in Oracle 8 is that the tables can be partitioned and stored in different locations as per requirement. A single logical table can be split into many physically separate pieces based on range of key values. Each of the parts of the table is called a partition. Although the partitions are held and managed independently, they can be queried and updated by reference to the name of the logical table. Oracle 8 provides partition transparency. The application doesnt require the knowledge that the table has been partitioned. A partitioned table consists of a number of pieces each having the same logical attributes. There is a difference between a table, which has a single partition, and a table that has no partitions. A non-partitioned table cannot be partitioned later. Each partition is stored in a different segment and has different table spaces. Storing a partition indifferent table spaces has its advantage. 1. Reduce the possibility of data corruption in multiple partitions. 2. Make it possible to back up and recover each partition independently. 3. Make it possible to control the mapping of partitions to disk drives. Partitions can be altered, dropped, rebuilt, merged and truncated. Partitions cannot have synonyms. Clustered tables and their indexes nor snapshots can be partitioned. The syntax fro partitioning a table is given below.

Syntax is Create table <table name> (column name datatype, columnname2 datatype) partition by range(column name) (partition <partition name> value less than <value>, partition <partition name> values less than <value>); The keyword partition makes the table into partitions. The partitions could be just two or more. The maximum value to be held in a partition could also be specified. The placing of the partitions into various table spaces must also be specified. Advantages of table partitioning. The assess of the table values could be faster. Even if one part of the table is locked the other parts could be used for the purpose of transactions. 24 / 122 By Naveen Jaiswal

Database Management System Concepts Reduction in downtime due to data failures. Reduction in downtime for maintenance. Partition independence allows for concurrent use of the various partitions fro various purposes. Partition transparency-which allows fro insensitivity of access to data irrespective of the partitions they are stored in. Ex: Create table employee (eno number(2), ename varchar2(10), eadd varchar2(30)) partition by range (ename) (partition p1 values less than (h), partition p2 value less than (m)); The above example shows how to create a table and also partition the table. This technique is very useful when the database is very large and has to be accessed many times. One of the constraints of having a partitioned table is that it cannot have userdefined types in it. This should be made note of while creating a table with partitions. Command to alter a table. Alter table <table name> modify (column definition); Alter table <table name> add (column definition); This command is used When a user wants to add a new column. When a user wants to modify the existing column definition( to change the width of the data type or data type itself.) To include or drop integrity constraints. We can decrease the length of an existing column datatype provided it is empty. No such restrictions, while increasing the length of an existing column. Ex: Alter table customer modify (custid number(8)); Here we are changing the width of an existing column custid from number(6) to number(8). Ex: alter table customer add (pin number(7)); Here we are adding extra column to the table customer. When a table is created with a partition it can be altered to merge two partitions or a single partition can be split into two. We can make use of the alter table add partition to 25 / 122 By Naveen Jaiswal

Database Management System Concepts append a partition to a table. If a table is not partitioned when it was created then the table cannot be partitioned using the alter table command. The split partition clause can be used to add a partition in the beginning of a table or in the middle. Ex: Alter table employee add partition p3 values less than (r); When we add a partition to a table we must remember that the partition can be added only to the end of the table. Ex: alter table employee split partition p1 at (c) into (partition p1, partition p3); The above example shows how a single partition can be split into two with the help of the split partition keyword. A partition can be renamed using the rename option. Ex: alter table employee rename partition p2 to par2; A partition can be altered to delete all the rows as shown below. Alter table employee truncate partition p1; Command to drop a table: Syntax to drop the table is Drop table <table name> This command is used to delete a table completely. Ex: drop table customer; By executing the above statement we will see the message table dropped. Truncating a table: Syntax is Truncate table <table name>; This command will delete all the rows from the table. Ex: truncate table employee;

26 / 122

By Naveen Jaiswal

Database Management System Concepts Here all the rows of the table employee are deleted and only the structure is remaining. The space that is used for the storage can be reclaimed or not depending on the user. Ex: Truncate table employee reuse storage; The above command deletes all the rows from the table employee and reuses any space that was occupied by the rows of the table employee. Viewing the tables structure Syntax is Desc <table name> Ex: Desc customer; The above statement will display the structure of the customer table.

Integrity constraints:
Till now we have seen the creation of tables in SQL *plus. Now we will look at the integrity constraints, which would be defined along with the columns in a table to avoid invalid entries. An integrity constraint in a mechanism used to prevent invalid data entry into the table. It is nothing but enforcing rule for a column in a table. We see different integrity constraints we use. Domain integrity constraints: maintains values according to the specifications like NOT NULL condition, so that the user has to enter a value for the column on which it is specified. NOT NULL and Check constraints fall under this category. 27 / 122 By Naveen Jaiswal

Database Management System Concepts

We know that by default all columns in a table allow NULL values. When a NOT NULL constraint is enforced on a column or a set of columns in a table, it will not allow NULL values. Zero and NULL are not equivalent. Ex: create table customer1 (custid number(6) constraint cust not null, name varchar2(20)); This command will ensure that the user enters null values for the custid column on the customer table, failing which it returns an error message. Check: These are rules governed by logical expressions or Boolean expressions. Check constraints cannot contain sub queries. The following example will help us to understand it much better. The following example creates a table order_info with a check constraint to restrict the values of ordid to be with in 100 Ex: Create table order_info (ordid number(4) constraint checkit check (ordid>100), orderdate date, complan character(1), custid number(6), shipdate date, total number(8,2)); Entity integrity constraints: These maintenances uniqueness in a record. An entity is any data recorded in a database. Each entity represents a table and each row of a table represents an instance of that entity to identify each row in a table uniquely we need to use this constraint. Unique constraints Usage of the unique key constraint is to prevent the duplication of values within the rows of a specified column or a set of columns in a table. Columns defined with this constraint can also allow Null values. If unique key constraint is defined in more than one column i.e. combination of columns, it is said to be composite unique key. In the above case, combination of columns cannot be duplicated. Maximum combination of columns that a composite unique key can contain is 16. Ex: Create table price (prodid number(6), stdprice number(8,2), minprice number(8,2), startdate date, enddate date constraint unidate unique); 28 / 122 By Naveen Jaiswal

Database Management System Concepts

The same constraint can be enforced using table level syntax also Ex: create table price (prodid number(6), stdprice number(8,2), enddate date, startdate date, constraint unitab unique(enddate)); example for composite unique key follows. Create table customer1 (custid number(6), name varchar2(30), constraint compuni unique(custid,name)); In the above example combination of columns custid and name cannot be duplicated. Primary key constraints: This constraint avoids duplication of rows and does not allow Null values, when enforced in a column or set of columns. As a result it is used to identify a row. A table can have only one primary key. If a primary key constraint is assigned to more than one column i.e. for combination of columns it is said to be a composite primary key, which can contain a maximum of 16 columns. Primary key constraint cannot be defined in an alter table command when the table contains rows having Null values. Ex: create table customer (custid number(6) constraint prim primary key, name char(45), address varchar2(20), city char(30), repid number(4), creditlimit number(8,2)); The same constraint can be enforced using table level also. Create table item(itemid number(6),ordid number(6), prodid number(6),actualprice number(8,2),qty number(8,3), constraint prim primary key(itemid)); Example for composite primary key: Alter table order_info add primary key (ordid, orderdate) disable; The above command ensures that no two rows in the table have a same value for both prdid and orderdate. Since the constraint is disabled it can only be defined in the oracle database dictionary but not enforced. Referential integrity constraints: To establish a parent-child relationship between two tables having a common column, we make use of referential integrity constraints. To implement this, we should defined the

29 / 122

By Naveen Jaiswal

Database Management System Concepts column in the table as a primary key and the same column in the child table as a foreign key referring to the corresponding parent entry. Foreign key: a column or combination of columns included in the definition of referential integrity, which would refer to a referenced key. Referenced key: it is a unique or a primary key, which is defined on a column belonging to the parent table. Child table: this table depends upon the values present in the referenced key of the parent table, which is referred by a foreign key. Parent table: this table determines whether intersection or updation of data can be done in child table. This table would be referred by childs table foreign key. Ex: create table order_info1 (ordid number(4), orderdate date, complan character(1), shipeddate date, total number(8,2), custid number(6) constraint fk references customer(custid)); The above command creates a table order_info1 and will also enable a foreign key on custid column which would refer to the primary key on the custid column of the customer table has been defined with either unique key or primary key constraint. The foreign key constraint ensures that all values in the column custid in order_info1 table have a corresponding custid value in the customer table. Note: the referential integrity constraint does not use foreign key keyword to identify the columns that make up the foreign key because the constraint is defined at column level on custid column, the foreign key is automatically enforced on the custid column. To define a referential integrity constraint using table level syntax Ex: create table order_info2 (ordered number(4), orderdate date, complan character(1),shipdate date, total number(8,2), custid number(6), constraint fk foreign key (custid) references customer(custid)); On delete cascade clause If all the rows under the referenced key column in a parent table are deleted, then all the rows in the child table with dependent foreign key column will also be deleted automatically. Ex: Create table order_info3(ordid number(4), orderdate date, complan character(1), ship_date date, total number(8,2), custid number(6), constraint fk references customer (custid) on delete cascade); 30 / 122 By Naveen Jaiswal

Database Management System Concepts

Foreign key keyword is an optional one and can be used for a more understandable syntax and missing it doesnt cause any error. Because of the on-delete-cascade option we find that deleting a particular custid value from the customer table, results in the deletion of the corresponding rows from the order table also. For ex: if custid 200 is deleted from the customer table, then, the depending rows in the order table also get deleted. Referential integrity constraints with composite keys: A composite foreign key can contain a maximum of 16 columns. It must either refer to a composite unique key or a composite primary key. Further, to maintain referential integrity constraints with foreign key, each row in the child table must satisfy on one the conditions mentioned below. The value of at least one of the columns, which make up the foreign key, can be null. The value of foreign key columns must match the value of referenced key column. In addition to the above options a default constraint checking is possible in oracle 8. When a constraint is made deferrable, the oracle 8 leaves the checking until the transaction is committed. Deferred constraint checking is exactly what it says: it can be used to defer the checking of constraints but it cannot be used to defer trigger execution. To support deferred checking of constraints, each constraint has two additional attributes. It may be deferred or not deferred. It may be initially deferred or initially immediate. Syntax Alter table <table name> add constraint <constraint name> foreign key <column name> references <table name> deferrable initially deferred; The above syntax when used will add a constraint, which will by default only be checked at commit time. The constraint, and the fact that is checked at commit time, are both encapsulated within the definition of the table. A user with enough knowledge of the data dictionary can find out that the deferred constraint exists, but code which manipulates the table need not know about the existence of this feature. An option that could be used to set all the constraints to deferred or enable all the constraints is available and has the following syntax. Set constraints all immediate; This enables all constraints. To disable all constraints, Set constraints all deferred; However, there is a minor design trap in these forms since some of the constraint checking which is required within the transaction may be marked as not deferred. Set 31 / 122 By Naveen Jaiswal

Database Management System Concepts constraints lasts for the duration of the transaction, but neither it nor subsequent statements issue warnings if the actions which it is being asked to take cannot be applied because one of the constraints encountered is not deferrable. In oracle 7 a constraint could not be enabled as long as there was data in the table that violated it. This means that often the constraints were never enabled. Oracle 8 has an option to enforce a constraint rather than enable it. Enforcement is applied to any future inserts and updates, but does not care about data already in the table. The syntax is : Alter table <table name> enforce constraint <constraint name>; This option can also be very useful when enabling a constraint on a very large table since it avoids the considerable effort of having to check every row. Data manipulation language: Data manipulation language commands are the most frequently used SQL commands, and they are insert, delete, select, and update. Insert command The insert command is used to add the rows to a table. While using this command the values are separated by commas and the datatypes char and date are enclosed in apostrophes. The values must be entered in the same order as they are defined in the table. Syntax is Insert into <table name> values (a list of data values); Ex: Insert into order_info values(200, 25-jul-77, b, 5 , 17-apr-76, Null); If the user wants to skip any one of the fields then he can enter Null against that columns value. In example above null has been inserted for the column total To add more than one record into the table see the following example Insert into order_info values(&no,&ordate, &comm, &shipdat , &total); To insert null values in the field, instead of entering null we can list only the columns and values that we want to enter. The syntax is Insert into <table name>(column_names) values (list of values); To insert date values other than the standard format for date we use a function to_date.

32 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: Insert into order_info values (150, 7-jan-77, b, to_date(14/2/78 9:30,dd/mm//yy hh: mi), 6000); We know that the standard format for the date datatype is dd-mon-yy. In the table order_info, for columns like ord_date and ship_date when the user enters a date with a format say mm/dd/yy then it can be converted to the standard data format with the help of the to_date function. Date formatting function to_date consists of two arguments, the first argument specifies the char value that contains the date and time, and the second one specifies the format according to which date and time has to be displayed. Insert command with a query We can use an insert command along with a query to select rows from one table and insert them into another table. Only those columns and rows selected by the query will be inserted. Ex: insert into ord (select * from order_info);

The above statement will copy all the rows from the order_info table to ord table, provided a table named ord exists having the same structure as order_info. Ex: insert into employee (eno, eadd) values (10, address(100, Gandhi st, tirupathi, 517502); The above statement shows us how to insert values into the table that contains a userdefined type. The values being inserted into the table are preceded by the type name. This is the name that is given when type was initially created. This example shows how to insert into a column that has a user defined type. Select command: To perform a query we use the select command. The query is a request for information. It is the most common database operation used. The syntax for select command is given below Select column_name. From table_name; Ex: select * from oeder_info; We can either display all the columns in a table or only specified columns from the table. For ex: if we want only columns ship_date and custid from the order table, then, we include only those columns in the select statement. The order of column names in the select command specifies the order in which they should be displayed.

33 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: select shipdate, orderdate,custid from order_info; The above ex: displays ship_date first, followed by ord_date and custid. On the other hand, if we enter the column name in the reverse order, then it would be displayed. Select distinct rows: to prevent the selection of duplicate rows we use distinct clause in the select command. Ex: select distinct repid from customer; This example would eliminate duplicate values present in repid column of the customer table. Where clause in the select command: to select specific rows from a table we include a where clause in the select command. It can appear only after the from clause. We can retrieve only the rows which satisfy the where condition. To arrange the displayed rows according to some pre-defined order we can use the order by clause. It is also used to arrange rows in descending or ascending order. The order by clause can also be used to arrange multiple columns. The syntax for the select command along with the where clause is given below. Select columns from the table where condition [order by]; In order to retrieve rows from the customer table for which repid equals 20 and to order the column name in ascending order, the following command is used. Select custid, name from customer where repid =20 order by name; The order by clause should be the last clause in a select command. The where clause in a select command which retrieves specific rows from a table is also applicable to delete and update commands. In these cases it will delete or update row or rows from a table according to conditions specified by the where clause. We can arrange the rows with reference to one or more columns. The following example arranges the customer table by name and within each name it arranges in the descending Order of max_credit. Ex: Select * from customer order by name, creditlimit desc; Ex: create table cust as select * from customer; In the above example we create a table cust and copy the records into it form the table customer with a single statement, by including a select clause in a create table command. But to select from a table that has user-defined data types, we use the name of the type.

34 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: select eno, ename, eadd from emp; The select statement shown above gives the name of the type with which the values from the user defined object type can be obtained. When we want to select only specific columns from the table we give the column names. These columns by themselves may be of a user defined data type. Ex: select eno, e.eadd.add1 from emp e; In the above ex: selection of specific columns in involved. When a column which has a user defined data type is used we have to use an alias name for the table from which the columns are being selected. After the alias name we give the column name followed by the attribute from the user-defined type. This retrieves a single row with two columns from the user-defined type. This retrieves a single row with two columns from the database. An alias name is required because the compiler associates the variable name with as address or memory location. This process is known as binding. This association lasts through all subsequent transactions until a recompilation occurs. Before binding all references must be resolved. This process is called name resolution. All names are considered to be in the same name space. One declaration or definition in an inner scope can hide another in an outer scope. Hence an alias name is required so that the exact date is retrieved and displayed. To retrieve specific rows from the table we have to use the where clause as mentioned before. In addition to this we have to use the dot notation if the table contains user defined types. We also should use an alias name. Update command: Update command is used to alter the column values in a table. The update command consists of a set clause and an optional where clause. The syntax for the update command is given below. Update table name set field=value, where condition; In the above syntax, the where clause and the set clause can also include queries. Update sets each field with the value that we supply, provided it satisfies the where condition. In the following example a query has been included in the where clause to select rows which are to be updated. Ex: update item set actualprice=200.00 where prodid in (select prodid from product); The result of the above command can be verified by selecting rows from the customer table. We can also include a query in the set clause of an update command. With the update command one can update rows in the table. A single column may be updated or more than one column could be updated. Specific rows could be updated based on a specific condition. The following example shows to update tables that contain user defined data types. 35 / 122 By Naveen Jaiswal

Database Management System Concepts

Ex: update employee set eadd= address(10, iind street, chennai,333456) where eno=10; The above where clause allows updation of a single row. To update tables that have user defined types and specific columns off the type the dot notation is followed. Here also the table is given an alias name Ex: update employee e set e.eadd.add2=bglr where e.eno=10; Delete command: After inserting rows in a table we can also delete them if required. The delete command consists of a from clause followed by an optional where clause. The syntax is Delete from <table name> where condition; To delete several rows from a table, select the rows with appropriate conditions in a where clause. The where clause can also include a query. Ex: delete from customer where custid in (select custid from order_info where commplan =b); The above example will delete a row from customer whose comm_type is b. The delete command allows deletion of rows from a table. A single row or many rows could be deleted. Alternatively, all the rows of a table could also be deleted while the structure is maintained. To delete specific rows from the table the where clause is used in combination with the delete command. To delete rows from a table that contain a userdefined type we have to use the dot notation to identify the column and use an alias name for the table to resolve the locations. Ex: delete from emp e where e.eadd.add1=10; Operators in SQL *plus: Arithmetic operators: to perform calculations based on number values, we include arithmetic expressions in SQL command. An arithmetic expression consists of column names with number datatype and an arithmetic operator connecting them. The arithmetic operators are addition (+), subtraction (-), multiplication (*) and division (/). Ex: select prodid, stdprice, minprice, stdprice+minprice from price where enddate =25jul-77;

36 / 122

By Naveen Jaiswal

Database Management System Concepts We know that stdprice+minprice is not a column in the table price, yet SQL would display it as a separate column. Arithmetic operations can also be performed in a where clause. If there are several operations in an arithmetic expression then the precedence of each operator must be known. * and / have equal precedence. Whereas + and have equal lower precedence. Ex: select ordid, itemid, 100 *(actualprice +qty) from item where prodid =200; In the above example, only after adding actual price with qty it is multiplied by 100. If parenthesis is omitted then multiplication will be performed first followed by addition. Comparison operators: Comparison operators are used in conditions to compare one expression with another. The comparison operators are =,!=,>,<,<=,>=, between, in, like, and is null. The last four operators mentioned above can also be used for checking the not conditions like not between, not like and so on. Ex: Select * from order_info where total>3000; The above will display the rows which have total greater than 3000. Ex: select * from order_info where not (custid =2 or custid= 4); The above command will display all columns where custid is neither 2 nor 4. The in operator can be used to select rows that match one of the values in a list. Ex: select * from order_info where shipdate in (12-jan-77, 12-jan-88); The above ex lists all the columns in a table for which ship date lies in the given list when we search for character values using in operator, the column name must exactly match with the values present in the list. In the case of LIKE operator, which is used to search a character pattern, we need not know the exact character value. The like operator recognizes special characters like % and _. The former can match zero or more characters, while the latter matches exactly one character. % cannot be used to match a null character. Ex: select name, address, city from customer where name like n% ; The above command will display the columns name, address, city and phone whose name begins with v. Ex: select * from customer where name like R_m;

37 / 122

By Naveen Jaiswal

Database Management System Concepts The above command lists all the columns from the customer table whose names are three character long, starting with R and ending with m Logical operators: Logical operators are used to combine the results of two conditions to produce single results. The logical operators are AND, OR and NOT. Ex: select * from order_info where shipdate> 1-jul-77 and total<5000; The above displays all the columns from order_info of the rows whose both the conditions mentioned are satisfied. Precedence of operators. Arithmetic operators. Comparison operators NOT logic operator AND logic operator OR operator. Highest precedence.

Lowest precedence.

Transaction control language: A transaction is a logical unit of work. All changes made to the database between commit and/or rollback operations can be referred to as a transaction. Transaction changes can be made permanent to a database only if they are committed. A transaction begins with an executable SQL statement and ends explicitly with either rollback or commit statements and implicitly, i.e., automatically, when a DDL statement is used. Commit: this command is used to end a transaction. Only with the help of the commit command, transaction changes can be made permanent to the database. This command also erases all savepoints in the transaction thus releasing the transaction locks. The syntax is given below. Commit work; or Commit; Rollback: a rollback command is used to undo the work done in the current transaction. We can either rollback the entire transaction so that all changes made by SQL statements are undone, or rollback a transaction to a save point so that the SQL statements after the save point are rolled back. The syntax is: Rollback work; or Rollback; these are used to rollback entire transaction.

38 / 122

By Naveen Jaiswal

Database Management System Concepts To rollback to a particular stage in a transaction, i.e., a save point, we say Rollback to savepoint a; Where a is the save point. Save point: savepoints are like markers to divide a very lengthy transaction to smaller ones. They are used to identify a point in a transaction to which we can later rollback. Thus savepoint is used in conjunction with rollback, to rollback portions of the current transaction Syntax is Savepoint a; here a is the save point. Ex: update oeder_info set total=8000 where ordid=200; Savepoint a; Update order_info set total=9000 where ordid=300; Savepoint b; Select sum (total) from order_info; Rollback to savepoint a; Update order_info set total=5000 where ordid=400;

In the above example we have two markers a, b and a rollback statement which rolls back the SQL statements to the save point a. Privilege commands: Privilege is the right to access another users objects (tables, views..). We can grant privileges (insert, delete, select.) to others and can also withdraw the granted privilege by using the privilege commands grant and revoke. Grant privilege command: If a user creates a table named customer, there is no necessity for the user to be given any privilege to use it. He becomes the owner of the table. In case, the user want to share an object with others, the appropriate privileges can be granted on that particular object to others. Objects are logical data storage structures like tables, views, sequences, indexes, and synonyms etc. object privileges can be granted to others using the SQL command grant. The syntax is Grant <object-privileges> on <object-name> to <user name>; Ex: grant select, insert, delete on customer to accounts; After successful execution of the above command, the message grant succeeded will be displayed. We can also specify ALL to grant all the privileges. 39 / 122 By Naveen Jaiswal

Database Management System Concepts

Ex: grant select on customer to admns with grant option; The above example grants the select privilege on customer table to admns along with with grant option, so that admns can pass the respective privilege to others. Revoke privilege command: To withdraw the privilege, which has been granted to a user, we use the revoke command. This command is closely similar to that of the grant command in its format. The syntax is Revoke <privileges> on <object-name> from <username>; Ex: revoke select, insert, delete on customer from admn; To withdraw select, insert and delete privileges on the object customer from the user admns, we use the above statement. After successful execution of the above statement the message revoke succeeded will appear. SQL * plus functions: A function of SQL * plus function takes one or more arguments and returns a value. One can classify functions into single row functions and group functions. Single row functions: a single row function or a scalar function returns only one value for every row queried in the table. Single row functions can appear in a select command and can also be included in a where clause. The single row functions can be broadly classified as: Date functions Numeric functions Character functions Conversion functions Miscellaneous functions.

Date functions: They operate on date values producing output, which also belongs to date datatype, except for months_between date function, which returns a number. Add_months: this date function returns a date after adding a specified date with the specified number of months. The format is add_months (d, n) where d is the date and n is the number of months. Ex: select add_months (sysdate, 2) from dual; 40 / 122 By Naveen Jaiswal

Database Management System Concepts The above will result in 13-Mar-00 if sysdate is 13-may-00 The sysdate variable will display the system date. All these functions use the system table duel. It is a table, which is automatically created by oracle along with the data dictionary. Dual table has one column defined to be of varchar2 type and contains only one row with value x. Last_day: the format is last_day(d), which returns the date corresponding to the last day of the month Ex: select sysdate, last_day (sysdate) from dual; The output is



Months_between: to find out the number of months between two dates, we use the months_between function. Its format is Months_between (d1,d2) where d1 and d2 are dates. Ex: select months_between (todate (1-5-77, dd-mm-yy), todate (1-3-77,dd-mmyy)) from dual; The result will be 2. Next_day: the format for this function is Next_date(d, day) where d represents date and day implies any weekday. Ex: select next_day (sysdate, Tuesday) from dual; The Tuesday that immediately follows the sysdate will be displayed. If sysdate is 8-mar00, then 14-mar-00 will be displayed which is the next Tuesday. Round: this function returns the date which is rounded to the unit specified by the format model. Its format is Round (d, [fmt]) where d is the date and fmt is the format model. Fmt is only an option, by default date will be rounded to the nearest date. Ex: select round (todate(23-oct-96,dd-mm-yy), year) from dual; 1-jan-97 will be the result. 41 / 122 By Naveen Jaiswal

Database Management System Concepts

Ex: select round (to_date(23-oct-96,dd-mon-yy),day) from dual; 23-oct-96 will be the result because it rounds 20-oct-96 to the nearest Sunday. Truncate: this function returns the date with the time portion of the day truncated to the unit specified by format model. The syntax is trunc(d,[fmt]); if fmt is neglected, then date is converted to the nearest day. Ex: select trunc (to_date (23-oct-96,dd-mon-yy),month) from dual; 01-oct-96 will be the result. Greatest: the function is greatest (d1, d2, d3), where d1, d2, d3 are dates. This function returns the latest date present in the argument. Ex: select greatest (2-oct-96, 17-apr-98) from dual; Output will be 17-apr-98. Arithmetic operations on date values: we can perform arithmetic operations on date values, which comprises date+number, date-number and date-date. Ex: select ordid, shipdate +15 from order_info where ordid =600; Character functions: Character functions accept character input and return either character or number values. The character functions supported by oracle are given below. Function Initcap(char) Lower(char) Upper(char) example select initcap(niranjan) from dual; select lower(NIRANJAN)from dual select upper(niranjan) from dual; result. Niranjan niranjan NIRANJAN niranjan abcniran sirasjas black and blue. cd By Naveen Jaiswal

Ltrim(char,set) select ltrim(abcniranjan,abc) from dual; Rtrim(char,set) select rttim(abcniranjan, jan)from dual;

Translate(char,from,to) select translate(niranjan,n,s) from dual Replace(char, select replace(jack and juej,bl)from dual Searchstring,[repstring]); Substr(char,m,n) select substr(abcdefg,3,2) from dual; 42 / 122

Database Management System Concepts

Soundex is another character function that compares words that are spelled differently, but sound alike. Ex: select name from customer where soundex (name)= soundex (smythe); It returns all names, which sound like smythe if present. If smith is present in the table then it is returned. Chr function will return the character value for the number given within the braces. Ex: select chr(67) from dual; The above statement will return C which is the character equivalent of the number 67. The chr function returns the character equivalent of the number that is given within the braces. Lpad: this function takes three arguments. the first argument is the character string, which has to be displayed with the left padding. The second is the number, which indicates the total length of the return value. The third is the string, with which the left padding is to be done when required. Ex: select lpad(niranjan,15,*) from dual; will print as *******niranjan.. rpad: the function rpad does exact the opposite of the lpad function. The number of arguments it take is the same as lpad function. Ex: select rpad(niranjan,15,*) from dual; will print as niranjan*******. Numeric functions: Abs Ceil(n) Cos(n) Cosh(n) Exp(n) Floor(n) Power(m,n) Mod(m,n) Round(m,n) Trunc(m,n) Sqrt(n) select abs(-20) from dual; select ceil(33.867)from dual; select cos(180) from dual; select cosh(0) from dual; select exp(4) from dual; select floor(100.2) from dual; select power(4,3) from dual; select mod(25,7) from dual; select round(127.648,2) from dual; select trunc(324.899,2) from dual; select sqrt(9) from dual; 20 34 -.5984601 1 54.59815 100 64 4 127.65 324.89 3

43 / 122

By Naveen Jaiswal

Database Management System Concepts Ln(n) logarithm) select ln(2) from dual; .69314718(finds the natural

Conversion functions. Conversion functions convert value from one data type to another. To_char() the function is to_char(d [,fmt]), where d is thew date, fmt is the format model, which specifies the format of date. To_char conversion function converts date to a value of varchar2 datatype in a form specified by date format fmt. If fmt is neglected then it converts date to varchar2 in the default date format. Ex: select to_char(sysdate,ddth of fmonth yyyy) from dual; The above statement displays the date according to the format specified in the format modal. If sysdate is 14-03-2000 then it will print 14th of March 2000. Miscellaneous functions: Uid: this function returns the integer value corresponding to the user currently logged in. Ex: select uid from dual; the result could be a number.

User: this function returns the logins user name, which is in varchar2 data type. Ex: select user from dual; The result could be name of the user. Group functions: A group function returns a result based on group of rows. The group functions supported by oracle are given below. Avg: gives the average of a column in a table Ex: select avg(total) from table_name; gives the average value of total. Max : gives the highest value in a column Ex: select max(custid) from table_name; gives the highest value of custid. Min: gives the least value of the column. Ex: select min(custid) from table_name ; gives the lowest value of custid. Sum: gives the sum of the column 44 / 122 By Naveen Jaiswal

Database Management System Concepts

Ex: select sum(total) from table_name;

summation of total.

Count function: in order to count the number of rows, count function is used. It can take three different arguments. Count(*): it counts all, rows inclusive of duplicates and nulls. Ex: select count(*) from customer; Count(col_name): it counts number of values present in the column without including Nulls. Ex: select count(total) from order_info; This example counts the number of rows after eliminating nulls in the column total. Count(distinct col_name): this counts the number of rows in the column eliminating nulls and duplicates. Ex: select count(distinct ordid) form order_info; Group by clause: simultaneous usage of column name and group function is totally absurd in a select statement. This flaw can be removed by using group by clause in the select statement. If an SQL statement consists of a where clause and group by clause, then the latter should follow the former. Ex: select max(custid), repid from customer group by repid; The example lists maximum custid for every unique repid. Having clause: the having clause is used to specify certain conditions on rows, retrieved by using group by clause. This clause should be preceded by a group by clause. Ex: select max(custid), repid from customer group by repid having count(*) >=2; The above example is same as previous example except that the count should be greater than 2. Set operators and joins: Set operators combine the results of two queries into single one. The following set operators aid SQL in joining queries to retrieve rows. The columns in the select statements joined using the set operators should adhere strictly to the norms mentioned below.

45 / 122

By Naveen Jaiswal

Database Management System Concepts The queries which are related by a set operator should have the same number of columns and the corresponding columns must be of the same datatype. Such a query should not contain any column of type long. The label under which the rows are displayed are those from the first select statement. Union: the union operator returns all distinct rows selected by either query. Ex: select custid from customer union select ordid from order_info; The above example combines the results of two queries with union operator, which eliminates duplicate rows. Union all: the union all operator returns all rows selected by either query including duplicates. Intersect: intersect operator returns only rows that are common to both the queries. Ex: select ordid from ord_info intersect select itemid from item; Minus: minus operator returns all distinct rows selected only by the first query and not by the second. Ex: select ordid from item minus select ordid from order_info; While using the orderby clause, it must follow the last select statement and we must order by integer and not by column name. Ex: select ordid, custid from order_info union select itemid,prodid from item order by 2; The above example displays distinct rows selected by either query, ordered by the second column stated in both queries. Since the column names are different in the above queries, we an integer in the order by clause instead of a column name. Joins: the purpose of a join is to combine the data spread across tables. A join is actually preformed by the where clause which combines the specified rows of tables. The syntax for joining tables is as follows. Select columns from table1, table2 where logical expression; The logical expression specifies how the tables are joined. There are basically three different types of joins. Simple join Self join Outer join. 46 / 122 By Naveen Jaiswal

Database Management System Concepts

Simple join: it is the most common type of join. It retrieves rows from two tables having a common column and is further classified into equi-join and non-equi-join. Equi-join: a join that is based on equalities is called equi-join. Ex: select * from item, order_info where item.ordid=order_info.ordid; In the above statement, item.ordid=order_info.ordid performs the join operation. It retrieves rows from both the tables provided they both have the same ordid as specified in the where clause. Since the where clause uses comparison operator equal to (=), to perform a join, it is said to be an equi join. Note: In the above example column name is prefixed by the table name because both the tables have the same column name ordid. Therefore to distinguish between them we use table names. If the column names are unique, then we need not prefix it with the table name. Non equi-join: a non equi-join specifies the relationship between columns belonging to different tables by making use of the relational operators. (>, <, <=, >=, <>) other than =. Ex: select * from customer, order_info where customer.custid> order_info.custid and customer.repid=10; The above example joins the rows of customer table to that of order_info table provided custids belonging to customer table are greater than custids belonging to order_info table. Table aliases: to prevent ambiguity in a query we include table names in the select statements. Table aliases are used to make multiple table queries shorter and more readable. As a result, we give an alias to the table in the form clause and use it instead of the table name throughout the query. Ex: select c.*, o.* from customer c, order_info o where c.custid > o.custid and repid =10; The above example is same as previous example. But uses aliases which are defined in the from clause are separated from the table name by spaces. Note: c.* , o.* will retrieve all columns from both the tables provided the conditions in the where clause is satisfied. Self join: joining of table to itself is known as a self-join, i.e., it joins one row in a table to another. It can compare each row of the table to itself and also with other rows of the same table.

47 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: select o.* from order_info o order_info u where o.ship_date >= u.ord_date and o.custid=u.custid ; The above example will display only those rows from the order_info table whose ship_date is either greater than or equal to the order_date provided they both have the same custid. Outer join: the outer join extends the results of a simple join. An outer join returns all the rows returned by simple join as well as those rows from one table that do not match any row from the other table. The symbol (+) represents outer join. Ex: select order_info.ordid, item.ordid from item, order_info where order_info.ordid (+)=item.ordid; The above example will also retrieve rows from item table which does not have any matching records in the order_info table because of the presence of an outer join (+). Outer join sumbol (+) is used after order_info.ordid in the where clause, to treate order_info table as though it contained an extra row with nulls. So that this null row of order_info table can be joined to any row of the item table. Locks: The need for locking can be clearly understood with the following discussion. consider an organization where multiple users want to access the same table say, product. In such a case, the following situations occur.

User1 Updates row1 of product; Commit;

user2 deletes row1 of product; commit;

Since both the users are accessing the same row on the same table at the same time it may end up in a situation where user2 will delete the row that user1 has updated. To overcome this situation oracle incorporates a locking facility, which permits or denies access to other users on a table or to certain rows in a table, when a user is operating on them. Types of locks: Locks are the mechanisms used to prevent destructive interaction between users accessing the same resource at the same time. A resource can either be an entire table or a specific row in a table. Thus locks provide a high degree of data concurrency. Locks can be acquired at two different levels. Row level lock 48 / 122 By Naveen Jaiswal

Database Management System Concepts Table level locks Row level locks: In the row level lock, a row is locked exclusively so that other users cannot modify the row until the transaction holding the lock is committed or rollback. Rowlocks are acquired automatically by oracle as a result of insert, update, delete and select with for update clause statement. Select for update clause The select command when used with for update of clause places an exclusive lock on one or more rows of a table. This command can be used to lock the rows that would be updated later. Ex: select * from order_info where ordid=200 for update of complan, total; Update order_info set complan =a where ordid =200; this update corresponds to the above example. After updating the columns in the order_info table, other users can perform other manipulations but can never update the row, which has been locked until the lock is released. Meanwhile, other users can update other rows. Table level lock: A table level lock will protect table thereby guaranteeing data integrity when data is being accessed concurrently by multiple users. A table lock can be held in several modes. Share lock Share update lock Exclusive lock The general syntax for locking a table is: Lock table <table name> in <share or share update or exclusive mode>; Share lock A share lock locks the table allowing other users to only query but not insert, update or delete rows in a table. Multiple users can place share locks on the same table at the same time. I.e., it allows resources to be shared, and hence the name share lock. Ex: lock table item in share mode; Share update lock: 49 / 122 By Naveen Jaiswal

Database Management System Concepts

It locks rows that are to be updated in a table. It permits other users to concurrently query, insert, update or even lock other rows in the same table. It prevents the other users from updating the same row, which has been locked. One can enforce a share update lock by using for update clause in the select statement. Ex: lock table customer in share update mode; Note: Although a share update lock falls under the table level category, it is effective only for rows. It allows many users to concurrently lock different rows of a table. Exclusive lock: It is most restrictive of table locks. When used by one user, it allows the other user to only query but not insert, delete or update rows in a table. It is almost similar to a share lock but only one user can place an exclusive lock on a table at a time, where as many users can place a share lock on the same table at the same time. Ex: lock table price in exclusive mode; Locks can be released by issuing either commit or rollback. Nowait: if a user has locked a table without a nowait clause in the lock table format and if another user tries to violate the above restrictions by trying to lock the table, then, he will be made to wait indefinitely until the former issues a commit or rollback statement. This delay could be avoided by appending a nowait clause in the lock table command. Ex: lock table customer in exclusive mode nowait; Deadlock: A deadlock occurs when two users have a lock, each on a separate object, and, each wants to acquire a lock on the other users object. When this happens, the first user has to wait for the second user and the second user to release the lock, but the second user will not release until the lock on the first users object is freed. At this point, both the users are at an impress and cannot proceed with their business. In such a case, oracle detects the deadlock automatically and solves the problem by aborting one of the two transactions. Formatting commands: SQL *plus provides us with the several commands for formatting query results. They can be broadly classified as:

50 / 122

By Naveen Jaiswal

Database Management System Concepts Column commands: column commands are again classified into customizing column name and content. Customizing column name Sql * plus uses column names as default column headings while displaying query results. We can display our own heading with help of the following command. Column <col name> heading <col heading>; Ex: column qty heading quantity; Select qty from item; The new heading is effective until we exit from the current SQL *plus session Customizing column contents When we display columns containing numeric values, we can either accept the default SQL *plus display format or we can change it by issuing the following command. Column <col name> format model; Ex: column total format $999,99; Select total from order_info; If we want to set the width of the column name to four characters, we do the following: Ex: column name format a4; Select name from customer; If a row in the column name in the customer table contains vivek then, the first four characters, i.e., vive would be present in the first in the first line and the remaining, i.e., k would follow in the next line. Note: to list the current display attributes for a given column we proceed as follows: Column <column name>; Compute commands To organize rows of reports into subsets and to perform summation on group of rows, break and compute commands are used. The break command also suppresses duplicate values. The syntax is Break on <break_column> skip n;

51 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: break on prodid skip 2; Select prodid from item;

The above example inserts 2 blank lines between every two different values of prodid. To perform computations on the row in each subset we use the compute command. We cannot perform the compute function without issuing a break command. Break on <col name> Compute function of column. On break_column.; Ex: break on prodid; Compute avg sum of qty on prodid; Select prodid, qty from item; The above example displays both the avg and sum for qty with respect to prodid. Grand total: to print the grand total we should include an on report clause in the break and compute commands. Syntax is Break on report; Compute function of column.. on report. Ex: break on report; Compute sum of qty on report; Select * from item; Note: to remove compute definition and break definition we say: Clear compute; Clear break; To list current compute definitions we enter : Compute; Title commands Title commands compressing title and btitle are used to place top title and bottom title on each page. The commands are Title position_clause char_value position_clause; Btitle position_clause char_value position_clause; Ex: title center introduction; Btitle center conclusion; 52 / 122 By Naveen Jaiswal

Database Management System Concepts Select prodid from item; Will display introduction, and conclusion at the top and bottom Setting page dimensions: the amount of data that SQL *plus displays on each page depends on the page dimensions. Commands like mew page, linesize and pagesize are used to set page dimensions. Newpage: this dimension is used to set the number of lines between the beginning of each page and top title. The syntax is: Set newpage <no.of lines> Oracle 8 adds a new keyword NONE. Set newpage { 1 | n | none} (default is 1. Where, 1-denotes the default value i.e, this command leaves a single line between the beginning of each page and the top title when the number of lines is not specified. n-denotes the number of lines that is required between the beginning of the page and the top title. None- is used to avoid any formatted and blankline between the pages. Linesize: linesize is used to print on a wide paper and alien a title. The syntax is Set linesize <no.of lines> Pagesize: it is used to set the number of lines on a page from the top title. Set pagesize <no.of lines> To display the page number at the top of each page along with the title, we say Ex: Title left hello right page: sql.pno; In the above example, the hello will be printed on the left and the page number will be printed on the right. Sql.pno refers to the current page number. Subqueries: Nesting of queries, one within the other is termed as subquery. A statement containing subquery is called a parent statement. Subqueries are used to retrieve data from tables, which depend on the value in the table itself. Ex: select repid, address, name from customer where name=(select name from customer where repid=10); 53 / 122 By Naveen Jaiswal

Database Management System Concepts

Note: always enclose subquery in parenthesis Subquery will be evaluated first followed by the main query. Subqueries that return several values: the above example used a subquery, which returned a single value. We should include operators like any, all, in or not in between the comparison operator and the subquery. Ex: select name, city, address from customer where repid < any (select repid from customer where creditlimit = 45345); In the above example the subquery will display that area which has maxcredit equal to 45345. The main query will display details about customers if area is lesser than any or the value returned by the subquery. Ex: select name, city, address from customer where repid< all(select repid from customer where creditlimit = 45345); The above example the subquery will display area, which has maximum credit equal to 5345. The main query will display details about customers only if area is lesser than all the values returned by the subquery. =any is equivalent to in and !=any is equivalent to not in. Multiple subqueries: oracle places no limit on the number of queries included in a where clause. Ex: select name, repid from customer where repid= (select repid from customer where custid=3) or creditlimit >(select creditlimit from customer where custid=2); The above example will select the columns name, repid from customer provided one of the above subqueries is true. A subquery itself can contain a subquery. Ex: select * from order_info where ordid=(select ordid from order_info where custid=(select custid from order_info where total=7000)) A subquery can retrieve information from more than one table. Ex: select name, city, address from customer where cusid in (select custid from order_info o, item I where o.ordid=i.ordid); In the above example the subquery refers to two tables, order_info and item. It will display rows from customer table for the custid returned by the subquery. Correlated subquery: a subquery is evaluated once for the entire parent statement whereas a correlated subquery is evaluated once per row processed by the parent statement.

54 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: select ordid, orderdate, shipdate from order_info o where shipdate < any (select orderdate from order_info where o.ordid=ordid); The behavior of a correlated subquery is evaluated as follows. Ordid of the row is first determined Ordid is then used to evaluate parent query If that rows shipdate is greater than any of the orddates, then the row is returned. The subquery is evaluated once for each row of the order_info table until all the rows of the table have been tested. Note: if the subquery is selected from the same table as the main query, the main query must define an alias for the table name, and the subquery must use an alias to refer to the first columns value in the main query. Database objects: The different database objects are Views Synonyms Sequence Index View: A view is an imaginary table and it contains no data and the table upon which a view is based are called base tables. The advantages of views are as follows They provide table security by restricting access to a predetermined set of rows or columns of a table. They simplify commands for the user because they allow them to select information from multiple tables. They provide data in a different perceptive than that of a base table by remaining columns without affecting the base table. The syntax for creating view is: Create view <view_name> [column alias name] as query [with check option constraint]; Ex: create view custview (customer, city, representative) as select custid, city, repid from customer where repid=20 with check option); In the above example, the view shows only about representatives whose repid is 20. because of the check option we should insert only those customers whose repid is 20. The

55 / 122

By Naveen Jaiswal

Database Management System Concepts same manipulations that are done on tables can be done on views. We can select, update, delete and insert into a view as same as a table. Ex: select * from custview; Ex: create view ver1 (item, product) as select itemid, prodid from item; Ex: create view ver2 (quantity, price) as select qty, actual_price from item; We can insert rows into both the views, provided other columns in the base table accept null values. If those columns were assigned as not null, then we cannot insert rows. We can perform updations or deletions on ver1 because itemid is declared as a primary key, which could be used to identify a row. Only after identification, the corresponding rows can be deleted or updated. In the case of ver2, we can perform updation or deletion with clause. Joining of tables is also possible in a view. But we cannot update, delete or insert through a view if it selects columns from more than one table. Example to create a view from two tables. Create view joinview (customername, maximumcredit, total) as select name, creditlimit, total from customer, order_info where customer.custid=order_info.custid; In the above example the view joinview will contain information about customers and also details about maximum credit that he can avail. Since this information is spread across two tables, we use the concept of join to retrieve them. Single row functions comprising number, character, date, group functions and expressions can also be used in views. Consider the following ex: Create view discount (quantity, ordid, price) as select qty, ordid, actualprice / 50 from item; Note: Views query cannot select pseudocolumns like currval and nextval If a views query consists joins, set operators, group functions and distinct clause then deletion, updation and insertion cannot be done. The change performed in a view will affect the base table and vice versa. Group functions group by clause can also be included in views. Object views: object views allow the user of relational data in object oriented applications. Hence we can define object views as extensions of traditional relational views that allow us to treat the relational data as object entities. Hence we can select, insert, update and delete the relational data as if they were object entities. Thus we can continue to run our current applications and at the same time develop new applications that make use of the object orientation features. We can now integrate the advantages of both the relational view concept and those of object view concept and have 56 / 122 By Naveen Jaiswal

Database Management System Concepts the best from both the worlds. This is of grater importance as the size of the database grows larger and larger. Oracle 7 supports the relational world while oracle supports the object-oriented system. Impressed by its various new features, suppose we decide to adopt oracle 8. Then there arises a question of how we go about migrating from oracle 7 to oracle 8. We cannot scrap all of our pervious databases just to reap the benefits of object-oriented technologys benefits. Object view comes as the solution to the above-discussed problem. This is because of its capability to abstract data from both relational and object oriented databases. Ex: create table employee (eno integer primary key, ename varchar2(25), company varchar2(30), street varchar2(30), city varchar2(20), pin varchar2(8), country varchar2(10)); To manipulate the above table, insert and update statements are issued as follows. Insert into employee values(10, niranjan, risingsoft, annamaiahmarg, tirupathi,. 517501, india); Update employee set street= AIR circle where eno=10; On the other hand, an object-oriented database expects the manipulations to be done using the two data types emp_type and add_type. For example, the insert statement is expected to be issued as follows in an object-oriented system: Insert into employee values (emp_type (10,niranjan, risingsoft, add_type(annamaiah marg, tirupathi, 517501, india)); To enable the object-oriented application to access the relational database, we can create a view as follows: Create view empview (empno, empname, companyname, address) as select eno, ename, company, add_type(street, city, pin, country) from employee; Now the object oriented queries to be issued to the underlying relational table must be as below: Select e.emp, from employee e; Synonyms: A synonym is a database object, which is used as an alias for a table view or sequence. They are used to Simply SQL statements 57 / 122 By Naveen Jaiswal

Database Management System Concepts Mask the name and owner of an object Provide public access to an object. Synonyms can be either private or public. The former is created by the user, which is available only to that person whereas the later is created by the DBA, which can be availed by any database user. The syntax for creating a synonym is given below. Create [public] synonym <synonym_name> for <table_name> [. @databaselink]; Consider the following example, which represents the table customer with a different name say, cust. Create synonym cust for customer; Note: only a DBA can create Sequences: A sequence is a database object, which can generate unique, sequential integer values. It can be used to automatically generate primary key or unique key values. A sequence can be either an ascending or descending sequence. The syntax is as follows: Create sequence <seq_name> increment by n start with n [maxvalue n] [minvalue n] [cycle/nocycle] [cache/nocache]; For creating a sequence we have to define the following terms. Increment by n: n is an integer, which specifies the interval between sequence numbers. The default is 1. If n is positive, then the sequence ascends and if it is negative the sequence descends. Start with n: specifies the first sequence number to be generated. Minvalue n: specifies the minimum value of the sequence. By default, it is 1 for an ascending sequence and 10e26-1 for a descending sequence. Maxvalue n: it specifies the maximum value that the sequence can generate. By default, it is 1 and 10e27-1 fro descending and ascending respectively. Cycle: specifies that the sequence continues to generate values after reaching either its max or min value. Nocycle: specifies that the sequence cannot generate more values after either its max or min values. The default value is nocycle. 58 / 122 By Naveen Jaiswal

Database Management System Concepts

Cache: allows faster generation of sequence number. Oracle preallocates sequence numbers and keeps them in memory for faster access. The cache value must be less than maxvalue minus minvalue and by default is 20. Nocache: the default value nocache does not preallocate sequence numbers for faster access. Ex: create sequence custseq increment by 1 start with 1 maxvalue 10 minvalue 1 cycle cache 4; After creating a sequence we can access its values with the help of pseudocolumns like currval and nextval. A pseudocolumn behaves like a table column, but it is not actually stored in the table. We can select values from pseudocolumns but cannot perform manipulations on their values. Nextval: nextval will return initial value of the sequence, when referred to, for the first time. Later reference to nextval will increment the sequence value by increment by clause and return the new value. Curval: currval returns the current value of the sequence, which is the value, returned by the last reference to nextval. Ex: create table temp (id number(3), name varchar2(20)); Insert into temp values(custseq.nextval,niranjan); Alter sequence We can alter the sequence when we want to do the following: Set or eliminate min or max values. Change the increment value. Change the number of cached sequence numbers. Alter sequence custseq maxvalue 15; Index: An index is a database object. Its purpose is to increase the performance of data retrieval and thereby provide faster access path to the table data. Indexes can be created on more than one column of a table. The syntax is Create [unique] index <index_name> on <table name> (column, column) Where the keyword unique ensures that the table does not allow two rows with identical values in all indexed columns. Square brackets indicate that unique is optional.

59 / 122

By Naveen Jaiswal

Database Management System Concepts Ex: create index ind_pri on price(prodid); Note: Indexes are independent of data. They can be dropped or created whenever needed, and their presence or absence will not affect the table. Columns of type long, long raw cannot be indexed. An index may contain up to 16 columns. Drop database objects: We can remove a database object from the database by issuing the following syntax: Drop database object <object_name>; Ex: drop view discount;

PL/SQL Using SQL statements we can retrieve or manipulate data present in a table. Using SQL statements alone it is not possible to gain the power of procedural language constructs. This aspect has been taken care of by PL/SQL, which is a procedural extension to SQL. Oracle 8 supports PL/SQL version 3. A PL/SQL block can contain DML and TCL statements. A PL/SQL block can also contain any number of SQL statements integrated with flow of control statements. Using PL/SQL we can also trap runtime errors. Thus, PL/SQL combines the data manipulating power of SQL with the data processing power of procedural languages. Advantages of PL/SQL: PL/SQL is a completely portable, high performance transaction processing language, which offers the following advantages Allows to write methods for direct types Supports the declaration and manipulation of object types and collections. Allows the calling of external functions and procedures. Comes with new libraries of built-in packages. PL/SQL has been upgraded to support directly most of the new features of the DBMS but not partitioned objects. There is an extensive support for the new type systems and the support for tables has been much extended.

60 / 122

By Naveen Jaiswal

Database Management System Concepts Support for SQL: PL/SQL allows us to use all SQL manipulation commands, transaction control commands, SQL functions (except group functions), operators and pseudocolumns, thus allowing us to manipulate data values in a table more flexibly and effectively. High productivity PL/SQL can be used to include procedural constructs in non-procedural tools like SQL*forms and oracle forms 4.5 to build applications. For ex:, we can use the entire PL/SQL block in an SQL * forms triggers. Further, PL/SQL remains the same in all environments. Better performance Without PL/SQL, oracle must process SQL statements one at a time. With PL/SQL, an entire block of statements can be processed in a single command line statement. This reduces the time taken to communicate between the application and the oracle server. Thus it helps in improving performance. Portability Applications written in PL/SQL are portable to any operating system or platform on which oracle ver 6.0 or 7.0 runs. Integration with oracle Both Pl/SQL and oracle have their foundations in SQL. PL/SQL supports all the datatypes and it integrates PL/SQL with the oracle data dictionary. Architecture of PL/SQL The PL/SQL runtime system is a technology, not an independent product. Think of this technology as an engine that executes PL/SQL blocks and subprograms. The engine can be installed in an Oracle Server or in an application development tool such as Oracle Forms or Oracle Reports. So, PL/SQL can reside in two environments: The Oracle Server Oracle tools

These two environments are independent. PL/SQL might be available in the Oracle Server but unavailable in tools, or the other way around. In either environment, the

61 / 122

By Naveen Jaiswal

Database Management System Concepts PL/SQL engine accepts as input any valid PL/SQL block or subprogram. Figure below shows the PL/SQL engine processing an anonymous block.

ORACLE SERVER Host Program or ORACLE tool Anon.


PL/SQL engine Anon. PL/SQL Block Procedural Procedural Statement Executer


S SQL statement executor The PL/SQL engine executes procedural statements but sends SQL statements to the SQL Statement Executor in the Oracle Server. In the Oracle Server Application development tools that lack a local PL/SQL engine must rely on Oracle to process PL/SQL blocks and subprograms. When it contains the PL/SQL engine, an Oracle Server can process PL/SQL blocks and subprograms as well as single SQL statements. The Oracle Server passes the blocks and subprograms to its local PL/SQL engine. Anonymous Blocks Anonymous PL/SQL blocks can be embedded in an Oracle Precompiled or OCI program. At run time, the program, lacking a local PL/SQL engine, sends these blocks to the Oracle Server, where they are compiled and executed. Likewise, interactive tools such as SQL*Plus and Server Manager, lacking a local PL/SQL engine, must send anonymous blocks to Oracle. Stored Subprograms Named PL/SQL blocks (subprograms) can be compiled separately and stored permanently in an Oracle database, ready to be executed. A subprogram explicitly created using an Oracle tool is called a stored subprogram. Once compiled and stored in the data dictionary, it is a database object, which can be referenced by any number of applications connected to that database.

62 / 122

By Naveen Jaiswal

Database Management System Concepts Stored subprograms defined within a package are called packaged subprograms; those defined independently are called standalone subprograms. (Subprograms defined within another subprogram or within a PL/SQL block are called local subprograms. They cannot be referenced by other applications and exist only for the convenience of the enclosing block.) Stored subprograms offer higher productivity, better performance, memory savings, application integrity, and tighter security. For Example, by designing applications around a library of stored procedures and functions, you can avoid redundant coding and increase your productivity. You can call stored subprograms from a database trigger, another stored subprogram, an Oracle Precompiler application, an OCI application, or interactively from SQL*Plus or Server Manager. Subprograms are stored in parsed, compiled form. So, when called, they are loaded and passed to the PL/SQL engine immediately. Moreover, stored subprograms take advantage of the Oracle shared memory capability. Multiple users need load only one copy of a subprogram into memory for execution. Introduction to PL/SQL block A PL/SQL block can be divided into three parts, namely, a declarative part, an executable part and an exception handling part. The order is shown below DECLARE } declarations BEGIN }executable statements EXCEPTION }handlers END; Objects can be declared in the declarative part, which can be used in the executable part for further manipulations. All procedural statements are included in between the BEGIN and END statements. Errors that occur during execution are dealt in the exception handling part. Character set: You write a PL/SQL program as lines of text using a specific set of characters. The PL/SQL character set includes the upper and lowercase letters A .. Z, a .. z 63 / 122 By Naveen Jaiswal

Database Management System Concepts


the numerals 0 .. 9 tabs, spaces, and carriage returns the symbols ( ) + - * / < > = ! ~ ; : . ' @ % , " # $ ^

PL/SQL is not case sensitive, so lowercase letters are equivalent to corresponding uppercase letters except within string and Character literals.

Lexical units: A line of PL/SQL text contains groups of characters known as lexical units, which can be classified as follows: For example, the line bonus := salary * 0.10; -- compute bonus contains the following lexical units: identifiers bonus and salary compound symbol := simple symbols * and ; numeric literal 0.10 delimiters (simple and compound symbols) identifiers, which include reserved words literals comments

64 / 122

By Naveen Jaiswal

Database Management System Concepts comment - - compute bonus

To improve readability, you can separate lexical units by spaces. In fact, you must separate adjacent identifiers by a space or punctuation. For example, the following line is illegal because the reserved words END and IF are joined: IF x > y THEN high := x; ENDIF; -- illegal However, you cannot embed spaces in lexical units except for string literals and comments. For example, the following line is illegal because the compound symbol for assignment (:=) is split: count : = count + 1; -- illegal To show structure, you can divide lines using carriage returns and indent lines using spaces or tabs. Compare the following IF statements for readability: IF x>y THEN max:=x;ELSE max:=y;END IF; | | | | Delimiters A delimiter is a simple or compound symbol that has a special meaning to PL/SQL. For example, you use delimiters to represent arithmetic operations such as addition and subtraction. Simple Symbols Simple symbols consist of one character; a list follows: + addition operator subtraction/negation operator * multiplication operator / division operator 65 / 122 By Naveen Jaiswal max := x; ELSE max := y; END IF; | IF x > y THEN

Database Management System Concepts

= relational operator < relational operator > relational operator ( expression or list delimiter ) expression or list delimiter ; statement terminator % attribute indicator , item separator . component selector @ remote access indicator ' character string delimiter " quoted identifier delimiter relational operator" != relational operator ~= relational operator ^= relational operator

66 / 122

By Naveen Jaiswal

Database Management System Concepts <= relational operator >= relational operator := assignment operator => association operator .. range operator || concatenation operator << (beginning) label delimiter >> (ending) label delimiter -single-line comment indicator /* (beginning) multi-line comment delimiter */ (ending) multi-line comment delimiter

Identifiers You use identifiers to name PL/SQL program objects and units, which include constants, variables, exceptions, cursors, cursor variables, subprograms, and packages. Some examples of identifiers follow: X t2 phone# credit_limit LastName 67 / 122 By Naveen Jaiswal

Database Management System Concepts oracle$number An identifier consists of a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs. Other characters such as hyphens, slashes, and spaces are illegal, as the following examples show: mine&yours -- illegal ampersand debit-amount -- illegal hyphen on/off -- illegal slash user id -- illegal space The next examples show that adjoining and trailing dollar signs, underscores, and number signs are legal: money$$$tree SN## try_again_ You can use upper, lower, or mixed case to write identifiers. PL/SQL is not case sensitive except within string and character literals. So, if the only difference between identifiers is the case of corresponding letters, PL/SQL considers the identifiers to be the same, as the following example shows: lastname LastName -- same as lastname LASTNAME -- same as lastname and LastName The length of an identifier cannot exceed 30 characters. But, every character, including dollar signs, underscores, and number signs, is significant. For example, PL/SQL considers the following identifiers to be different: lastname last_name Identifiers should be descriptive. So, use meaningful names such as credit_limit and cost_per_thousand. Avoid obscure names such as cr_lim and cpm. Reserved Words Some identifiers, called reserved words, have a special syntactic meaning to PL/SQL and so cannot be redefined. For example, the words BEGIN and END, which bracket the executable part of a block or subprogram, are reserved. As the next example shows, if you try to redefine a reserved word, you get a compilation error: DECLARE end BOOLEAN; -- illegal; causes compilation error 68 / 122 By Naveen Jaiswal

Database Management System Concepts

However, you can embed reserved words in an identifier, as the following example shows: DECLARE end_of_game BOOLEAN; -- legal Often, reserved words are written in uppercase to promote readability. However, like other PL/SQL identifiers, reserved words can be written in lower or mixed case. Predefined Identifiers Identifiers globally declared in package STANDARD, such as the exception INVALID_NUMBER, can be redeclared. However, redeclaring predefined identifiers is error prone because your local declaration overrides the global declaration. Quoted Identifiers For flexibility, PL/SQL lets you enclose identifiers within double quotes. Quoted identifiers are seldom needed, but occasionally they can be useful. They can contain any sequence of printable characters including spaces but excluding double quotes. Thus, the following identifiers are legal: "X+Y" "last name" "on/off switch" "employee(s)" "*** header info ***" The maximum length of a quoted identifier is 30 characters not counting the double quotes. Using PL/SQL reserved words as quoted identifiers is allowed but not recommended. It is poor programming practice to reuse reserved words. Some PL/SQL reserved words are not reserved by SQL. For example, you can use the PL/SQL reserved word TYPE in a CREATE TABLE statement to name a database column. But, if a SQL statement in your program refers to that column, you get a compilation error, as the following example shows: SELECT acct, type, bal INTO ... -- causes compilation error To prevent the error, enclose the uppercase column name in double quotes, as follows: SELECT acct, "TYPE", bal INTO ... 69 / 122 By Naveen Jaiswal

Database Management System Concepts

The column name cannot appear in lower or mixed case (unless it was defined that way in the CREATE TABLE statement). For example, the following statement is invalid: SELECT acct, "type", bal INTO ... -- causes compilation error Alternatively, you can create a view that renames the troublesome column, then use the view instead of the base table in SQL statements. Literals A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier. The numeric literal 147 and the Boolean literal FALSE are examples. Numeric Literals Two kinds of numeric literals can be used in arithmetic expressions: integers and reals. An integer literal is an optionally signed whole number without a decimal point. Some examples follow: 030 6 -14 0 +32767 A real literal is an optionally signed whole or fractional number with a decimal point. Several examples follow: 6.6667 0.0 -12.0 3.14159 +8300.00 .5 25. PL/SQL considers numbers such as 12.0 and 25. to be reals even though they have integral values. Numeric literals cannot contain dollar signs or commas, but can be written using scientific notation. Simply suffix the number with an E (or e) followed by an optionally signed integer. A few examples follow: 2E5 1.0E-7 3.14159e0 -1E38 -9.5e-3 E stands for "times ten to the power of." As the next example shows, the number after E is the power of ten by which the number before E must be multiplied: 5E3 = 5 X 103 = 5 X 1000 = 5000 The number after E also corresponds to the number of places the decimal point shifts. In the last example, the implicit decimal point shifted three places to the right; in the next example, it shifts three places to the left: 5E-3 = 5 X 10-3 = 5 X 0.001 = 0.005 70 / 122 By Naveen Jaiswal

Database Management System Concepts

Character Literals A character literal is an individual character enclosed by single quotes (apostrophes). Several examples follow: 'Z' '%' '7' ' ' 'z' '(' Character literals include all the printable characters in the PL/SQL character set: letters, numerals, spaces, and special symbols. PL/SQL is case sensitive within character literals. For example, PL/SQL considers the literals 'Z' and 'z' to be different. Do not confuse the character literals '0' .. '9' with integer literals. Character literals cannot be used in arithmetic expressions. String Literals A character value can be represented by an identifier or explicitly written as a string literal, which is a sequence of zero or more characters enclosed by single quotes. Several examples follow: 'Hello, world!' 'XYZ Corporation' '10-NOV-91' 'He said "Life is like licking honey from a thorn."' '$1,000,000' All string literals except the null string ('') have datatype CHAR. Given that apostrophes (single quotes) delimit string literals, how do you represent an apostrophe within a string? As the next example shows, you write two single quotes, which is not the same as writing a double quote: 'Dont leave without saving your work.' PL/SQL is case sensitive within string literals. For example, PL/SQL considers the following literals to be different: 'baker' 'Baker' Boolean Literals Boolean literals are the predefined values TRUE and FALSE and the non-value NULL, which stands for a missing, unknown, or inapplicable value. Remember, Boolean literals are values, not strings. For example, TRUE is no less a value than the number 25. 71 / 122 By Naveen Jaiswal

Database Management System Concepts

Comments The PL/SQL compiler ignores comments, but you should not. Adding comments to your program promotes readability and aids understanding. Generally, you use comments to describe the purpose and use of each code segment. PL/SQL supports two comment styles: single line and multi-line. Single-Line Single-line comments begin with a double hyphen (- -) anywhere on a line and extend to the end of the line. A few examples follow: -- begin processing SELECT sal INTO salary FROM emp -- get current salary WHERE empno = emp_id; bonus := salary * 0.15; -- compute bonus amount Notice that comments can appear within a statement at the end of a line. While testing or debugging a program, you might want to disable a line of code. The following example shows how you can "comment-out" the line: -- DELETE FROM emp WHERE comm IS NULL; Multi-line Multi-line comments begin with a slash-asterisk (/*), end with an asterisk-slash (*/), and can span multiple lines. An example follows: /* compute a 15% bonus for top-rated employees */ IF rating > 90 THEN bonus := salary * 0.15; END IF; You can use multi-line comment delimiters to comment-out whole sections of code, as the following example shows: /* OPEN c1; LOOP FETCH c1 INTO my_empno, my_ename, my_sal;

72 / 122

By Naveen Jaiswal

Database Management System Concepts EXIT WHEN c1%NOTFOUND; ... END LOOP; CLOSE c1; */ Restrictions You cannot nest comments. Also, you cannot use single-line comments in a PL/SQL block that will be processed dynamically by an Oracle Precompiler program because endof-line characters are ignored. As a result, single-line comments extend to the end of the block, not just to the end of a line. So, use multi-line comments instead. Data types Every constant and variable has a datatype, which specifies a storage format, constraints, and valid range of values. PL/SQL provides a variety of predefined scalar and composite datatypes. A scalar type has no internal components. A composite type has internal components that can be manipulated individually. A reference type contains values, called pointers, that designate other program objects. Figure below shows the predefined datatypes available for your use. An additional scalar type, MLSLABEL, is available with Trusted Oracle, a specially secured version of Oracle. The scalar types fall into four families, which store number, character, date/time, or Boolean data, respectively.

PL/SQL datatypes Scalar datatypes Binary_integer Dec Decimal Double precision Float Int Integer Natural Number Numeric Positive Real Smallint char character long long raw raw rowid string varchar varchar2 date Boolean composite types record table reference types ref curser

73 / 122

By Naveen Jaiswal

Database Management System Concepts Predefined Datatypes This section discusses the scalar types; the composite types are discussed later in this chapter; the reference type is discussed in "Using Cursor Variables" on page 4 - 17. BINARY_INTEGER You use the BINARY_INTEGER datatype to store signed integers. The magnitude range of a binary integer value is -2147483647 .. 2147483647. PL/SQL represents BINARY_INTEGER values as signed binary numbers, which, unlike NUMBER values, can be used in calculations without conversion. BINARY_INTEGER Subtypes A subtype associates a base type with a constraint and so defines a subset of values. For convenience, PL/SQL predefines the following BINARY_INTEGER subtypes: NATURAL POSITIVE (0 .. 2147483647) (1 .. 2147483647)

You can use the NATURAL or POSITIVE subtype when you want to restrict a variable to non-negative integer values. NUMBER You use the NUMBER datatype to store fixed or floating-point numbers of virtually any size. You can specify precision, which is the total number of digits, and scale, which determines where rounding occurs. The syntax follows: NUMBER[(precision, scale)] You cannot use constants or variables to specify precision and scale; you must use integer literals. The maximum precision of a NUMBER value is 38 decimal digits; the magnitude range is 1.0E-129 .. 9.99E125. If you do not specify the precision, it defaults to the maximum value supported by your system. Scale can range from -84 to 127. For instance, a scale of 2 rounds to the nearest hundredth (3.456 becomes 3.46). Scale can be negative, which causes rounding to the left of the decimal point. For example, a scale of -3 rounds to the nearest thousand (3456 becomes 3000). A scale of zero rounds to the nearest whole number. If you do not specify the scale, it defaults to zero. 74 / 122 By Naveen Jaiswal

Database Management System Concepts

NUMBER Subtypes The NUMBER subtypes below have the same range of values as their base type. For example, DECIMAL is just another name for NUMBER. DEC DECIMAL DOUBLE PRECISION INTEGER INT NUMERIC REAL SMALLINT

FLOAT is another subtype of NUMBER. However, you cannot specify a scale for FLOAT variables; you can only specify a binary precision. The maximum precision of a FLOAT value is 126 binary digits, which is roughly equivalent to 38 decimal digits. You can use these subtypes for compatibility with ANSI/ISO and IBM types or when you want an identifier more descriptive than NUMBER. CHAR You use the CHAR datatype to store fixed-length (blank-padded if necessary) character data. How the data is represented internally depends on the database character set, which might be 7-bit ASCII or EBCDIC Code Page 500, for example. The CHAR datatype takes an optional parameter that lets you specify a maximum length up to 32767 bytes. The syntax follows: CHAR[(maximum_length)] You cannot use a constant or variable to specify the maximum length; you must use an integer literal. If you do not specify the maximum length, it defaults to 1.

75 / 122

By Naveen Jaiswal

Database Management System Concepts Remember, you specify the maximum length of a CHAR(n) variable in bytes, not characters. So, if a CHAR(n) variable stores multi-byte characters, its maximum length is less than n characters. Although the maximum length of a CHAR(n) variable is 32767 bytes, the maximum width of a CHAR database column is 255 bytes. Therefore, you cannot insert values longer than 255 bytes into a CHAR column. You can insert any CHAR(n) value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes or 2 gigabytes. However, you cannot select a value longer than 32767 bytes from a LONG column into a CHAR(n) variable. CHAR Subtype The CHAR subtype CHARACTER has the same range of values as its base type. That is, CHARACTER is just another name for CHAR. You can use this subtype for compatibility with ANSI/ISO and IBM types or when you want an identifier more descriptive than CHAR. VARCHAR2 You use the VARCHAR2 datatype to store variable-length character data. How the data is represented internally depends on the database character set. The VARCHAR2 datatype takes a required parameter that specifies a maximum length up to 32767 bytes. The syntax follows: VARCHAR2(maximum_length) You cannot use a constant or variable to specify the maximum length; you must use an integer literal. Remember, you specify the maximum length of a VARCHAR2(n) variable in bytes, not characters. So, if a VARCHAR2(n) variable stores multi-byte characters, its maximum length is less than n characters. Although the maximum length of a VARCHAR2(n) variable is 32767 bytes, the maximum width of a VARCHAR2 database column is 2000 bytes. Therefore, you cannot insert values longer than 2000 bytes into a VARCHAR2 column. You can insert any VARCHAR2(n) value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes. However, you cannot select a value longer than 32767 bytes from a LONG column into a VARCHAR2(n) variable.

76 / 122

By Naveen Jaiswal

Database Management System Concepts Some important semantic differences between the CHAR and VARCHAR2 base types are described in Appendix C. VARCHAR2 Subtypes The VARCHAR2 subtypes below have the same range of values as their base type. For example, VARCHAR is just another name for VARCHAR2. STRING VARCHAR

You can use these subtypes for compatibility with ANSI/ISO and IBM types. However, the VARCHAR datatype might change to accommodate emerging SQL standards. So, it is a good idea to use VARCHAR2 rather than VARCHAR. LONG You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum length of a LONG value is 32760 bytes. You can insert any LONG value into a LONG database column because the maximum width of a LONG column is 2147483647 bytes. However, you cannot select a value longer than 32760 bytes from a LONG column into a LONG variable. LONG columns can store text, arrays of characters, or even short documents. You can reference LONG columns in UPDATE, INSERT, and (most) SELECT statements, but not in expressions, SQL function calls, or certain SQL clauses such as WHERE, GROUP BY, and CONNECT BY. For more information, see Oracle7 Server SQL Reference. RAW You use the RAW datatype to store binary data or byte strings. For example, a RAW variable might store a sequence of graphics characters or a digitized picture. Raw data is like character data, except that PL/SQL does not interpret raw data. Likewise, Oracle does no character set conversions (from 7-bit ASCII to EBCDIC Code Page 500, for example) when you transmit raw data from one system to another. The RAW datatype takes a required parameter that lets you specify a maximum length up to 32767 bytes. The syntax follows: RAW(maximum_length)

77 / 122

By Naveen Jaiswal

Database Management System Concepts You cannot use a constant or variable to specify the maximum length; you must use an integer literal. Although the maximum length of a RAW variable is 32767 bytes, the maximum width of a RAW database column is 255 bytes. Therefore, you cannot insert values longer than 255 bytes into a RAW column. You can insert any RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes. However, you cannot select a value longer than 32767 bytes from a LONG RAW column into a RAW variable. LONG RAW You use the LONG RAW datatype to store binary data or byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum length of a LONG RAW value is 32760 bytes. You can insert any LONG RAW value into a LONG RAW database column because the maximum width of a LONG RAW column is 2147483647 bytes. However, you cannot select a value longer than 32760 bytes from a LONG RAW column into a LONG RAW variable. ROWID Internally, every Oracle database table has a ROWID pseudocolumn, which stores binary values called rowids. Rowids uniquely identify rows and provide the fastest way to access particular rows. You use the ROWID datatype to store rowids in a readable format. The maximum length of a ROWID variable is 256 bytes. When you select or fetch a rowid into a ROWID variable, you can use the function ROWIDTOCHAR, which converts the binary value to an 18-byte character string and returns it in the format BBBBBBBB.RRRR.FFFF where BBBBBBBB is the block in the database file, RRRR is the row in the block (the first row is 0), and FFFF is the database file. These numbers are hexadecimal. For example, the rowid 0000000E.000A.0007 points to the 11th row in the 15th block in the 7th database file. Typically, ROWID variables are compared to the ROWID pseudocolumn in the WHERE clause of an UPDATE or DELETE statement to identify the latest row fetched from a cursor. For an example, see "Fetching Across Commits" on page 4 - 43.

78 / 122

By Naveen Jaiswal

Database Management System Concepts BOOLEAN You use the BOOLEAN datatype to store the values TRUE and FALSE and the nonvalue NULL. Recall that NULL stands for a missing, unknown, or inapplicable value. The BOOLEAN datatype takes no parameters. Only the values TRUE and FALSE and the non-value NULL can be assigned to a BOOLEAN variable. You cannot insert the values TRUE and FALSE into a database column. Furthermore, you cannot select or fetch column values into a BOOLEAN variable. DATE You use the DATE datatype to store fixed-length date values. The DATE datatype takes no parameters. Valid dates for DATE variables include January 1, 4712 BC to December 31, 4712 AD. When stored in a database column, date values include the time of day in seconds since midnight. The date portion defaults to the first day of the current month; the time portion defaults to midnight. MLSLABEL With Trusted Oracle, you use the MLSLABEL datatype to store variable-length, binary operating system labels. Trusted Oracle uses labels to control access to data. For more information, see Trusted Oracle7 Server Administrator's Guide, Release 7.1. You can use the MLSLABEL datatype to define a database column. Also, you can use the %TYPE and %ROWTYPE attributes to reference the column. However, with standard Oracle, such columns can store only nulls. With Trusted Oracle, you can insert any valid operating system label into a column of type MLSLABEL. If the label is in text format, Trusted Oracle converts it to a binary value automatically. The text string can be up to 255 bytes long. However, the internal length of an MLSLABEL value is between 2 and 5 bytes. With Trusted Oracle, you can also select values from a MLSLABEL column into a character variable. Trusted Oracle converts the internal binary value to a VARCHAR2 value automatically. Collections: Collections are user defined composite datatypes. Oracle PL/SQL provides the feature of declaring a composite type, which can contain variables of different datatypes. In this type we can see the object-oriented technologys impact on PL/SQL. This can be implemented as a record type, as a nested table or as a variable array.

79 / 122

By Naveen Jaiswal

Database Management System Concepts Record type: a record is a group of related fields, which has their own names and datatypes. So say in, in a table of multiple columns, a record type can substitute the values of the columns that the record type holds. This record type will be useful, when you have subset of columns common in two or more tables. To create records, first you define a record type and then declare records of that type. The syntax for defining a record in the declarative part of any PL/SQL block, subprogram, or package using the syntax: Type type_name is record (field_declaration [, field_declaration].); Ex: Declare Type emp_rec is record( empno int, ename varchar2(10), empsal number(3,2)); my_rec emp_rec; in this PL/SQL, declaration part, we are creating a user defined record type named emp_rec comprising three variables. This data type is used for the declaration of another variable my_rec . Here the base object emp_rec and my_rec is an instance of that object. Nested tables: As the name implies nested tables are tables within a database table. When the number of rows to be entered in a table is not definite, nested tables can be used. A record type comprising the required column variables must be created. A table is created using this record type as its datatype. The syntax for creating a nested table type is Type table_name is table of table_type [not null] Ex: declare Type rec1 is record (a int, b varchar2, c date); Type tableitem is table of rec1; Mytable tableitem; In this code rec1 is the user created record type, which has the necessary column variables declared. This record type rec1 is used to create another table type. Using this tabletype as the datatype the variable mytable is declared. Through this variable records can be filled in to the table. Varying records(varray) A varray is the variable length array datatype similar to any other array declared in C or pascal. This is similar to a nested table except that the limit for the records to be filled is fixed. The main difference occurs in the declaration part of the table. The syntax for declaring a varray type is: 80 / 122 By Naveen Jaiswal

Database Management System Concepts

Type type_name is varray (maximum size) of element type[not null]; Using the same record type rec1 of the previous example, the declaration looks like this: Type varitem is varray (3) of real; Mytable varitem; Here a variable array varitem is created of size 3. a table mytable of type varitem is created. The number of rows that can be entered in this table is limited to 3. Collection methods: To manipulate these nested tables and varrays, PL/SQL supports several different methods that can be used by the program called collection. The list is given below. Exists(x) :returns if the xth element in a nested or varray exists. Otherwise the method returns false. Count: returns the number of elements currently in a nested table of varray. Limit : for varrays, returns the maximum number of elements that the collection can contain. First: returns the first member of the nested table or varray. Last: returns the last member of the nested table or varray Prior(x): returns the member prior to the xth member of the nested table or varray. Next(x): returns the member next to the xth member of the nested table or varray. Extend(x,y) :appends x copies of the yth elements to a nested table or varray Trim(x): trims x elements from the end of a nested table or varray. Delete: deletes some or all the nested tables or varrays elements. These collection methods can be used along with the names of nested tables or varrays with the referencing methods using the dot( .) operator. For example in a nested table Ntab, If the number of existing rows has to be found, we can make use of the collection method count as, number:=ntab.count; If the 4th row of the nested table Ntab has to be deleted, then use the collection method delete as, Ntab.delete(4); Similarly Ntab.delete(4,60); deletes 4th, 5th,6th rows respectively and Ntab, delete will delete all the existing rows from the table Ntab. Ref operator: Every object has an object identifier(OID) associated with it. This helps the corresponding object to be identified from other objects or relational tables. A REF is a 81 / 122 By Naveen Jaiswal

Database Management System Concepts built-in datatype that acts as a container for an object identifier, ref could also point to NULL object. When the reef is said to be dangling, it means that the ref is pointing to an non-existent object and not a null object. Consider the following example: Select from emp where emp.obj is not dangling; Oracle 8 supports reference pointers to refer from one object to another. The subject of the reference must be an object table. Consider the following case: An object type of name dept_type is created as below: Create type dept_type as object (deptno number(3), dname varchar2(20), loc varchar2(120); A table named dept_t of type dept_type is created Create table dept_t of dept_type; Now to create a table named emp with a field called dept that refers to the object dept_type, the syntax to be followed is: Create table emp (empno number(4) ename varchar2(20), job varchar2(10), mgr number(4), hiredate date, sal number(7,2), comm. Number(7,2), dept REF dept_type); We assign a value to the REF by querying the table to be referenced, for example Update emp set dept=(select REF(d) from dept_t d where deptno=10) where empno=200; Attributes: Attributes allow us to refer to datatypes and object from the database. PL/SQL variables and constants can have attributes. The following are the types of attributes supported by PL/SQL %Type: %type attribute is used when declaring variables that refer to the database columns. Consider the following example where a variable called prod is declared to be of type itemid in the item table using %type attribute. Declare Prod item.itemid %type; 82 / 122 By Naveen Jaiswal

Database Management System Concepts

Where prod is the variable name, item is the name of the table and itemid is the name of the column. The advantages of using %type are listed below: we need not know the exact datatype of the column itemid. If the database definition of itemid is changed, then, the datatype of prod changes accordingly at run time. %rowtype: %rowtype attribute provides a record type that represents a row in a table. The record can store an entire row of data selected from the table or fetched by a curser.. In the following example, a record named cust_inf will have the same names and datatypes as the columns in the customer table. Declare Cust_inf customer %rowtype; In the above example, cust_inf stores a row selected from the customer table. Logical comparisons: PL/SQL supports the comparison of variables and constants in PL/SQL statements. These comparisons, called Boolean expressions, are often connected by logical operators AND, OR and NOT. There are three types of Boolean expressions Numeric Boolean expressions: We can compare numbers using numeric Boolean expressions. The table below illustrates relational operators and their meanings when used with numeric values. Operator = != < > <= >= meaning is equal to is not equal to less than grater than less than or equal to greater than or equal to example a=300 n!=275 s<210 r>300 s<=210 m>=336

Character Boolean expressions: A sequence of character or individual characters enclosed in a string can be compared using character Boolean expressions. Their evaluation is based on the alphabetical ordering of the character strings. The table below illustrates relational operators and their meanings when used with character strings. Operator meaning 83 / 122 example By Naveen Jaiswal

Database Management System Concepts

= != < > <= >=

is the same as is not the same as comes alphabetically before comes alphabetically after comes alphabetically before or is the same as comes alphabetically before or is the same as

name=niranjan product!=diary milk name1<name2 name1>name2 name2>=name3 name2<=name3

Date Boolean expressions. We can compare 2 dates using date Boolean functions. Operator = != < > = >= meaning is the same as is not the same as is earlier than is later than is earlier than or same as is later than or same as example ord_date=17-apr-76 ship_date!=9-fib-98 birthdate<25-jul-77 joiningdate>1-jan-98 joiningdate<=1-apr-77 expdate>= 52-jul-77

Control structures: In addition to SQL commands, PL/SQL can also process data using flow of control statements. The flow of control statements can be classified under the following categories. Conditional control Iterative control Sequential control Before discussing them in detail, let us get acquired with a package named dbms_standard. This package provides a language facility to interact with oracle. The examples that follow illustrate the usage of control structures in oracle along with this package. Conditional control: sequence of statements can be executed based on some condition using the if statement. There are three forms of if statements, namely, if then, if then else and if then elsif. The simplest form of a statement is the if then statement. The syntax is: If condition then 84 / 122 By Naveen Jaiswal

Database Management System Concepts Sequence of statements; End if; The sequence of statements is executed only if the condition evaluates to true. If it is false or null, then, the control passes to the statement after end if. An else clause in the if then statement defines what is to be done if the condition is false or null. An if then elsif statement can be used to select one of several mutually exclusive alternatives. The following example illustrates the if then else statement. Ex: Declare Commission order_info.commplan%type; Begin Select complan into commission from order_info where custid=4; If commission= a then Update order_info set shipdate=12-mar-98 where custid=4; Else Update order_info set shipdate=12-apr-98 where custid=4; Endif; End; The above ex will change shipdate to 12-mar-98 if the condition is met, else it changes shipdate to 12-apr-98. Iterative control: A sequence of statements can be executed any number of times using loop constructs. Loops can be broadly classified as: Simple loop For loop While loop Simple loop: The keyword loop should be placed before the first statement in the sequence and the keyword end loop after the last statement in the sequence. The following example illustrates this concept and the sequence of statements are repeated, until a=100. Syntax for simple loop Loop Sequence of statements; 85 / 122 By Naveen Jaiswal

Database Management System Concepts End loop; Ex: Declare A number:=1; Begin Loop A:=a+10; Exit when a=100; End loop; Dbms_output.put_line(to_char(a)); End; Note: the exit when statement allows us to complete a loop if further processing is undesirable or impossible. While loop: The while loop statement includes a condition associated with a sequence of statement. If the condition evaluates to true, then the sequence of statements will be executed, and again control resumes at the top of the loop. If the condition evaluates to false, then the loop is bypassed and the control passes to the next statement. Syntax for a while loop is: While <condition> Loop Sequence of statements; End loop; Ex: Declare I number; J number; Begin While I<=100 loop J:=j+1; I:=I+2; End loop; Dbms_output.put_line(to_char(j)); End; For loop:

86 / 122

By Naveen Jaiswal

Database Management System Concepts The number of iterations for a while loop is unknown until the loop terminates, whereas the number of iterations in a for loop is known before the loop gets executed. The for loop statement specifies a range of integers, to execute the sequence of statements once for each integer. The syntax is given below For counter in [reverse] lowerboundupperbound Loop Sequence of statements; End loop; By default, iteration proceeds from lowerbound to upperbound. If we use the optional keyword reserve, then, iteration proceeds downwards from upperbound to lowerbound. Ex: Begin For I in 1..2 Loop Update order_info set commplan=c where ordid=5000; End loop; End; This example executes the update statement once for each integer specified in the for loop. Sequential control The goto statement allows us to branch to a label unconditionally. The label, which is enclosed by double angle brackets must precede an executable SQL statement or a PL/SQL statement block. When executed, the goto statement transfers control to the labeled statement or block. Ex: Declare Cost price.minprice%rowtype; Begin Select stdprice into cost from price where prodid in (select prodid from product where prodesc= kit kat); If cost>7000 then Goto updation; End if; <<Updation>> 87 / 122 By Naveen Jaiswal

Database Management System Concepts Update price set minprice=6999 where prodid=111; End; Error handling Error condition in PL/SQL is termed as an exception. There are two types of exceptions. They are Predefined exceptions User-defined exceptions. An exception is raised when an error occurs. In that case, normal execution stops and the control is immediately transferred to the exception handling part of our PL/SQL block. Predefined exceptions are raised automatically by the system during run time, whereas user-defined exceptions must be raised explicitly by using RAISE statements. Predefined exceptions: An exception is raised implicitly when a PL/SQL program violates oracle rule. The following are predefined exceptions supported by PL/SQL. No_data_found: This exception is raised when select statement returns no rows Curser_already_open: This exception is raised when we try to open a curser which is already open. Dup_val_on_index: This exception is raised when we insert duplicate values in a column, which is defined as unique index. Storage_error: This exception is raised if PL/SQL runs out of memory or if the memory is corrupted. Program_error: This exception is raised if PL/SQL has an internal problem. Zero_divide: this exception is raised when we try to divide a number by zero Invalid_curser: This exception is raised when we try to violate curser operation. For example when we try to close a curser which is not opened. Login_denied: This exception is raised when we try to enter oracle using invalid username/password Invalid_number: This exception is raised if the convention of a character string to a number fails because the string does not represent a valid number. For ex:, inserting john for a column of type number will raise this exception. Too_many_rows: Raised when the select into statement returns more than one row. Syntax for predefined exception is as follows Begin Sequence of statements; Exception When <exception_name> then Sequence of statements; 88 / 122 By Naveen Jaiswal

Database Management System Concepts When others then Sequence of statements; End; Where others handler guarantees that no exception will go unhandled. A PL/SQL block can have only one others handler. Ex: Declare Price item.actualprice%type; Begin Select actualprice into price from item where qty=300; Exception When no_dat_found then Dbms_output.put_line(item missing); End; User-defined exception A user-defined exception should be declared and raised explicitly by a raise statement. It can be declared only in the declarative part of the PL/SQL block. The syntax is <Exception name> exception; The syntax for a raise statement is: Raise <exception name>; The following example is used to fine out whether price per item is zero or null. If it is so then rises an exception named zero_price.

Declare Zero_price exception; Price number(8,2); Begin Select actualprice into price from item where ordid=200; If price=0 or price is null then Raise zero_price; Endif; Exception When zero_price then Dbms_output.put_line(raised zero_price exception); End; 89 / 122 By Naveen Jaiswal

Database Management System Concepts

Cursers: A work area called private SQL area is used by the oracle server to execute SQL statements and store processed information. PL/SQL uses cursers to name the private SQL area and to access the stored information. There are two types of cursers. They are: Explicit cursers Implicit cursers A curser can be declared in the declarative part of PL/SQL block, a subprogram or a package. The syntax for declaring a cursor is as follows. Cursor <cursor_name> is <select statement>; Submitted by SQL, might be an insert, an update or a delete. Oracle automatically opens a cursor for processing. Cursors, when user-defined, can see off certain limitations. Cursors can either be strong or weak depending upon the way it is declared. Ex: Type cur1 ref cursor return emp %rowtype; samp1 cur1; samp2 cur1; samp3 cur1; Here in this curser declaration, the return type determines the shape of the cursor variables. Since they are pre-defined, it relies on the rowtype of the table emp. These cursor variables are meant to be strong. On the other hand, we can also declare a curser as: Type cur1 is ref cursor; Since we are not giving any return value for the cursor, the cursor variable is shape independent. This in fact adds flexibility to the cursor variable, aiding future alterations. Being vulnerable to changes in shape, it is called weak cursor. Cursor using dynamic SQL: Usually the PL/SQL comprising the SQL statements, while compiling, binds all the SQL statements. The various objects referenced by SQL statements are checked before compiling. So the execution of the PL/SQL block will be more efficient. But the drawback with this method is its limited repertoire of PL/SQL statements. With the new 90 / 122 By Naveen Jaiswal

Database Management System Concepts feature of dynamic SQL, PL/SQL programs use a special database utility called the DBMS-SQL package. This utility has a lot of in-built procedures and functions. When a SQL statement has to be executed dynamically the program calls the in-built functions and procedures of DBMS-SQL package. The program opens a cursor for this dynamic SQL statement to get executed. Explicit cursor: The set of rows returned by a query can contain zero or multiple rows depending upon the query defined. These rows are called the active set. The cursor will point to the current row in the active set. After declaring a cursor, we can use the following commands to control the cursor. Open Fetch Close The open statement executes the query, identifies the active set and positions the cursor before the first row. The syntax is: Open <cursor name>; The fetch statement retrieves the current row and advances the cursor to the next row to fetch the remaining rows. Syntax for fetch statement is: Fetch <cursor name> into <column name>; After processing the last row in the active set, the cursor is disabled with the help of the close command. The syntax is: Close <cursor name>; Ex: Declare Pri item.qty%type; Quantity item.qty%type; Cursor a is select qty from item where ordid=100; Begin Open a; Loop Fetch a into quantity; Pri:=3*quantity; Update item set actualprice=pri where ordid=2000; Exit when a%notfound; Dbms_output.put_line(one row updated); 91 / 122 By Naveen Jaiswal

Database Management System Concepts End loop; Close a; End; Explicit cursor attributes when appended to the cursor name allow us to access useful information from the retrived rows. They are: %notfound %found %rowcount %isopen %Notfound: After opening a cursor, a fetch statement is used to fetch rows from the active set, one at a time. The attribute %notfound indicates whether fetch statement returns row from the active set. If the last fetch fails to return a row, then %notfound evaluates to true, else it evaluates to false. The following example uses the %notfound attribute to exit a loop when fetch fails to return a row. Ex: Declare Cursor c2 is select actualprice, qty from item where itemid=2000; Total number(8); Price item.actualprice%type; Quantity item.qty%type; Begin Open c2; Loop Fetch c2 into price, quantity; Total:=price * quantity; Dbms_uotput.put_line(the value of the total is | | to_char(total)); Exit when c2%notfound; Endloop; Dbms_output.put_line (value not found) Close c2; End; %Found: The %found attribute is the logical opposition of %notfound. It evaluates to true if the last fetch statement succeeds. It would be evaluated to false if the last fetch command failed because no more rows were available.

92 / 122

By Naveen Jaiswal

Database Management System Concepts %Rowcount: The %rowcount attribute is used to return the number of rows fetched. Before the first fetch, %rowcount is zero. When the fetch statement returns a row, them the number is incremented. The following ex uses the %rowcount attribute to check whether the cursor fetches more than two rows. Declare Cursor c2 is select actualprice, qty from item where itemid=7872; Price item.actualprice%type; Quantity item.aty%type; Begin Open c2; Loop Fetch c2 into price, quantity; If c2%rowcount >2 then Dbms_output.put_line(fetches more than two rows); End if ; Exit when c2%rowcount<2 End loop; Close c2; End; %isopen if the cursor is already open, then, the attribute %isopen evaluates to true, else it evaluates to false. The following example uses the %isopen attribute to open a cursor. Ex: Declare Cursor c4 is select actualprice, qty from item where itemid=1000; Begin If c4%isopen then Dbms_output.put_line(this message is not displayed); Else Open c4 Dbms_output.put_line(cursor opened); End if; Close c4; End; Cursor for loop: A cursor for loop can be used instead of explicit cursors to simplify coding. A cursur for loop implicitly opens a cursor, repeatedly fetches rows from the active set, and then, 93 / 122 By Naveen Jaiswal

Database Management System Concepts closes the cursor when all rows have been processed. The syntax for the cursor for loop is as follows. For <record name> in <cursor name> loop Sequence of statements; End loop; The following ex: is illustrative of the cursor for loop. Ex: Declare Cursor for_cur is select name from customer where repid=20; Cur_rec for_cur%type; Begin For cust_rec in for_cur loop Delete from customer where name=readymoney; Commit; End loop; Dbms_output.put_line( name has been deleted); End; Implicit cursor PL/SQL implicitly declares cursors for all SQL data manipulation statements, including queries that return one row. For queries that return more than one row, we should use explicit cursors to access the rows individually. Implicit cursor attributes can be used to access information about the most recently executed SQL statement. The most recently executed SQL statement is referred as SQLCURSOR. The implicit cursor attributes are: %notfound %found %rowcount %isopen %notfound: This %notfound attribute evaluates to true if DML statements do not return any row, else it evaluates to false. Ex: Begin Delete from customer where name= ready money; If sql%notfound then Dbms_output.put_line(value not found); End if; End; 94 / 122 By Naveen Jaiswal

Database Management System Concepts

If a select statement fails to return a row, then, the predefined exception no_data_found is raised. Then, normal execution stops and control transfers to the exception handling part. In that case, attribute SQL%NOTFOUND will not be used to find out whether the SQL DML statement has affected a row. %Found: The %found attribute is the logical opposite of the %notfound attribute. The %found attribute is evaluated to true if the SQL DML statement affects one or more rows, else it is evaluated to false. %Rowcount The %rowcount attribute counts the number of rows returned by an SQL DML statement. The %rowcount will return zero if the DML statement does not affect any row. The following example uses the %rowcount attribute to check if the cursor fetches any rows. Ex: Declare Cursor c1 is select name from customer where repid=10; Cust_rec c1%rowtype; Begin Update customer set name=vivek where repid=10; If sql%rowcount > 0 then Dbms_output.put_line(record exists); End if; End loop; End;

%isopen Oracle closes the SQL cursor automatically after executing its associated SQL statement. As a result, %isopen is always evaluated to true. PL/SQL composite data types: Scalar datatypes supported by PL/SQL have already been discussed in the previous session. In this session we will be introduced to composite datatypes. Composite datatypes can be broadly classified into table and record datatypes. Let us discuss one by one in detail.

95 / 122

By Naveen Jaiswal

Database Management System Concepts PL/SQL tables: PL/SQL tables are temporary array-like objects used in a PL/SQL block. PL/SQL tables can have one column and a primary key. The column datatype can belong to any scalar datatype, but the primary key must only belong to the type binary-integer. Like the size of the database table, the size of the PL/SQL table is unconstrained, i.e., the number of rows can increase dynamically. PL/SQL tables uses primary key to provide array-like access to the rows. Note: the column and the primary key belonging to PL/SQL table cannot be named.

Declaring PL/SQL tables: A PL/SQL table can be declared in the declarative part of any block, subprogram or package. A PL/SQL table must be declared in two steps. First, we define a table type. Then, we declare a PL/SQL table of that type. The format is as follows: Declare Step1 Type <name-of-type> is table of <col-def> Indexed by binary-integer; Step2 <PL/SQL table name> <type name>; While defining a column in step1, we can also use the %type attribute to provide the column type. Ex: Declare Type curtype is table of char(10) index by binary-integer; After defining type named custtype, we can declare PL/SSQL tables of that type as follows. Custom custtype; After the above declaration we can use custom to represent an entire PL/SQL table. A PL/SQL table is unconstrained because the primary key can assume any value in the range defined for binary-integer. Therefore we cannot initialize PL/SQL table in its declaration. For example, the following declaration is illegal. Custom custtype:= (vivek, vgp,creadymoney);

96 / 122

By Naveen Jaiswal

Database Management System Concepts Referring PL/SQL table: To refer rows in a PL/SQL table, we specify the primary key value using the array-like syntax shown below. PL/SQL_table_name (primary_key_value) Here primary_key_value belongs to type binary-integer. for ex: to refer the 4th row in the cust_tab PL/SQL table, the following syntax is used. Cust_tab(4) Since the magnitude range of binary_integer ranges from 2^(31-1) to 2^(31-1), the following reference is legal. Cust_tab(-3) ----Note: the value of a PL/SQL expression can be assigned to a specific row using the following syntax, PL/SQL_table_name (primary_key_value):= PL/SQL expression; The following example assigns the sum of variable qty and primary to the second row in the PL/SQL table. Cust_tab(2):=qty+primary; The following example illustrates the above-mentioned concept. We know that the table customer contains all details relevant to the customer. If, say, we want to know only the details about name of customers, we can use a PL/SQL table to achieve it. Ex: Declare Type custtype is table of index by binary_integer; Cust custtype; Custname varchar2(30); I binary_integer:=0; Begin Custname:= &a; Cust(I):=custname; If cust(I) = vivek where repid=10; Update customer set name=Vijay where repid=10; Dbms_output.put_line(updation performed); End if; End; Note: to load more than one PL/SQL table, cursor fro loop can be used. 97 / 122 By Naveen Jaiswal

Database Management System Concepts

Maintaining row count in PL/SQL tables: As the size of the PL/SQL table is unconstrained, to maintain the number of rows, we have to declare a variable in the declarative part of the PL/SQL block.] It is essential to maintain a row count, if not, PL/SQL will eventually run out of memory, thus, rising the predefined exception storage error. In the following example an integer variable is used to store the number of current rows present in the PL/SQL table. Ex: Declare Type prices is table of number(4) index by binary_integer; Price_tab prices; I binary__integer := 0; Begin Loop I:= I+1; Price_tab(I) := 1; Exit when I=10; End loop; Dbms_output.put_line(total number of rows are | | to_char(I)); End; Inserting and fetching rows using a PL/SQL table: We can insert values from a PL/SQL table into a database column using loop statements. The following example is used to insert values from PL/SQL into customer table. Declare Type price_type is table of number(4) index by binary_integer; Price_tab price_type; I binary_integer:=10; Begin Loop I:=I+2; Price_tab(I):=I; Insert into price(prodid) values(price_tab(I)); End loop; End;

98 / 122

By Naveen Jaiswal

Database Management System Concepts It is also possible to fetch rows from a database into a PL/SQL table using loop statements. The following example fetches all the rows from the price database table into a PL/SQL table. Ex: Declare Itemrec item%rowtype; Type itemtype is table of number(4) index by binary_integer; Itemtab itemtype; I binary_integer : = 0; Begin For itemrec in(select itemid from item) Loop I:=I+1; Itemtab(i) : = itemrec.itemid; Dbms_output.put_line( || itemtab(i)); End loop; End; Note: we can also use procedures to achieve the above task. Deleting rows from a PL/SQL table: To delete rows from a PL/SQL table we cannot use a delete statement, because in the delete statement it is not possible to specify PL/SQL tables. Therefore to delete a PL/SQL table, we follow the steps given below: We should declare another PL/SQL table of same type as that of the original table, which is to be declared. The new PL/SQL table should be kept empty. The empty table should then be assigned to the original PL/SQL table, only then the PL/SQL table will be deleted. Note: we can delete only an entire PL/SQL table and not individual rows from it. Ex: Declare Type ordertype is table of number(4) index by binary_integer; Ord_tab ordertype; Empty_tab ordertype; Begin For I in 1..50 Loop Ord_tab(i) := I; Dbms_output.put_line( | |ord_tab(i)); 99 / 122 By Naveen Jaiswal

Database Management System Concepts End loop; Ord_tab := empty_tab; If ord_tab (3) is null then Raise no_data_found; End if ; Exception When no_data_found then Dbms_output.put_line(data not found); End; Records: In the composite datatype record, we can specify the datatype of the column and can also define our own columns in the record. Thus a record datatype allows us to access information about the attributes of a database table, which cannot be achieved using %rowtype attribute alone. User-defined records can have any number of columns belonging to different datatypes, which is not so in the case of PL/SQL tables. Declaring records: Like PL/SQl tables, records must be declared in two steps. Firstly, we must define a record type with the help of the following syntax: Type <type name> is record (column definitions..); Attributes like %type and %rowtype can also be used to specify column datatype. After declaring a record type, the next step would be to declare a record of that type as an identifier to represent an entire record. The syntax is shown below: <PL/SQL record type> <type name>; Consider the following example, which declares a record type named price_rectype. It is later identified by price_rec. Declare Type price_rectype is record (prodid number (4) not null: = 10; minimum price.maxprice%type); Price_rec price_rectype; In the above example, each column has a unique name and specified datatype. Not null constraint is appended to the column prodid to prevent null values. Note: Column declared, as not null must be initialized in the deceleration part. 100 / 122 By Naveen Jaiswal

Database Management System Concepts A record can be initialized in its declaration unlike PL/SQL tables, which doesnt allow initialization in the declaration part. The following example declares a record of type timetype, which has all its columns initialized with null values. Ex: Declare Type timetype in record (hour integer: = 0, minute integer: =0; second integer: =0); Tim_typ timetype;

Note: Records can be declared as parameters for procedures and functions. Record can also be declared while using cursor for loop. Referencing records: We can refer individual fields or columns in a record with the help of the syntax, given below: <Record name> <column name>; For example, to assign 25-jul-77, to the column shipdate belonging to the record order_rec, we can proceed as follows. Order_rec.shipdate: = 25-jul-77; We can also assign the value of PL/SQL expression to a specific column by using the following syntax. <Record name>.<column name>: = PL/SQl expression; oreder_rec.qty := price*total; we are now familiar with the syntax for referring and assigning individual columns or fields in a record. Now let us see how values can be assigned to all columns simultaneously. This can be done in two ways. The first way should be to assign one record to another, provided both belong to the same datatype. Ex: 101 / 122 By Naveen Jaiswal

Database Management System Concepts

Declare Type item_typ is record (itemid number (80 not null := 20; ordid item.ordid%type := 500); Rec2 item_typ; Rec3 item_typ; Begin Rec2.itemid := 20; Rec2.ordid := 100; Rec3 :=rec2; Dbms_output.put_line (itemid | | to_char(rec3.itemid)); Dbms_output.put_line(ordid | |to_char(rec3.ordid)); End; The second method for assigning values to all fields at once is illustrated below with the help of an example. Ex: Declare Type item_typ is record(itemid number (8) not null: =20; ordid item.ordid%type); Item_rec item_typ; Begin Select itemid, ordid into item_rec into item_rec from item where prodid: =150; Dbms_output.put_line(to_char(item_rec.itemid)); Dbms_output.put_line(to_char(item_rec.ordid)); End; The above example has used select into clause. Database triggers: A database trigger is a stored procedure that is fired when an insert, update or delete statement is issued against the associated table. Database triggers can be used for the following purpose. To generate data automatically To enforce complex integrity constraints To customize complex security authorizations. To maintain replicate tables. To audit data modifications.

Syntax for creating triggers: The syntax for creating a trigger is given below 102 / 122 By Naveen Jaiswal

Database Management System Concepts Create or replace trigger <trigger name> [Before/after] [Insert/update/delete] on <table name> [for each statement/for each row] [When <condition>]; A database trigger can also have declarative and exception handling part. Parts of triggers: A database trigger has three parts, namely, a trigger statement, a trigger body and a trigger restriction.

Trigger statement The trigger statement specifies the DML statements like update, delete and insert and it fires the trigger body. It also specifies the table to which he trigger is associated. Trigger body It is a PL/SQL block that is executed when a triggering statement is issued. Trigger restriction: Restriction on a trigger can be achieved using the when clause as shown in the above syntax. They can be included in the definition of a row trigger, wherein, the condition in the when clause is evaluated for each row that is affected by the trigger. Note: a subquery cannot be included in the when clause. Types of triggers: Triggers are categorized based on when they are fired: Before After For each row For each statement (default) Before/after options: The before/after options can be used to specify when the trigger body should be fired with respect to the triggering statement. If the user includes a before option, then, Oracle fires the trigger before executing the triggering statement. On the other hand, if after is used, then, Oracle fires the trigger after the executing the triggering statement. 103 / 122 By Naveen Jaiswal

Database Management System Concepts

For each row / statement: The for each row / statement option when included in the create trigger syntax specifies that the trigger fires once per row. By default, a database trigger fires for each statement. Using a combination of the above options, we can assign 12 triggers to a database table. Only one trigger of each type can be assigned to a table. Before update row/statement Before delete row/statement Before insert row/statement After update row/statement After delete row/statement After insert row/statement In general, each table can have four triggers (before / after/ statement / row) on statement (insert / update / delete). Thus we can assign twelve triggers to a single table. Note: we already know about DBMS_standard which provides the language facility to interact with oracle. This package provides a procedure named raise_application_error to issue user-defined error messages. The syntax is given below: Raise_application_error(error_number, error_message); The error_number ranges from 20000.-20999 and the error_message can be a character string. Ex: Create or replace trigger trig Before insert on item for each row Declare Item_ident; Begin Select itemid into item_ident from item where qty =5000; If item.ident =1000 then Raise_application_error (-2000, enter some other number); End if; End; The above example also illustrates the before row trigger. Oracle fires this trigger before adding each row by using the insert statement. The following example uses triggers to avoid transactions during Saturday and Sunday Ex: 104 / 122 By Naveen Jaiswal

Database Management System Concepts

Create or replace trigger sun_trig Before insert or update or delete On order_info Declare Shipping_date char; Begin Shipping_date := to_char(sysdate,dy); If shipping_date in (sat,sun) then Raise_application_error (-2002, try on any weekdays); End if; End; The above trigger will fire if insert, update or delete statements affect the order_info table. Since it is a before statement trigger, Oracle fires it once before executing the trigger statement. There are two variables namely, :old and: new which retain the old and new values of the column updated in the database. The values in these variables can be used in database triggers for manipulation. Instead of triggers: Oracle 7 introduced the concept of database triggers that fired before or after a particular event occurring on a table. These triggers could fire either at the row or a statement level. Version 7.1 added the ability to have multiple triggers for the same event. This feature overcame a number of practical difficulties; the most obvious was that many different applications could now apply their own triggers to a particular event without having to be aware of the logic required by each other. Oracle designers have used triggers to great effect, particular in the implementation of denormalization and the enforcement of complex data rule. With the coming of oracle 8 many designers and developers had hoped that oracle 8 would support select triggers. Such triggers would enable queries to be intercepted and would allow user specified logic to take place at query time; simply recording the query would have been a major potential use of such a trigger. Select triggers would have also been a powerful tool in implementing auditing and data sensitive security. But however appearing such select triggers might be, they are not what instead of triggers are about. Working of the instead of triggers: In oracle8 there is something new in the world of triggers: instead of triggers. These are triggers that are defined on a view rather than on a table. Such triggers can be used to overcome the restrictions placed by oracle on any view, which is deemed to be nonupdateable. Prior to version 7.3 it was impossible to issue DML statements-insert, delete 105 / 122 By Naveen Jaiswal

Database Management System Concepts and update-against any view which contained a join. In version 7.3, it became possible to issue DML against a join view, but only with sever restrictions. Only columns belonging to one table can be updated in a single statement, and the view must be key preserved, meaning that the join key columns may not be updated. In oracle 8, instead of triggers are defined on the same event as their table counterparts: insert, delete and update. Since there is no provision for a trigger, which is run at lock time, then either locking must be implicit or the application must know what objects to lock. Despite this minor inconvenience, the new triggers have removed major constraints on design. The designer now has the ability to specify the logic to be used to perform DML against any view definition, and this logic need only be implemented once. Without these triggers, designers had two choice. The view update logic had to be placed in a stored procedure, which every application that used the trigger expected to call. Worse, each application was expected to contain its own version of the logic. The problem with these solutions is that both of them cooperative that is, they work only if each application behaves according to the same set of rules. Cooperative solutions make maintenance somewhat daunting. There are few restriction raises a surprising anomaly if you issue this statement: Create view emp_view as select * from emp; It would be legal to declare a trigger as follows: Create trigger emp_insert instead of insert on emp_view Begin Delete from emp where empno:= new.empno; End; However, it would be illegal to declare the same trigger on emp even though the resulting action would be identical. The completely legal view shown in this definition is an example of subversion. Any normal maintenance programmer who known or can inspect the view definition, and encounters the statement: Insert into emp_view (empno, ename, deptno) values (1111,smith, 40); Will assume that the result of the statement will be at least one row in emp. Conventional triggers may augment that action in any number of ways, but the basic meaning of the statement will still be reflected in the result. The instead of trigger caries no such guarantee. The result of the trigger may be quite contrary to the apparent meaning of the statement invoking the trigger. Because the code is encapsulated in the trigger, unless access to the data dictionary is given and can both 106 / 122 By Naveen Jaiswal

Database Management System Concepts discover the existence of the trigger and inspect the trigger text, an apparent mystery is encountered. An insert is issued against emp_view but when the view is retrieved the new data is nowhere to be seen. However, if the insert has resulted in a duplicate empno being added then the row currently containing that employee number will be deleted. The example may seem extreme but it works. Role of instead of trigger- the two points learned so far: For any view if a meaning can be defined for insert, update or delete then the required actions can be implemented. Even if the actions make perfect sense they may not be at all intuitive to anyone else and they will be both encapsulated and potentially difficult to find. Using multiple instead of triggers will only make this situation worse. Unfortunately, some designers might over use Instead of triggers and therefore cause serious damage to maintainability and possibly even the integrity, of their applications. Nevertheless, instead of views have a natural role in allowing insert, update and delete to be applied to views, which would otherwise not be updateable. Example of such cases include: Allowing updates to single table views, which for security reasons do not project a NOT NULL column, which is present in the table. Join views, which translate codes into their standard meaning: such views can be a source of major performance enhancement in client/server operations. Again, update and delete triggers may make perfect sense. Union all views used to support manual partitioning. In this case, it will often be quite simple to code trigger logic to determine which of the partitions is subject to any particular DML operation. However, remember that although manual partitioning allows key partitioning to be applied using any scheme the designer chooses to employ. Enabling and disabling a trigger: A trigger can be either enabled or disabled. An enabled trigger executes the trigger body if the triggering statement is issued. By default, triggers are enabled. A disabled trigger does not execute the trigger body even if the triggering statement is issued. We can disable a trigger using the following syntax. Alter trigger <trigger name> disable; The following example disables the trigger named trig. Ex: alter trigger trig disable;

107 / 122

By Naveen Jaiswal

Database Management System Concepts To disable all the triggers associated with the table, we can use issue the following syntax. Alter table <table name> disable all triggers;

Note: To enable a trigger, which is disabled, we can use the following syntax: Alter table <table name> enable; All the triggers defined for a specific table can be enabled by the following syntax: Alter table <table name> enable all triggers; Dropping triggers: To drop a trigger from the database, the drop trigger command is used. The syntax is: Drop trigger <trigger name>; Subprograms: Subprograms are named PL/SQL blocks that can accept parameters and can be invoked whenever required. Similar to a PL/SQL block, a subprogram can also have a declarative part, an executable part and an exception handling part. Some of the important features offered by subprograms are given below. Modularity: Subprograms allow us to break a program into manageable, well-defined logical modules. Reusability:- Subprograms once executed can be used in any number of applications. Maintainability:-Subprograms can simplify maintenance, because if a subprogram is affected, only its definition changes. PL/SQL supports two types of subprograms. They are: Procedures Functions 108 / 122 By Naveen Jaiswal

Database Management System Concepts

Generally, we use procedures to do some specific task and functions to compute a value. Procedures: A procedure is a subprogram that performs a specific action. The syntax for creating a procedure is given below. Create or replace procedure <proc name> [parameter list] is <logical declarations>; Begin Executable statements; [Exception] End; A procedure has two parts, namely, specification and body. The procedure specification begins with the keyword procedure and ends with the procedure name or parameter list. The procedure body begins with the keyword is and ends with the keyword end. It can also include declarative, executable and exceptional parts within the keywords is and end. Syntax to execute a procedure is given below. Exec <proc name> (parameters); While declaring variables in the declarative part of the procedure body, we should not specify the width of the data type. For example: Procedure width (name char(40)) is Begin Set of statements; End; In the above example, char(40) should be replaced by char. The following example illustrates the usage of procedures. It is used to increase the actual price of an item by an amount provided by the user. Ex: Create procedure tot (identity number, total number) is Price number; Null_price exception; Begin Select actualprice into price from item where itemid=identity; If price is Null then 109 / 122 By Naveen Jaiswal

Database Management System Concepts Raise null_price; Else Update item set actualprice=actual_price +total where itemid=identity; End if; Exception When null_price then Dbms_output.put_line ( the value of price is null); End; While executing the above procedure, it prompts the value of identity and total from the user. With the help of the value provided by the user, it fetches the corresponding itemid from the database table item. The above procedure is executed as shown below Exec tot(23,300); The parameter list (defined in the create procedure command) can hold any of the following modes, namely, in(by default), out and inout. These parameter modes can be within any subprogram. In parameter: The in parameter mode is used to pass values to the subprogram when invoked. It acts like a constant and therefore it cannot be assigned a value. Consider the following example. Ex: Create or replace procedure pond(a in number) is Price number; Begin Select actualprice into price from item where itemid= a; Dbms_output.put_line(actual_price is | | to_char(price)); If price is Null then Dbms_output.put_line (the value of price was found to be null); End if; End; While executing the above procedure, it prompts the value of a from the user. With the help of the value provided by the user, it fetches the corresponding itemid from the database table item. This procedure is executed by the following syntax: Exec pond(2000; Out parameter:

110 / 122

By Naveen Jaiswal

Database Management System Concepts The out parameter mode is used to return values to the caller of a subprogram. Since the initial value for an out parameter is undefined, its value can be assigned to another variable. Ex: Create or replace procedure test ( a is number, b out number) is identity number; Begin Select ordid into identity from item where itemid =a; If identity <1000 then b:=100; End if; End; While executing the above procedure we pass only variables for an out parameter. Constants and expressions are not allowed as an out parameter. For example Exec test(100,b) is legal Exec test(100,20) is not legal Exec(100, price_qty) is not legal The same is applicable for the inout parameter. The procedure test is executed by the following block. Ex: Declare A number; B number; Begin Test(4000, b); Dbms_output.put_line ( the value of b is | | to_char(b)); End; In out parameter: The in out parameter is used to pass initial values to the subprogram when invoked and it also returns updated values to the caller. An in out parameter acts like an initialized variable and therefore, can be assigned to other variables or to itself. Ex: Create or replace procedure sample ( a in number , b in out number) is identity number; Begin Select ordid, prodid into identity, b from item where itemid=a; 111 / 122 By Naveen Jaiswal

Database Management System Concepts If b < 600 then B:=b+100; End if; End; To pass parameters to the above procedure, the following block is used.

Ex: Declare A number; B number; Begin Sample(3000, b); Dbms_output.put_line ( the value of b is | | b); End; Functions: A function is a subprogram that computes a value. The syntax for creating a function is given below Create or replace function <function name> [argument] Return datatype is (local declaration) begin (executable statements) [exception] (exception handlers) end; where arguments can be in, out and inout. Like a procedure, a function also has two parts, namely, the function specification and the function body. The function specification begins with the keyword function and ends with the return clause. The function body begins with the keyword is and ends with the keyword end. A PL/SQL block can also be included in a function body. Ex: Create or replace function func (id number, amount number) return Boolean is Minimum real; Maximum real; 112 / 122 By Naveen Jaiswal

Database Management System Concepts Begin Select minprice, stdprice into minimum, maximum from price where prodid=id; Return (minimum >=amount) or (maximum <=amount); End; To pass parameters to the above function, we can write a program as shown below.

Ex: Declare Id number; Amount number; Remark Boolean; Begin Id := &a; Amount:=&b; Remark:=func(id,amount); If remark =true then Dbms_output.put_line(true); Else Dbms_output.put_line(false); End if; End; Note: A function can be called as part of an expression inside a procedural statement. Packages: A package is a database object, which is an encapsulation of related PL/SQL types, subprograms, cursors, exceptions, variables and constants. It consists of two parts, a specification and a body. In the package specification we can declare types, variables, constants, exceptions, cursors and subprograms. A package body implements cursors, subprograms defined in the package specification. Note: Packages cannot be called, hence, we cannot pass parameters as we do in subprograms. Nesting of packages is also not possible. Packages can be created using the following commands.

113 / 122

By Naveen Jaiswal

Database Management System Concepts Create package command Create package body command. The package specification is declared using a create package command. The syntax for the create package command is as follows. Create package <pack name> as (public type, object declarations, subprogram specifications); [begin (executable statements) end] [package name]; the procedures and cursors declared in the create package command is fully defined and implemented by the package body, which can be achieved by using the following syntax. Createe package body <package name> as (private type, declarations, subprogram bodies); [begin (executable statements); end] [body name]; in the create package and create package body commands, the keywords public and private denote the usage of object declaration in a package. Items declared in the package body, can be termed as private because their use is restricted within the package. On the other hand, items declared in the package specification can also be used outside the package. Such items are referred to as public objects. The package specification The package specification contains public objects and types. It can also include subprograms. The specification contains the package resources required for our application. If a package specification declares only types, constants, variables, and exceptions, then we need not include package body, because all the information required for the usage of types, constants, variables and exceptions are specified in the specification. Only subprograms and cursors have an underlying implementation or definition and hence we got to include package body. Package body: The package body contains the definition of every cursor and subprogram declared in the package specification and implements them. Private declarations can also be included in

114 / 122

By Naveen Jaiswal

Database Management System Concepts a package body. Till now, we were discussing about the declarative part of package body. Now let us have an understanding of the initialization part. The initialization part of the package body is optional. It may consist of statements that initialize some of the variables previously declared in the package. The initialization part of a package plays a minor role, because, neither a package can be called nor parameters be passed to it. Therefore, the initialization part of a package is run only once. Note: oracle stores package specification and body separately in the data dictionary. Ex: Create or replace package pack_me is Procedure item_pro (items number, prods number, quantity number); Procedure cost (id number, increase number); Function func(id number) return number; Missing_price exception; End pack_me; The above example illustrates the usage of packages whereby cursors, procedures and datatypes are packed. An example follows illustrates the concept of a package body. Ex: Create or replace package body pack_me as Procedure item_pro(items number, prods number, quantity number) is Begin Insert into item (itemid, produd, qty) values (items, prods, quantity); End item_pro; Procedure cost (id number, increase number ) is Begin Declare Pprice number; Begin Select actualprice into pprice from item where prodid =id; If pprice is Null then Raise missing_price; Else Update item set actual_price=actualprice +increase where prodid=id; End if; Exception When missing_price then Dbms_output.put_line ( the value of price is null); 115 / 122 By Naveen Jaiswal

Database Management System Concepts End cost; End; Function func (id number) return number is Headcount integer; Begin Select count (8) into headcount from customer where repid=20; Rerurn (headcount+1); End func; End pack_me; Calling packaged subprograms To reference the types, objects and subprograms declared in a package specification the following notation is used. Package-name.type-name Package-name.object-name. Package-name.subprogram-name. We can also refer to the package contents, from database triggers, embedded PL/SQL blocks, stored subprograms and Oracle tools such as SQL*plus. A stored subprogram can call a packed subprogram. Ex: Pack_me.item_pro(100,232,50); Where pack_me refers to the package and item_pro refers to the procedure. The following example calls the packed subprogram cost interactively from SQL *plus. Ex: execute pack_me.cost(100,300); Note: Before executing a packed subprogram, oracle marks an implicit savepoint. If a subprogram fails in the package, then, before returning to the host environment, oracle rolls back to the savepoint and undoes database changes made by the subprogram. While including subprograms in the database triggers or SQL forms, the application cannot call packed subprograms if they contain commit, rollback or savepoint. Overloading:

116 / 122

By Naveen Jaiswal

Database Management System Concepts PL/SQL permits two or more packaged subprograms to have the same name. This option is used when we want a subprogram to accept parameters that belong to different datatypes. Package degree_pack is Procedure bachelor_deg(name char, course char); Procedure bachelor_deg(name char, course number); End degree_pack; Package body degree_pack is Procedure bachelor_deg(name char, course char) is Begin .. end [bachelor_deg]; Procedure bachelor_deg(name char, course number) is Begin .. End [bachelor_deg]; End [degree_pack]; In the above example, both the procedures have the same name bachelor_deg but the first procedure accepts course as a character string and the second one accepts it as a number.

117 / 122

By Naveen Jaiswal

Database Management System Concepts

Example programs. The following example uses a simple FOR loop to insert ten rows into a database table. The values of a loop index, counter variable, and either of two character strings are inserted. Which string is inserted depends on the value of the loop index. Input Table Not applicable. PL/SQL Block DECLARE x NUMBER := 100; BEGIN FOR i IN 1..10 LOOP IF MOD(i,2) = 0 THEN -- i is even INSERT INTO temp VALUES (i, x, 'i is even'); ELSE INSERT INTO temp VALUES (i, x, 'i is odd'); END IF; x := x + 100; END LOOP; COMMIT; END; Output Table SQL> SELECT * FROM temp ORDER BY col1; COL1 COL2 MESSAGE 118 / 122 By Naveen Jaiswal

Database Management System Concepts ----- ------1 100 2 200 3 300 4 400 5 500 6 600 7 700 8 800 9 900 10 1000 --------i is odd i is even i is odd i is even i is odd i is even i is odd i is even i is odd i is even

10 records selected. The next example uses a cursor to select the five highest paid employees from the emp table. Input Table SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC; ENAME ---------KING SCOTT FORD JONES BLAKE CLARK ALLEN TURNER MILLER WARD MARTIN ADAMS JAMES SMITH EMPNO ----------7788 7902 7566 7698 7782 7499 7844 7934 7521 7654 7876 7900 7369 SAL -------7839 3000 3000 2975 2850 2450 1600 1500 1300 1250 1250 1100 950 800


14 records selected. PL/SQL Block DECLARE CURSOR c1 is SELECT ename, empno, sal FROM emp 119 / 122 By Naveen Jaiswal

Database Management System Concepts ORDER BY sal DESC; -- start with highest paid employee my_ename CHAR(10); my_empno NUMBER(4); my_sal NUMBER(7,2); BEGIN OPEN c1; FOR i IN 1..5 LOOP FETCH c1 INTO my_ename, my_empno, my_sal; EXIT WHEN c1%NOTFOUND; /* in case the number requested */ /* is more than the total */ /* number of employees */ INSERT INTO temp VALUES (my_sal, my_empno, my_ename); COMMIT; END LOOP; CLOSE c1; END; Output Table SQL> SELECT * FROM temp ORDER BY col1 DESC; COL1 --------5000 3000 3000 2975 2850 COL2 -------7839 7902 7788 7566 7698 MESSAGE ------KING FORD SCOTT JONES BLAKE

The following example illustrates block structure and scope rules. An outer block declares two variables named x and counter and loops four times. Inside this loop is a sub-block that also declares a variable named x. The values inserted into the temp table show that the two x's are indeed different. Input Table Not applicable. PL/SQL Block 120 / 122 By Naveen Jaiswal

Database Management System Concepts

DECLARE x NUMBER := 0; counter NUMBER := 0; BEGIN FOR i IN 1..4 LOOP x := x + 1000; counter := counter + 1; INSERT INTO temp VALUES (x, counter, 'outer loop'); /* start an inner block */ DECLARE x NUMBER := 0; -- this is a local version of x BEGIN FOR i IN 1..4 LOOP x := x + 1; -- this increments the local x counter := counter + 1; INSERT INTO temp VALUES (x, counter, 'inner loop'); END LOOP; END; END LOOP; COMMIT; END; Output Table SQL> SELECT * FROM temp ORDER BY col2; COL1 ------1000 1 2 3 4 2000 1 2 3 4 3000 1 2 3 COL2 -------1 2 3 4 5 6 7 8 9 10 11 12 13 14 MESSAGE ------------OUTER loop inner loop inner loop inner loop inner loop OUTER loop inner loop inner loop inner loop inner loop OUTER loop inner loop inner loop inner loop 121 / 122 By Naveen Jaiswal

Database Management System Concepts 4 4000 1 2 3 4 20 records selected. 15 16 17 18 19 20 inner loop OUTER loop inner loop inner loop inner loop inner loop

122 / 122

By Naveen Jaiswal