Professional Documents
Culture Documents
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,Sysbase and informix. What is Database Management System? A DBMS is essentially a collection of interrelated data and a set of programs to access this data. This collection of data is called the Database.A Database System consists of two parts namely, Database Management System and 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 updates information stored in the DBMS DBMS has to protect database against unintentional changes that could be caused by users and applications In case of multi-user system, it must be capable of notifying any database change to the other user.
Codds Rules A database management system should obey the following twelve rules of Dr. E.F.Codd for it to be relational. 1. The Information Rule: Each and every piece of data should be represented as datavalue of a table. 2. The Guaranteed Access Rule: Every piece of data must be accessible by specifying the name of the table,column of the data and the primary key value of the row
3. The Systematic Treatment Of Null Values: Database System must support Null value to represent unknown or inapplicable information. It must be different from zero and spaces. NULL value must be independent of datatype. 4. The Database Description Rule: The description of database objects stored in the database must also be stored logically as the data and should be accessible to the users with appropriate privileges. It is usually called as System catalog or data dictionary.
Integrity Constraints
Authorization Transaction Management Operations
6. View Updating Rule : All kinds of views that are theoretically updateable must also be updateable by the system.
11. The Distribution Rule : The system must be able to access or manipulate the data that is distributed in other systems. 12. The Non - Subversion Rule:
The Non -subversion rule states the 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 then it should not bypass any integrity constraints defined in the higher level.
Create table <tablename>(co11 definition, co12 definition, co13 definition, co1n definition);
Criteria In Creation of Table
Table name should not exceed 30 characters in length
and no spaces are allowed between table name. Inspite of spaces underscores can be used. Example :SQL>Create table emp(eno number(4),ename varchar2(30),designation varchar2(30),salary number(8,2));
After creating the table to view the structure of the table syntax is SQL>Desc <tablename> Which displays the structure of the table.
Syntax To Modify a Table:To add a column to the table following is the syntax Alter table <tablename> add(col1 definition,col2 definition,coln definition); If the user want to add more than one column than it has to be given within parentheses. Just to add one column parentheses is not a must.
Example:
SQL>Alter table emp add(dob date,doj date); The columns added to the table with the help of alter table command will be added to the end of the table, and the user cannot insert a column between existing columns. But at time of viewing the user can select the columns according the user wish.
width.
Criteria to be followed when modifying the column in a table.
To change the Datatype of a column and to decrease the
width of a column the table should be empty. Example: SQL>Alter table emp modify(salary number(10,2));
Deleting a Column from a table: In oracle 8i we can delete a column and the syntax to delete a column is SQL> Alter table <table name> drop column <column name> Dropping a Table: To dropping a table is very simple and the syntax to drop the table is : Drop table <tablename>; Example: SQL>Drop Table Emp;
The Structure of the table is removed from the database after performing the above command. Before dropping the table the user should be careful because table once dropped it cannot be retrieved.
Data Manipulation Language Commands:Since table is dropped user has to create the table again SQL>Create table emp(eno number(4),ename varchar2(30),designation varchar2(30),salary number(8,2),dob data,doj date);
Select Command : This command is used the view the rows in a table. SQL> Select * from emp;
The above statement displays the value for all the columns
in the table * is a wild card character which displays the values of all column. By default the values are displayed in the order in which the table is created.
Example:
SQL> Insert into emp values(101,Aswin,Programmer,12000,02-Aug-78,02nov-98);
If the user want to insert a set of records then the user should use the & symbol.
Example to insert more than one record : -
For number datatype giving the value within quotes is an optional part. By default in oracle for all the columns the user has to insert records even to insert NULL value user has to specify explicitly it contains NULL value . If the user want to insert rows for few columns and not to all the columns in the table means the syntax is SQL>Insert into <tablename> (col1,col3,col5) values (list of data values);
In the above example the user can insert multiple records. Update Command: Syntax to update a record in a table. SQL>update <tablename> set =col1 where <condition>; Example for Updating Records in a Table: SQL> update emp set designation=Manager where eno=101; In the update statement if the user is ignoring the where clause then all the records in the table will be updated. More than one column can also be updated in a table.
Example for updating more than one column in a Table: SQL> update emp set designation=Manager , Doj=15-Sep-78 where eno=101; Delete Command : Syntax to delete all records in a table SQL> Delete from <tablename>; If the user want to delete a set of records then the syntax is SQL> Delete from <tablename> where condition;
Example to delete set of records : SQL> Delete from emp where eno = 105; All DML Commands are not fixedly stored in the database if the user want to store the transaction preformed into Database then the user has to commit the transaction. Transaction Control Language (TCL) Commands : -
Commit Command : After performing any DML Commands user has to give the commit statement. SQL> Commit;
Rollback Command: To retrieve the transactions from the database user can go for Rollback command. SQL>Rollback; Savepoint command: If the user want to commit or rollback up to certain transaction than savepoint can be used it acts like a bookmark. SQL> Savepoint S1; After creating savepoint user can commit or rollback to savepoint.
Truncate Command: Truncate command leaves the structure of the table and removes all the rows in a table. And the rows cannot be retrieved after truncating the table. Example for Truncating the Table: SQL>Truncate table emp; The above command removes the rows from the table emp and the structure is left. This we can check it by place the select command on the table.
Operators in SQL
The following are the operators supported by SQL
Arithmetic Operators Comparison Operators
Logical Operators
Arithmetic Operators : All arithmetic operators (Addition, Subtraction,Multiplication,Division) can be performed on SQL Statements.
For Example:
SQL> Select eno,ename,salary+1500 salary from emp where salary>8000; Comparison Operators Comparison Operators are used in conditions to compare one expression with another. The comparison operators are =, !=,<, >, <=, >=, Between, In,Not In
Example for Comparison Operator SQL>Select eno,ename from emp where ename like R%; The above command displays the records of the employees those name starts with R and followed by any number of characters. SQL> Select eno,ename from emp where ename like R__;
Logical Operators : A logical operator is used to combine the results of two conditions to produce a single result the logical operators are
And Operator OR Operator Not Operator
If the user want to view the details of the employee whose designation is Programmer and his/her salary should be greater than 10000. Then
Not Operator
If the user want to view the details of employee who salary is not 10000 then the following query can be issued SQL> Select * from emp where salary !=10000; The above query can be issued in different ways they are
Operator Precedence: Arithmetic Operators Comparison Operators Not Logical Operator highest
Note :
The order of precedence can be altered by using parenthesis.
Order By Clause: Order by Clause is used to sort the records. Column can be sorted in either by ascending or descending, By default oracle sorts the column in ascending order if the user want to sort the column in descending order then
Restrictions in Order by Clause : Order by Clause cannot have any conditions and it can be last statement in SQL.
Group by Clause : Group by Clause eliminates the duplicate records and unique records are displayed, In Group by clause the user can place the conditions. Conditions in a group by clause is specified with the having Clause. If the user want to view the employees details who draw the same salary then
Functions
Single Row Functions Group Functions
Single Row Function returns only one value for every row queried in the table. Single row functions can appear in a select command and can 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
The add_months 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 represents the number of months Example for Add_months
Example for Last_day Function: SQL>Select Sysdate,last_day(sysdate) from dual; The above query displays the last day the current month. Months_Between : This function results the number of months between the given dates the format is months_between(date1,date2)
Example
SQL> Select months_between(sysdate,06-Dec-96) from dual;
Next_Day:The format for this function is next_day(date,day) Example SQL>Select next_day(sysdate,Friday) from dual; The above query will the date of next Friday. New_Time:-
The new_time function displays the time and date of a date column or literal date in other time zones
The format is
new_time(date,this,other); this is replaced by a 3 letter abbreviation of the current time zone while other is replaced by a three letter abbreviation of the zone in which the date is wanted.
Numeric Functions : ABS (value) -------------->ABSolute Value CIEL (value) ------------>Smallest integer larger than or equal to value COS (value) ------------> COSine Value
POWER
ROUND(value,precision) ----->Rounding the value to precision
Character Functions : LENGTH: LENGTH tells the user how long a string is how many characters it has in it, including letters,spaces. Example:SQL>Select length(LSIL) from dual; Initcap:Initcap converts the first letter of the word given into capital letter.
Example : SQL> select Initcap(lsil) from dual; LOWER : Converts the word into lowercase. Example : -
Example : SQL> select upper(lsil) from dual; LTRIM:LTRIM (char,set) SQL>Select ltrim(xyzadams,xyz) from dual;
RTRIM:RTRIM(char,set)
Translate: Translate(char,from,to) Example:Translates a single character SQL>Select translate (jack,j,b) from dual;
Substr(char,m,n)
EXAMPLE:-
The second is the number, which indicates the total length of the return value. The third is the string , with which the left padding has to be done when required.
Example:-
LPAD(LSIL) -------------------
******LSIL
The entire string is 10 in length after padding is done. RPAD The Function RPAD does the exact opposite of the LPAD function. The number of arguments it takes is the same as the lpad function.
Example:SQL> Select rpad(LSIL,10,*) from dual; The output gives the sign * before the word LSIL. RPAD(LSIL) ------------------LSIL******
DECODE : Unlike the translate function which performs a character by character replacement the DECODE function does a value by value replacement. Syntax Of DECODE : SQL> Select decode ( <value, if1,then1, if2, then2,--->) from <tablename>; Example : -
CONCAT : Concat Function is used to combine the strings in the database. Example : SQL > Select Concat(first_name,Last_name) Name from emp; Concatenation Operator : Another method to Combine the String is using the Concatenation Operator SQL>Select first_name || last_name from emp;
SQL>Select (The designation of || ename || is || designation || and || ename || draws || salary || per month) from emp where ename = Maya;
CHR : The above function returns the character value of the given number. Example : SQL> Select chr(67) from dual;
Conversion Function : Conversion functions convert a value from one data type to another. The conversion functions are broadly classified into the following.
To_char() To_date() To_number()
where d is the 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. Consider the following example.
SQL> select to_char (sysdate,ddth of fmmonth yyyy) from dual;
The above statement displays the date according to the format specified in the format model. The date will be displayed as
Miscellaneous Functions : The following are some of the miscellaneous functions supported by Oracle.
Uid
User Nvl Vsize
Uid:This function returns the integer value corresponding to the user currently logged in.
Example :SQL> Select Uid from dual; The result could be a number. User:This function returns the logins user name, which is in varchar2 datatype. Example : SQL> Select user from dual; The result will be the name of the current user.
Null value (Nvl) : The Null value function is used in cases where we want to consider Null values as zero or the value which is specified by the user. The syntax is given as nvl (exp1,exp2).
If exp1 is null, nvl will return exp2. If exp1 is not null, nvl will return exp1 If exp1 and 2 are of different datatypes, then
oracle converts exp2 to the datatype of exp1 and then compares it.
Example : SQL> Select ename,salary,nvl(salary,2500) from emp; Vsize :SQL> Select Vsize(LSIL) from dual;
Group Functions : A group function returns a result based on a group of rows. Some of these are just purely mathematical functions. The group functions supported by Oracle are summarized below.
Avg Function Min Function Max Function
Sum Function
Count Function
Avg Function
The Avg function return the average of values of the column specified in the argument of the column Example : SQL> Select avg(salary) from emp where dno=10; Min Function : This function will give the least of all values of the column present in the argument.
Example : SQL> Select min(salary) from emp where dno=10; Max Function : This function will give the highest of all values of the column present in the argument.
Example : SQL> Select max(salary) from emp where dno=10; Sum Function : Th above function can be used to obtain the
Set Operators & Joins Set Operators : 1. Union 3. Intersect 2. Union All 4. Minus
Conditions to be followed in set operators The queries, which are related by a set operator should have the same number of columns and the
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 both queries. The following example combines the result of two queries with the union operator , which eliminates duplicate rows.
SQL> Select dno from emp UNION Select dno from dept ; The union operator returns all distinct column values from the emp and dept table respectively. Union All : The Union All operator returns all rows select by either query including duplicates. SQL> Select dno from emp UNION ALL select dno from dept;
Intersect : Intersect returns only the rows that are common to both the queries. SQL> Select dno from emp INTERSECT Select dno from dept; Minus : Minus operator returns all distinct rows selected only by the first query and not by the second.
SQL> Select dno from dept MINUS Select dno from emp;
Joins The purpose of a join is to combine the data spread across tables. A join is actually performed by the where clause which combines the specified rows of tables. There are Three types of Joins: Simple Join Self Join
Outer Join
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, which is based on equalities, which is called an equi - join. The equi join combines rows that have equivalent values for the specified columns. SQL > select * from emp,dept where emp.dno=dept.dno;
The above query fetches the rows from the table emp and dept where the dno of emp table matches the dno of the table dept.
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 =. The following example is illustrative of this
Example : SQL>Select itemdesc,max_level,qty_ord,qty_deld from itemfile,order_detail where (itemfile.max_level<order_detail.qty_ord) and (Itemfile.itemcode=orderdetail.itemcode); 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. SQL > Select e.eno,e.ename,e.dno,d.dno,d.dname from emp e,dept d where e.dno = d.dno;
Self Join : Joining the tables to itself is known as self join, i.e., it joins one row in a table to another. The join is performed by mirroring the table using the where clause it can compare each row of the table to itself and also with other rows of the same table. SQL>Select e1.ename || works for || e2.ename Employees and their Managers from emp e1,emp e2 where e1.mgr=e2.eno;
Outer Join :The outer join extends the result 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. This cannot be done with simple join alone. The symbol, (+) represents outer join SQL>Select e.eno,e.ename,e.salary,d.dno,d.dname from emp e,dept d where d.dno=e.dno(+); The above example will also retrieve rows from dept table which do not have any matching records in the
emp table. Such a retrieval is due to the presence of an outer join(+). The rows are retrieved in addition to those records which have a simple join.
Subqueries
Nesting of queries one within the other, is termed as a subquery. A statement containing a subquery is called a parent statement. Subqueries are used to retrieve data from tables that depend on the values in the table itself. Example:The user want to view the details of the employees whos salary is equivalent to
Aswin Kumar salary. Without the help of subquery the user has to perform 2 queries one is to identify the salary of Aswin Kumar and the second one is to list the details
Of the employee whos salary is equivalent to Aswin Kumar salary. If the user uses the subquery then complication of the query is reduced. SQL> select * from emp where salary in(select salary from emp where ename = Aswin Kumar);
Correlated Subquery
Multiple Subquery
Let us consider the following tables for examples :TABLE NAME (a) DEVELOPER (b) CAREERS (c) PRODUCT
SEX
SKILL1
Char(1)
Varchar2(20)
SKILL2
SALARY
Varchar2(20)
Number(8,2)
COURSE
FEES
Varchar2(30)
Number(8,2)
SOLD
Number(3)
Nested Subquery : If a Subquery is nested with another query that is Nested Subquery.
Example :If the user want to view the details of the programmer whos skill is VC++ and developed projects in VC++ and has experience of 5 yrs atleast then the following the query
SQL> Select * from developer where skill1 =VC++ or skill2=VC++ and name in(select name from product where environ=VC++ and name in(select name from developer where to_char(sysdate,yy)to_char(doj,yy)>=5));
Multiple Subquery : Example used for Nested query itself can be applied to Multiple subquery.
SQL>Select * from developer where skill1 =VC++ or skill2=VC++ and name in(select name from product where environ=VC++) and name in (select name from developer where to_char(sysdate,yy)-to_char(doj,yy)>=5);
Correlated Subquery : A subquery is evaluated once for the entire statement whereas a correlated subquery is evaluated once for every row processed by the parent statement. SQL> Select deptno,ename,sal from emp x where sal> (select avg(sal) from emp where x.deptno=deptno)
Operators Used in Subquery : Subqueries can also return more than one value. In such cases we should include operators like any,all,in or not in between the comparison operator and the subquery. SQL>Select * from emp where salary < any (Select salary from emp where ename in(Ram Kumar,Balaji )); In the above example the subquery returns the salary of Ram kumar and Balaji and the main query will display the details of the employees who are all drawing less than these two employees.
All Operator :SQL>Select * from emp where salary > all (Select salary from emp
Constraints To maintain security and integrity of a database is the most important factor in judging the success of a system. An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. The following are the various types of integrity constraints : Domain Integrity Constraints Entity Integrity Constraints
Domain Integrity Constraints : These constraints set a range, and any violations that take place will prevent the user from performing the manipulation that caused the breach. There are basically two types of domain integrity constraints.
Not Null Constraint Check Constraint
By default the tables can contain null values. The enforcement of Not Null constraints in a table ensures that the table contains values. Oracle will not validate the record until this is satisfied.
The other type of constraint available under this classification is the check constraint. This can be defined to allow only a particular range of values. When the demarcation specified in this range is violated Oracle rejects the record. Entity Integrity Constraint : Entity Integrity Constraints are two types.
Unique Constraints Primary Key Constraints
The Unique Constraint designates a column or a group of columns as a unique key. This constraint allows only unique values to be stored in the column oracle rejects
The Referential Integrity constraint enforces relationship between tables. It designates a column or combination of columns as a foreign key.
The foreign key establishes a relationship with a specified primary or unique key in another table, called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table.
Note:
Not Null integrity constraint can be define using alter table command even when the table has rows. Zero and Null are not equivalent. One null is not equivalent to another null.
Example : SQL> create table emp (eno number(3),ename varchar2(25) constraint nn not null ,salary number(8,2));
Check Constraint : This constraint is used to check the values in the column satisfies the condition, i.e the user can restrict the records to be inserted into the table with the help of check constraint. Example : SQL> create table test(no number(3),name varchar2(25) constraint nn Not Null,salary number(8,2)constraint chk_sal check(salary>=2500),phone number(8)); In the above table the user can insert records which satisfies the condition.
Unique Constraints : This constraint checks for the uniqueness of the record. If the user dont want to have any duplication of records at the time of insertion then the user can assign unique constraint for that column. How to add a constraint with the alter table statement SQL>alter table test add constraint uni unique phone number(8,2); The user can assign composite unique constraint also. If the user want to assign unique constraint for more than one column then the user can prefer composite unique constraint.
Example : SQL>Create table test (no number(3), name varchar2(25),salary number(8,2), phone number(8),E-Mail varchar2(25) unique(phone,e-mail)); Composite unique constraint can be assigned for more than one column.
Primary Key Constraint : Primary Key Constraint is a combination of Not Null and Unique Constraint, i.e., primary key column wont accept duplicated records and null value. A table can have only one primary key constraint and this constraint is mainly introduced to set relationship between tables.
If the user want to assign primary key constraint for more than one column than they can use composite primary key, the composite primary key can be assigned for 16 columns maximum.
Primary key constraint is assigned to a column with the keyword primary key.
Table Level Constraints & Column Level Constraints: The table level constraint is part of the table definition .
An integrity constraint defined at table level can impose rules on any columns in the table.
Column level constraint being a part of the column definition can be imposed only on the column level.
Example for a Table Level Constraint : SQL> Create table itemfile (itemcode varchar2(5), itemdesc varchar2(20),p_category varchar2(20), qty_hand number(5),re_level number(5), max_level number(5),itemrate number(9,2), constraint max check(max_level<500), constraint un_item unique(itemdesc));
Referential Integrity Constraints : To establish a parent - child or a master - detail relationship between two tables having a common column, we make use of referential integrity constraints. To implement this we should define the column in the parent table as a primary key and the same column in the child table as a foreign key referring to the corresponding parent entry. Example : SQL> Create table dept(deptno number(3) constraint pk1 primary key, deptname varchar2(30) constraint nn1 not null);
SQL>Create table emp (eno number(4) primary key, ename varchar2(35), designation varchar2(25),deptno number(3) constraint fk1 references dept(deptno),salary number(8,2));
Note: The referential integrity constraint does not use foreign key keyword to identify the columns that make up the foreign key. This is because the constraint is defined at column level. The foreign key is automatically enforced on the columns.
Like other constraints it is also possible to define the referential integrity constraint at table level.
Example : SQL> Alter table order_master add constraint fk_code foreign key (vencode) references vendor_master(vencode) on delete cascade; SQL>delete from vendor_master where vencode=v006; Deferrable Constraints When a constraint is made deferrable, oracle 8 leaves the checking until the transaction is committed. Each constraint has two additional attributes to support deferred checking of constraints.
Non deferrable initially immediate - this is the default Condition which need not be specified.
When a table is being accessed by different clients concurrently transactions being performed simultaneously can prove to be harmful at times. Oracle provides the locking facility, which can be performed explicitly. Another facility available to protect data is to partition the tables. Doing so will minimize the chance of complete data loss.
The need for locking can be clearly understood with this example. Consider the users from two different departments in ABC ENTERPRISES - sales and accounts, wish to access the same table i.e.., order_master. In such a case, the following situation may arise.
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 user in accounts will delete the row that user in sales has updated. To overcome this situation oracle incorporates a locking facility which permits or denies access to other users on a table or a certain rows in a table, when a user is still is in the process of operating on them.
Types of Locks Locks are the mechanisms used to prevent destructive interaction between users accessing the same resource simultaneously . A resource can be an entire table or a specific row in a table. Thus locks provide a
high degree of the data concurrency. Locks can be acquired at two different levels.
Row level lock (for specific rows)
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 rolled back. Row locks are acquired automatically by oracle as a result of insert, update, delete and select.. for update clause statement.
Share Lock
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. Example : SQL> lock table emp in share mode;
Note : Although a share update lock falls under the table level category, it is effective only for rows.
Exclusive Lock : Exclusive lock is the most restrictive of the table locks. When issued 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, whereas many user can place a share lock on the same
commit.
Nowait:Consider a user has locked a table without a nowait clause in the lock table format. 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 user
Initially locked the table issues a commit or rollback statement. This delay could be avoided by appending a nowait clause in the lock table command.
Example:SQL>lock table emp in exclusive mode nowait; Deadlock:A deadlock occurs when two users have a lock, each on separate object, and, they want to acquire a lock on the each others object. Oracle automatically detects the deadlock and solves the problem by one of the two transactions.
Partitions The additional feature in Oracle 8 is that the tables are partitioned. And stored in different locations as per requirement. A single logical table can be split can be split into a number of physically separate pieces based on ranges 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.
There is difference between a table, which has a single partition, and a table that has no partitions. A nonpartitioned table cannot be partitioned later. Each partition is stored in a different segment and has different physical attributes. Table partitions can be stored in different tablespaces. Oracle 8 provides partition independence. We can access and manipulate data in one partition even if some or all of the other partitions are unavailable. This is the major benefit. Storing the partitions in different table spaces has its advantages.
It reduces the possibility of data corruption in multiple partitions. Back up and recovery of each partition can be done independently.
Note: Partitioned tables cannot contain any columns with long or long raw datatypes, LOB datatypes (BLOB,CLOB or BFILE), or object types.
partition.
Inserting records into a partitioned table:The records are stored in the partitions of a table based on the partition key specified. The partition key specified in the insert statement is compared with partition bound defined when creating the partitioned table. Example :SQL>insert into emp values(101,Maya,Programmer,5000);
SQL>insert into emp values(101,Meera,Systems Analyst,9500); SQL>insert into emp values(101,Megha,Programmer,8000); SQL>insert into emp values(101,snegha,Senior Manager,8000); SQL>insert into emp values(101,sathya,Accountant,5000);
Maintaining Partitions :This section describes the various partition maintenance operations, including:
The MOVE PARTITION clause of the ALTER TABLE statement is used to move a partition from a most active tablespace to a different tablespace in order to balance I/O operations.
Assuming that a tablespace called student_data exists lets try to move a partition from the system tablespace into the student_data tablespace.
Adding Partitions :The ALTER TABLE ADD PARTITION statement is used to add a new partition after the existing last partition. Example :SQL> alter table emp add partition p3 values less than(15000);
Note:-
The SPLIT PARTITION clause can be used to split a partition into two.
This is useful when a partition becomes too large and causes backup, recovery or maintenance operations to consume a lot of long time. Example :SQL> alter table emp split partition p3 at(12000) into (partition p4, partition p5); The partition p3 in the table emp is split into partitions p4 and p5. Now p4 will contain records with salary 10,000 to 11,999 and p5 will contain the records from 12,000 to 14,999.
Dropping Partitions :To drop a partition the DROP PARTITION clause can be made use of the ALTER TABLE statement. Example:SQL> alter table emp drop partition p5;
Exchanging Table Partitions:Exchanging table partitions is used to convert a partitioned table to non- partitioned table and non partitioned table to partitioned table.
Criteria in Exchanging the Table Partitions: The structure of the tables should be same. The records in the table which the user want to exchange the partition should satisfy the partition condition.
Example :SQL> alter table emp exchange partition p2 with table emp1;
Views
A view is a tailored presentation of the data contained in one or more tables. A view takes the output of a query and treats it as a table; therefore, a view can be thought as stored query or a virtual table. We can use views in most places where a table can be used. The tables upon which a view is based are called base tables. Syntax for creating views Create [or replace][[no] [force]] view <view name> [column alias name] as <query>[with [check option] [read only] [constraint]];
Example SQL> Create view emp_view as select * from emp; Creating view with conditions SQL> Create or replace view emp_view as Select * from emp where name like M%;
where name=Maya;
SQL> Create or replace view emp_view as select * from emp with read only ;
The above command creates a view called emp_view and it wont allow the user to update that view. The user can just select the records they cannot perform any manipulations.
Creating view with Joins (view having more than one base table)
SQL> create view emp_dept_view(emp_no,emp_name, salary,dept_no,department_name) as select (e.eno,e.ename,e.salary,d.no,d.dname) from emp e,dept d where e.dno=d.dno; The above view has two base tables emp and dept if the user tries to update the view user will get an error message.
Synonym
A synonym is a database object, which is used as an alias for a table,view or sequence they are used to Simplify SQL Statements Hide the name and owner of an object Provide location transparency for remote objects of a distributed database
Public Synonyms are created by a Database Administrator to hide the identity of the base table and reduce the complexity of SQL statements. One such example of a public synonym is TAB, which we use for selecting the tables owned by the user. These public synonyms are owned by user group PUBLIC.
Example for Synonym SQL>Create Synonym e1 for emp; Granting Privileges to Synonym SQL>Grant all on e1 to Scott; The Scott user can do all DML manipulations such as insert,delete,update o the synonym in the same way that of the table but he cannot perform any DDL operations on Synonym except dropping the synonym. The synonym is just an alias of a table and all the manipulations on it actually affect the table.
Sequences A sequence is a database object, which ca generate unique, sequential integer values. It can be used automatically generate primary key or unique key values. A sequence can be either in an ascending or in descending order Syntax for creating a sequence Create sequence<sequence_name> [increment by n] [start with n] [maxvalue n] [minvalue n] [cycle/nocycle] [cache/nocache]
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 numbers 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 for descending and ascending sequences respectively
Cycle: Specifies that the sequence continues to generate values from the beginning after reaching either its max or min value. No Cycle: Specifies that the sequence cannot generate values from the beginning after reaching either its max or min value. The default value is no cycle. Cache: The CACHE option pre-allocates a set of sequence numbers and retains them in memory so that sequence numbers can be accessed faster. When the last of the sequence numbers in the cache has been used No Cache: The default value nocache, does not preallocate sequence numbers for faster access.
start with 1
maxvalue 10 minvalue 1 cycle cache 4;
SQL> Insert into emp (no,name) values(seq1.nextval,Gettha); To view the values SQL>Select seql.currval from dual; Alter Sequence The sequence can be altered when we want to perform the following:
Indexes
Indexes are optional structures associated with tables. We can create indexes explicitly to speed up SQL statement execution on a table. Similar to indexes in books that helps us to locate information faster, an oracle index provides a faster access path to table data. User can create index on a column or combination of column using CREATE INDEX command as follows.
Unique Indexes
Indexes can be unique or non - unique. Unique indexes guarantee that no two rows of a table have duplicate values in the columns that define the index. Non-unique indexes do not impose this restriction on the column values. Oracle enforces unique integrity constraints by automatically defining a unique index on the unique key. A unique index is created by using create unique index command as follows. SQL> create unique index ind1 on test(no);
Note : A unique index is automatically created when we create unique or primary key constraint. We cannot create index for a column which is already indexed. Composite Indexes :A composite index(also called a concatenated index) is a index created on multiple columns on a table. columns in a composite index can be in any order and need not be adjacent columns of the table.
Example : -
Index Organized Tables:SQL> create table indorg (vencode number(4) primary key, venname varchar2(20)) organization index; Note : Primary key is a must for creating index organized table.
Regular Table : 1. ROWID uniquely identifies a row; primary key can be optionally specified.
Organized Table : 1. Primary Key uniquely identifies the rows. Primary key must be specified. 2. No Implicit ROWID column, cannot have physical secondary indexes. 3. Primary key based access. 4. Full- index scan returns all rows in primary key order
COMMAND
remark
DEFINITION
Tells SQLPLUS that the words are to be treated as comments, not instructions. The heading separator identifies the single character tells SQLPLUS to split a title onto two or more lines. sets the top title for a each page of a report. sets the bottom title for each page of a report.
set headsep
ttitle btitle
Column
Break on
Set pagesize
Set newpage Spool
/**/
--
Marks the beginning of an inline comment within a SQL query. Treats everything from the mark to the end of the line a s a comment. Similar to remark.
Makes screen display stop between pages of display. Save the SQL query youre creating into the file of your choice.
Host
Edit
Abstract Datatype
Example :SQL> Create or replace type address_ty as object (street_no number(3), street_name varchar2(20), city varchar2(20), state varchar2(20)); The above syntax creates a type named as address_ty Implementing object type as a column object. SQL> Create table emp (eno number(3), ename varchar2(25),address address_ty, salary number(8,2));
Deleting records in Abstract Data types SQL> delete from emp e where e.address.street_no=10; Dropping object Types SQL > drop type address_ty; * ERROR at line 1:
ORA - 02303: cannot drop or replace a type with type or table dependents.
Since the type is used by the table and table is not dropped the user cannot drop the type. But oracle as a FORCE clause to drop the type even dependencies are there. SQL> drop type address_ty force; Indexing Abstract data type attributes SQL> create index streetnum on emp (address.street_no);
Varying Arrays :These help in storing repeating attributes of a record in a single row. Varray cannot be extended beyond the limit that was defined when the varray was created. Creating Varrays
Inserting records into Varrays :SQL > insert into order_detail values (o100,itemcode(i100,i101,i102,i103,i104), qty_ord(100,980,900,800,1000), qty_deld(100,900,800,700, 600)); Selecting the data from varray:SQL> select item_va from order_detail;
Nested Tables :Varying arrays are used to create collectors within the tables and data types. Varying arrays have a limited number of entries, whereas nested tables have no limit on the number of entries per row. A nested table is table within a table. A table is represented as a column within another table. Let us assume that the table contains a structure as shown below:
Column
Book_Id Book_Name Author_Name Publications Price
Type
Varchar2(15) Varchar2(30) Varchar2(30) Varchar2(30) Number(8,2)
For each book an unique id is maintained and that is Book_Id . For example ORA001 is Id assigned for oracle books. If the user uses the Varray there is a limitation to specify the maximum limit.
The user dont know how many books will be purchased so he cannot give the maximum limit. This drawback can be removed with the help of nested tables. Let us see how to create a nested table.
SQL> create type book_ty as object(book_name varchar2(30),author_name varchar2(30),publications varchar2(30),price number(8,2)); type is created. The book_ty contains a record for each book. To use this datatype as the basis for a nested table a new abstract data type has to be created and is as shown below.
Book_id is an ordinary column which is of varchar2 data type in the table book_details
Book_particulars is the nested table column in the table book_details. The user has to specify that the column is a nested table column by specifying nested table keyword
Inserting records into a nested table :SQL > insert into book_details values (&book_id,book(book_ty(&book_name,&author _name,&publications,&price)));
Uses of the keyword :Previous example is how to insert record into the table which consist of nested table column first time. If the user want to insert record only to the nested table not to the main table then user has to for the keyword. Assume that 3 books has purchased for oracle and the user has to insert the details of those books then Example :SQL > insert into the (select book_particulars from book_details where book_id=ORA001) values(book_ty(How-To Oracle8 ,John,BPB,500));
Selecting records from the nested table:SQL > select a.book_name,a.author_name from the(select book_particulars from book_details) a;
Updating the records in the nested table :SQL> update the (select book_particulars from book_details where book_code =ORA001) set price= 595 where book_name=How-To Oracle8; Uses of CAST and MULTISET keyword
If the user want to insert the same set of records in nested table then the user can go for CAST and MULTISET keyword.
For example in a library there will be more than one book of the same series the user has to maintain the details of all the books then.
Example :SQL > insert into the (select book_particulars from book_details where book_id=VB001) values(book_ty(Visual Basic 6 Programming Black Book ,Steven Holzner,dream tech Press,475)); Later on the same book has purchased that details has to be maintained.
Example :SQL > insert into book_details values (VB002 ,cast (multiset (select * from the (select book_particulars from book_details where book_id=VB001)) as book));
Introduction to PL/SQL
PL/SQL Stands for Procedural Language/SQL. PL/SQL extends SQL by adding control structures found in other procedural language. Advantages of PL/SQL Supports the declaration and manipulation of objects Allows the calling of external functions and procedures
Architecture of PL/SQL
The PL/SQL engine executes PL/SQL blocks. The PL/SQL engine executes only the procedural statements and sends the SQL statements to the SQL statement executor in the Oracle server. The PL/SQL engine can either reside in the Oracle server or on Oracle tools such as Oracle Forms 5, Reports 3. 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 as shown below:
EXCEPTION
handlers
END;
Before proceeding to learn about the above three parts, we need to have a brief idea on the character set and lexical units used in the PL/SQL block
PL/SQL text can contain groups of characters known as lexical units. The following are the lexical units:
Identifiers
Literals
Comments Delimiters (simple and compound symbols)
In the above example, total and salary * and ; := 0.90 ----------- identifiers ---------- simple symbols ---------- compound symbols ---------- numeric literals ----------- represents comment
Some of the simple symbols are +,-,*,/,=,<,>,% (attribute indicator) ;(statement terminator) and : (host variable indicator).
Attributes
Attributes allow us to refer datatypes and objects from the database. PL/SQL Variables and constants can have attributes. The following are the types of attributes by PL/SQL
%type
%rowtype
%Type: %type attribute is used when declaring that refer to the database columns. Consider the following example where a called vcode is declared to be of type vencode in the item table using %type attribute. Example:
declare
enum emp.eno%type;
where enum is the variable name, emp is the name of the table and eno is the name of the column.
%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 cursor.
In the following example, a record named vend_inf will have the same names and datatypes as the columns in the customer table. Example
Declare vend_inf vendor_master%rowtype; In the above example, vend_inf stores a row selected from the vendor_master table.
Logical Comparisons
PL/SQL supports the comparison of variables and constants in SQL and PL/SQL statements.
These comparisons, Boolean expressions, are often connected by logical operators AND,OR and NOT.
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
Conditional control
Sequence of statements can be executed based on a certain condition using the if statements, namely if then, if then else and if then elsif. The simplest form of an if statement is the if then statement . The syntax is
if condition then
sequence of statements; end if;
Begin
select ostatus into orderstatus from order_master where orderno=o001; if orderstatus =p then update order_master set odate= 01-jan-99where orderno=o001; Else update order_master set odate= 26-jan-99 where orderno=o001; end if;
End;
the output of the above command is, PL/SQL procedure successfully completed. Iterative control A sequence of statements can be executed any number of times using loop constructs. Loops can be classified into
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. Syntax for a simple loop is:
loop
--sequence of statements;
end loop;
Example
Declare a number:=100; Begin Loop a:=a+25; exit when a=250; End Loop; dbms_output.put_line(a); End;
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 beginning of the loop. If the condition evaluates to false, then the loop is bypassed and the control passes to the next statement.
loop
sequence_of_statements; end loop; Example SQL> declare i number:=0; j number:=0;
end loop;
dbms_output.put_line(The value of j is || j) end; The output of the above PL/SQL procedure is given below.
The value of j is 2550 PL/SQL procedure successfully completed. FOR Loop 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.
Begin
For I in Reverse 100..1 Loop DBMS_OUTPUT.PUT_LINE(I); End Loop; End;
Example
Begin
for i in 1..2
loop update order_master set ostatus =p where odate<sysdate; end loop; end;
Sequential Control:
The goto statement allows to branch label unconditionally. The label which is enclosed with angle brackets must precede an executable SQL, statement a PL/SQL block. When executed the goto statement transfers control to the labeled statement or block.
Example:
Declare qtyhand itemfile.qty_hand%type; relevel itemfile.re_level%type; Begin select qty_hand,re_level into qtyhand,relevel from itemfile where itemcode=i201; If qtyhand < relevel then goto updation; End If;
<< updation>> update itemfile set qty_hand=qty_hand +relevel where itemcode = i201; End;
Concept of Error Handling: Error condition in PL/SQL is termed as an exception, There are 2 types of exceptions They are: Predefined Exception User-defined Exception Predefined Exception An exception is raised implicitly when a PL/SQL program violates Oracle rule. The following are the predefined exceptions supported by PL/SQL
No_data_found
Zero_Divide
Cursor_already_open
Dup_val_on_index Login_denied Invalid _number
Invalid_Cursor
Program_error Storage_Error Too_many_rows
Example: declare qtyhand itemfile.qty_hand%type; relevel itemfile.re_level%type; begin select qty_hand,re_level into qtyhand,relevel from itemfile where itemcode=i100; Exception when no_data_found then dbms_output.put_line(such an item number not avaliable); End;
select qty_hand into qtyhand from itemfile where itemcode=i201; If qty_hand < 200 then raise lo_value; End If; Exception when lo_value then dbms_output.put_line(quantity not enough); End;
Cursor Management
Oracle allocates an area of memory known as context area for the processing of SQL statements. The context area contains information necessary to complete the processing, including the number of rows processed by the statement.
A cursor is a handle or pointer to the context area.The three types of cursors are
Explicit Cursor Implicit Cursor
An Explicit Cursor is one in which the cursor name is explicitly assigned to the select statement. An implicit cursor is used for all other SQL statements. Processing an explicit cursor involves 4 steps. Processing of an implicit cursor is taken care by PL/SQL. The declaration of the cursor is done in the declarative part of the block. A cursor variable is a reference type. A reference type is similar to a pointer. It can name different storage locations as the program runs.
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.
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
After processing the last row in the active set, the cursor is disabled with the help of the close command. The syntax is as follows. close <Cursor name>;
declare icode order_detail.itemcode%type; cursor a is select itemcode from order_detail where itemcode =i201; begin open a; Loop fetch a into icode; update itemfile set itemrate=22.05 where itemcode=icode; exit when a%NOTFOUND; End Loop;
dbms_output.put_line(table updated);
Close a;
End;
%Notfound
The attribute %notfound indicates fetch statement returns from the active set. If the last fetch fails to return a row,then %notfound evaluates to true,else it evaluates to false.
%Found The %found attribute is the logical opposite of %notfound. It evaluates to true if the last Fetch statement returns at least one record. %Rowcont The %rowcount attribute is used to return the number of rows fetched. Before the first fetch %rowcount is 0. When the fetch statement returns a row, then the number is incremented.
Example to illustrate %Rowcount declare cursor a is select * from order_detail where orderno=o001; myorder order_detail%rowtype; begin open a; loop
dbms_output.put_line(the cursor is yet o be opened); end if; open mycur; if mycur%isopen then dbms_output.put_line(the cursor is now opened); end if; close mycur; 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.
Example for %Notfound attribute (Implicit Cursor) begin delete from order_detail where orderno =o201; if sql%NOTFOUND then dbms_output.put_line(value not found); else dbms_output.put_line(value found and deleted); end if; end;
begin
select orderno into order_no from order_master where orderno=o001; if sql%ROWCOUNT > 0 then dbms_output.put_line(rows selected from table);
end;
Cursor For Loop
A cursor for loop can be used instead of explicit cursors to simplify coding. A cursor for loop implicitly opens a cursor, repeatedly fetches rows from the active set, and then, closes the cursor when all rows have been processed.
Example declare
cursor for_cur is select orderno from order_master where vencode = v002; cust_rec for_cur%rowtype; begin
for cust_rec in for_cur loop delete from order_detail where orderno=cust_rec.orderno; end loop;
Subprograms & Packages 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.
Procedures are usually used to perform any specific task and functions are used 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
<local declarations>; begin [executable statements] [exception] (exception handlers) end;
A procedure has two parts, namely, specification and body. The procedure specification begins with the procedure name or parameter list. The procedure body begins with the keyword is and ends with keyword end. It can also include declarative, executable and exceptional parts within the keyword end. Syntax to execute a procedure is given below. SQL> exec <proce_name>(parameters);
While declaring variables in the declarative part of the procedure body, we should not specify the width of the datatype, For example,
Example create or replace procedure items (orders varchar2)) is qtyhand number; relevel number; maxlevel number; begin select qty_hand,re_level, max_level into qtyhand,relevel,maxlevel from itemfile where itemcode=orders;
If qtyhand<relevel then update itemfile set qty_hand=relevel + qtyhand where itemcode=orders; else dbms_output.put_line(item level ok); end if; Exception when no_data_found then
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. Example for in parameter mode create or replace procedure orders(a in varchar2) is v_code varchar2(5);
o_stat char(1);
begin
if o_stat=p then
Out Parameter
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. Example create or replace procedure test(a in varchar2, b out number) is identity number;
begin
select qty_ord into identity from order_detail where orderno=a; if identity <450 then b:=100;
end if;
end; After compilation of the above program procedure is created.
declare
a varchar2(5); b number; begin test(o202,b); dbms_output.put_line(the value of b is || to_char(b)); end; The value of b is 100 is the output of the above program
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. Example create or replace procedure or_detail(orno in varchar2,b in out varchar2) is qtyord number; qtydeld number; code varchar2(5);
Begin
select qty_ord,qty_deld,itemcode into qtyord,qtydeld,code from order_detail where orderno=no; if qtydeld <qtyord then b:=code; end if; end; The output of the above program is procedure created. To execute the above procedure a block as shown below is written and executed.
end;
The output of the above program is
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;
Example
create or replace function items(it varchar2) return number is
args:=maxlevel;
return args; else args:=(qtyhand+relevel); return args; end if; end;
a varchar2(5);
b number; begin a:=&a; b:=items(a); dbms_output.put_line(the value returned is || b); end;
The output of the above program is Enter the value for b: i201 old 5: b:=&b;
new 5: b:=i201;
the value returned is 140
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
The procedures and cursors declared in the create package command is fully defined and implemented by the package body.
begin
(executable statements) end [body_name]
Example for Package Specification Create or replace package pack_me is procedure order_proc(orno varchar2); function order_fun(ornos varchar2) return varchar2; end pack_me; / The output of the above package on successful compilation is, package created
Function order_fun(ornos varchar2) return varchar2 is icode varchar2(5); ocode varchar2(5); qtyord number; qtydeld number; begin select qty_ord,qty_deld,itemcode,orderno into qtyord,qtydeld,icode,ocode from order_detail where orderno=ornos; if qtyord<qtydeld then return ocode; else return icode; end if;
end order_fun;
end pack_me;
The output of the above block of code when compiled is package body created. Calling packaged subprograms To reference the types, objects and subprograms declared in a package specification the following notation is used. Package-name.typename. Package-name.object-name. Package-name.subprogram-name.
To execute the above package SQL> exec pack_me.order_no(o001); The output of the above SQL command is
completed order
PL/SQL procedure successfully completed.
To execute the function that is given in the package a block of code is written as shown below,
Declare a varchar2(5); b varchar2(5); begin b:=pack_me.order_fun(0202); dbms_output.put_line(the value is || b); end; / The output of the above program is,
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 purposes. To generate data automatically. To enforce complex integrity constraints.(e.g. checking with sysdate, checking with data in another table). 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. 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 parts.
Parts of a triggers A database trigger has three parts, namely, a trigger statement, a trigger body and a trigger restriction. Trigger Statement A trigger statement specifies the DML statements like update,delete and insert and it fires the trigger body. It also specifies the table to which the trigger is associated.
Trigger Body
Trigger body 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 syntax for creating triggers. 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 Types of Triggers Before After
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 trigger statement. On the other hand, if AFTER is used, then, Oracle fires the trigger after executing the triggering statement.
Apart from above types of the Triggers one more type is there that is Instead of ,this, trigger can be applied only to views and not for tables and it can be defined only in Row-Level and not in Statement Level.
Example create or replace trigger orders before insert on order_detail for each row declare orno order_detail.orderno%type; begin
select orderno into orno from order_detail where qty_ord<qty_deld; if orno =o001 then raise_application_error(-20001,enter some other number); end if;
end;
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. Example using old and new variable create or replace trigger new_old_trig before update on itemfile for each row begin if :new.qty_hand<:old.qty_hand then raise_application_error(- 20001, QUNATITY ON HAND IS LESS); end if; end;
Instead of Triggers
In Oracle8 there is something new in the world of triggers. INSTEAD OF triggers. These are the 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,UPDATE,DELETE against any view which contained a join. There are few restrictions on INSTEAD OF triggers
They are available only at the row level and not at the statement level
Creating view with Joins create view ord_view as select order_master.order_no,order_master.ostatus, order_detail.qty_Deld,order_detail.qty_ord from order_master,order_detail where order_master.order_no=order_detail.order_no the above view is created with joins
Create or replace trigger order_mast_insert INSTEAD OF insert on ord_view referencing new as n for each row declare cursor ecur is select * from order_master where order_master.order_no = :n.orderno; cursor dcur is select * from order_detail where order_detail.order_no=:n.orderno; a ecur%rowtype; b dcur%rowtype;
begin
open ecur; open dcur;
fetch ecur into a; fetch dcur into b; if dcur%notfound then insert into order_master(orderno,o_status) values(:n.orderno,:n.o_status); else update order_master set order_master.o_status=:n.o_status where order_master.orderno=:n.orderno; end if;