Professional Documents
Culture Documents
If the user want to insert rows for few columns and not to
all the columns in the table means the syntax is
Delete Command : -
Commit Command : -
After performing any DML Commands user has to
give the commit statement.
SQL> Commit;
Rollback Command:
SQL>Rollback;
Savepoint command:
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.
Select Command to Create a Table
The user can also create a table and copy the
records into it with a single statement, by
including a ‘select’ clause in a create table
command. The syntax is given below
create table <tablename> as select
column_name from <existing_table_name>;
Example :
SQL> Create table employee_details as select *
from emp;
SQL> select * from employee_details;
The above command displays all the details of
the table employee_details which is a copy of
the table emp.
If the user want to copy the structure of the
table then
SQL> Create table emp_details
(employee_id,employee_name) as select
(eno,ename) from employee_details
where 1 = 2;
Select Command to Insert Records:
Syntax to insert records to a table with the help of
Select command is
Insert into <table_name> (Column_Name) (select
column_names from <existing_table_name>);
Example
SQL> insert into
emp_details(employee_id,employee_name) (select
eno,ename from emp where salary>15000);
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
Not Between, like, Not Like, is Null, is Not Null.
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
Operator Precedence: -
Arithmetic Operators highest
Comparison Operators
Not Logical Operator
And Logical Operator
Or Logical Operator Lowest
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
SQL>Select * from emp order by ename desc;
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 employee’s details who
draw the same salary then
SQL>Select * from emp
where salary in(select salary from emp group by
salary having count(salary)>1);
Functions
Single Row Functions
Group 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
SQL> Select sysdate ,add_months(Sysdate,2) from
dual;
Last_Day
The format of is last_day(d), which returns the
date corresponding to the last day of the month.
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.
SQL> select new_time(‘13-Feb-99’,’est’,’yst’)
from dual;
It returns 12-Feb-99 which is the date in the
time zone ‘yst’
Numeric Functions : -
ABS (value) -------------->ABSolute Value
CIEL (value) ------------>Smallest integer larger
than or equal to value
COS (value) ------------> COSine Value
COSH (value) --------->Hypeblic COSine of value
EXP (value) ------------>Value Raised to the
EXPonent
To_char() : -
Format of this function is To_char(d[,fmt])
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
28th of February 2000 if the sysdate is
‘28-Feb-00’;
In the above example fill mode (fm) format mask
is used to avoid blank padding of characters and
zero padding to numeric.
To_date ()
The format is to_date(char [,fmt]). This converts
char or varchar2 datatype to date datatype.
Format model, fmt specifies the form of character.
Consider the following example which returns date
for the string ‘January 23 2000’.
SQL> select to_date(‘January 23 2000’,’month-
dd-yyyy’) from dual;
‘23-jan-00’ will be the output.
To_number() : -
The to_number function allows the conversion of
string containing numbers into the number
datatype on which arithmetic operations can be
performed. This is largely unnecessary as oracle
does an implicit conversion of numbers contained
in a string.
SQL>Select to_number(‘100’) from dual;
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 login’s 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;
Th output of the above query is ‘4’.
So far we have discussed functions classified as
single row functions. These provided the result
based on individual rows.
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
sum of a range of values of a record set.
Example :-
SQL>Select sum(salary) from emp where dno=10;
Count Function :-
In order to count the number of rows, count
function is used. It can take 3 different arguments .
Count (*) :-
It counts all rows, inclusive of duplicates and
Nulls.
SQL>Select count(*) from emp;
The above query returns the number of records in
the table emp inclusive of null values.
Count(Col_name):-
It counts the number of values present in the
column excluding Null values.
SQL>Select count (dob) from emp;
Count(distinct col_name) : -
It is similar to count(col_name) but eliminates
duplicate values while counting.
SQL>Select distinct(count( dob )) from emp;
The above query returns the number of records in
dob column eliminating the duplicated records.
Set Operators & Joins
Set Operators : -
1. Union 2. Union All
3. Intersect 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
corresponding columns must be of same data type.
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:-
Implementation of Constraints :-
Domain Integrity - ‘Not Null’ Constraint
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 don’t 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
won’t 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.
To alter an existing table for adding a referential
integrity constraint
SQL> alter table emp add constraint fk1 foreign
key(deptno)references dept(deptno);
On Delete Cascade Clause: -
The ‘On Delete Cascade’ clause specifies that
oracle maintains referential integrity by automatically
removing foreign key values if a referenced primary key
value is removed. The syntax for creating a table to
include this clause is
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.
It may be deferrable or not deferrable
The initial state may be set to initially deferred or
initially immediate.
The three conditions, which can be set, are
Deferrable initially immediate - this checks for
constraint violation at the time of insert.
Deferrable initially deferred - this checks for
constraint violation at the time of commit.
Non deferrable initially immediate - this is the
default Condition which need not be specified.
The syntax for setting the condition is
alter table <tablename> add constraint <constraintname>
foreign key<columnname> references <tablename>
deferrable initially deferred.
The above syntax when used will add a constraint which
will by default only be checked at commit time.
The following statement enables all constraints
set constraints all immediate;
the next command is used to disable all constraints.
Set constraint all deferred;
To Drop a Constraint Syntax is
alter table <table_name> drop constraint
<constraint_name>;
LOCKS & TABLE PARTITIONS
Sales Accounts
updates row1 of order_master; deletes row1 of
commit; order_master;
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 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)
Table level lock (for entire table)
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.
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. The following example locks
rows in which the employees salary between 5000 to
15000.
Example : -
SQL> select * from emp where salary between 5000 and
15000 for update of name,designation;
Table level lock
A table level lock will protect table data there by
guaranteeing data integrity when data is being accessed
concurrently by multiple users. A table lock can be held
in several modes they are
Share Lock
Share Update Lock
Exclusive Lock
The general syntax for locking a table is given below:
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.
Example : -
SQL> lock table emp in share mode;
Share update lock
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 row that has been locked.
We can enforce a share update lock by using the ‘for
update’ clause in the select statement.
Example:-
SQL>lock table emp in share update mode;
Note :-
Although a share update lock falls under the table
level category, it is effective only for rows.
It allows numerous users to concurrently lock
different rows of a table.
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
table at the same time.
Example :-
SQL>lock table emp in exclusive mode;
Note :-
Locks can be released by issuing either rollback or
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 other’s 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 non-
partitioned 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.
Example to create a partitioned table :
SQL> Create table emp(empno number(3) primary key,
empname varchar2(25),designation
varchar2(30),salary number(8,2))partition by
range(salary)(partition p1 values less than(5000),
partition p2 values less than(10000));
In the above example table emp is created with
partition, and the table is partitioned on the column
salary. The data’s are stored in two partitions. Based
on the records the data’s are splitted and stored. In the
above example from 0 to 4999 the records are stored in
partition p1 and from 5000 to 9999 it is stored in p2
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);
SQL>insert into emp
values(‘101’,’VijayKumar’,’Clerk’,4500);
To view the records in partition table
SQL> Select * from emp partition(p1);
SQL> Select * from emp partition(p2);
Maintaining Partitions :-
This section describes the various partition
maintenance operations, including:
Moving Partitions
Adding Partitions
Dropping Partitions
Splitting Partitions
Exchanging Table Partitions
Moving Partitions:-
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
let’s try to move a partition from the system tablespace
into the student_data tablespace.
Example :-
SQL> alter table emp move partition p1 tablespace
student_data;
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 add partition option shown above is only for
tables where the last existing partition has been defined
with a specific key value.
If we wish to add a partition at the beginning or in
the middle of a table, or if the partition bound on the
highest partition is MAXVALUE, we should use the
SPLIT PARTITION statement.
Splitting Partitions :-
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%’;
Updating the records in a view
SQL> Update emp_view set name =‘Geetha’
where name=‘Maya’;
Creating view with check option
SQL> Create or replace view emp_view as
select * from emp where name like ‘R%’
with check option constraint empv;
The above command creates a view called emp_view
which consists of records where employee name starts
with character ‘R’. Now the user tries to update a record
in the view by changing the name of employee Ram to
Sam.
SQL> Update view emp_view set ename=‘Sam’
where ename=‘Ram’;
For the above command oracle displays an error stating
view WITH CHECK OPTION where -clause violation.
Creating view with Read Only Option :-
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 won’t allow the user to update that view. The
user can just select the records they cannot perform any
manipulations.
Creating view with functions
SQL> Create or replace view
emp_view(name,designation,salary) as select
name,designation,salary from emp where dno=10;
Creating view by Force
Oracle by default creates a view for the existing table
and valid column names. If the user want to create a
view for a table which does not exists or invalid column
name then with the help of force option the user can
create the view.
SQL>Drop table emp;
SQL>Create force view emp_view as select * from emp;
for the above command the user displays
view created with compilation errors.
After creating the emp table the user can compile the
view and use the view.
SQL> alter view emp_view compile;
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
Provide public access to an object
Synonym can be either private or public.
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.
Syntax for Creating a Synonym
Create [public] synonym <Synonym name> for
<tablename>
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.
Example for creating sequence:
SQL>Create sequence seq1 increment by 1
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:
Example:
Total :=salary * 0.90; -- to compute total
In the above example,
total and salary ---------- identifiers
* and ; ---------- simple symbols
:= ---------- compound symbols
0.90 ---------- numeric literals
-- ----------- represents comment
Some of the simple symbols are
+,-,*,/,=,<,>,% (attribute indicator)
;(statement terminator) and : (host variable indicator).
The compound symbols consist of two characters like
< >,!=,:=(assignment), || (concatenation),
-- (single line comment), ** ( exponentiation),
/* */ (multi line comment),<<>>(label delimiter)
Datatypes Used in PL/SQL
Boolean
Binary_integer ( used to store signed integer)
Number (Dec/decimal, Int/integer/Real)
Varchar2 (4000 bytes), char(2000 bytes) Long
(32,760 bytes)
Raw (types are used to store binary data)
Rowid
Composite Types (Collections and objects can be
used in PL/SQL)
LOB Types (BLOB, CLOB, BFILE)
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.
The advantages of using %Type is,
We need not know the exact type of the column
If the database definition is changed, then the data
type of the variable 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
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;
Example
Declare
orderstatus order_master.ostatus%type;
Begin
select ostatus into orderstatus from
order_master where orderno=‘o001’;
if orderstatus =‘p’ then
update order_master set odate=
‘01-jan-99’where 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.
Syntax for a while loop
while <condition>
loop
sequence_of_statements;
end loop;
Example
SQL> declare
i number:=0;
j number:=0;
Begin
while i<=100 loop
j:=j+i;
I:=I+2;
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.
The syntax is given below.
For counter in ,[REVERSE] lower bound ..Upper bound
loop
sequence_of_statements
end loop;
Example
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 Invalid_Cursor
Dup_val_on_index Program_error
Login_denied Storage_Error
Invalid _number 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;
User defined Exception
declare
lo_value exception;
qty_hand itemfile.qty_hand%type;
begin
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
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’ 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 as follows.
close <Cursor name>;
Example for an Explicit Cursor:
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;
Attributes in Explicit & Implicit Cursor
%notfound
%found
%rowcount
%isopen
%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.
Example for a %notfound Attribute
Declare
order_no order_detail.orderno%type;
cursor a is select orderno from order_detail
where orderno=‘o001’;
Begin
Open a;
Loop
Fetch a into order_no;
Update order_master set del_date=
sysdate where orderno=order_no;
Exit When a%NOTFOUND; End
Loop; Close a;
End;
%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
fetch a into myorder;
exit when %Notfound;
dbms_output.put_line(‘fetched’ || a%rowcount || ‘ from
table’);
Example to illustrate %Isopen
declare
cursor mycur is select * from order_master;
begin
if not mycur%isopen then
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;
Example for %Rowcount attribute (Implicit Cursor)
declare
order_no order_master.orderno%type;
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’);
else
dbms_output.put_line(‘ no rows selected from
table’);
end if;
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.
The syntax for the ‘cursor for’ loop is as follows.