Vous êtes sur la page 1sur 42

BT 22-01

ORACLE 8i AND DISTRIBUTED DATABASE

Q1:-What is oracle8i?Explain its features.

Ans:-Oracle 8i is an Object relational database system which


offers capabilities of both relational and object oriented
database system oracle 8i supports very large databases
that can contain 100 of terabytes of information. It also
provides access to many concurrent users through the
order of thousands or 10 thousands users. 8i supports
multithreaded server (MTS). The multithreaded server
and Net8 manage the concurrent users of the database.
Oracle 8i has an advanced queuing feature. The feature
allows the deferring of execution of database transaction.
Application can use the PL/SQL application-
programming interface (API) to queue transactions,
prioritize their execution, and set acceptable times for
transactions. Oracle 8i is up to ten times faster. Oracle 8i
provides ten-fold size improvement. It can support ten
times the amount of data.

Features of Oracle 8i:-

(i)Oracle 8i supports very large databases, which can


extend upto terabytes.
(ii) It provides access to many users without slowing
down the data access speed.
(iii)Oracle 8i is up to 10 times fasters than the traditional
oracle.
(iv) Oracle 8i provides a new utility named DB_VERIFY
which ensures the logical integrity of the data in an
Oracle 8i database. DB_VERIFY will diagnose problem
and recover. It in the event of database broken.
(v) Password management has been greatly improved
with in oracle 8i.It forces the user to select complex
password which cannot easily be opened by the potential
includes.
(vi) it supports password history maintains to prevent
from reusing the previous password.
(vii)Oracle 8i supports partitioning of tables. The tables
are divided on a partiontion key and are stored separately
but are access as a whole through partiontion
transparency.
(viii) It supports a new technology called parallel
propagation to achieve replicated data much more
quickly. Parallel propagation allows modified data on one
node/client to be propagated on many other nodes on the
network simultaneously.

Q2:- What is Data Definition Language? Explain the various


categories under it with examples.

Ans:- This component is used to defined and destroy object


like table and for granting and revoking permition on
such objects.
i.e. Create, Alter , Drop ,Grant, Revoke.

Table Definition:-
A table is a unit of storage, which holds data in the form
of rows and columns. The Data Definition used for table
definition can be classified into the following three
categories.
• Create table command
• Alter table command
• Drop table command

Create a Table:-
Create table<table name>(column definition 1, column
definition 2..);

In a table
• We should specify a unique column name.
• We should specify proper data type along with
its width.
• We can include ‘Not null’ condition when
needed; by default it is ‘Null’.

Alter a table:-
Alter table <table name>modify(column definition…);
Alter table <table name> add(column definition..);

Alter table commands cater to then need of the following


situations;
 When a user wants to add a new column.
 When a user wants to modify the existing column
definition to change the width of the data type or data type
itself.
 To include or drop integrity constraints.

Drop a table:-
To dropping a table
Drop table <table name>;

Truncate:-
This command is used to delete all the records from the
table.Command to truncate a table is Truncate
table<table name>;

Desc:-
It shows the view the structure of the table Desc help to
achieve the same. Command to view the table’s structure
is Desc <table name>

Q3:-Explain the feature of partitioning in tables using Oracle


8i with correct syntax and an example? Also explain its
advantages.

Ans:-The additional feature in oracle 8iis the tables can be


partitioned and stored in different locations as per
requirements. A single logical table can be spite into
many 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. Oracle 8i
provides transparency. The application doesn’t require
the knowledge that the table has been partitioned.
A partitioned table consists of a number of
pieces each having the same logical attributes. A
difference between a table, which has a single
partition, and a table that has no partitions. A non-
partitioned table cannot be later. Each partition is stored
in different segment and different physical attributes.
Table partitions can be stored in table spaces. Oracle 8i
also provided partition independence.

Advantages of partitions:-

Advantages of storing the partitions in different table


spaces:
 Reduce the possibility of data corruption in multiple
partitions.
 Make it possible to back up and recover each partition
independently.
 Make it possible to control the mapping of partitions to
disk drives.

Partitions can be altered, dropped, rebuilt, merged and


truncated. Partitions cannot have synonyms. Clustered
tables and their indexes nor indexes nor snapshots can be
partitioned.

Syntax of partitioning a table:-

SQL>create table<table name>(column name data


type,<column name>data type…)partition by
range(column name)(partition<partition name>values less
than<value>,partition<partition name> values less
than<value>;

The initial part of syntax is the same as in oracle 7.But


the keyword partition is given so at Oracle 8i recognizes
the column used to partition the table. The partitions
could be just two or more. The maximum value to be held
in a partition could also be specified. The placing of the
partitions into various table spaces must be specified.

The example shown below helps in understanding the


concept of partitioning tables.

Ex:-
SQL> create table Mite(empno number(7),empname
varchar2(20), empadd varchar2(30)) partition by range
(empname)(partition p1 values less than(‘h’),partition p2
value less than(‘m’));

Altering the partition:-


When a table is created with a partition it can be altered
to merge two partitions or a single can be split into two.
We can make use of the alter table add partition to
append a partition to a table. If a table is not partitioned
when it was created then the table cannot be partitioned
using the alter table command. The split partition clause
can be used to add a partition in the beginning of a table
or in the middle.
Example:-
SQL> alter table MITE add partition p3 values less than
(‘r’);
Partition can only be appended to the table. If the last
partition contained values that are less than the max
value then no other partition can be appended to the
table. In such a case the split partition option can be used
to insert a partition in the desired position.

A split partition gives us the option of splitting a partition


in the two. It gives the new partitions new physical
attributes and the older attributes are discarded.
Example:-
SQL> alter table MITE split partition p1 at (‘c’) into
(partition p1, partition p3));
The example shows us how a single partition can be split
into two the help of the split partition keyword. This gives
us two partitions i.e., p1 and p2. P1 contains values that
are less than c and the partition p3 contain values that
are less than h.
A partition name can be renamed using the rename
option. The rename option works as shown below:
Ex:-
SQL> alter table MITE rename partition p2 to p2;

The above statement shows us how we can rename the


partition.
A partition can be altered to delete all rows from it. To
delete all rows from a partition we can use the truncate
partition command along with the alter table command.
The following example helps in a better understanding of
the alter table command with the truncate option & shows
us how we can remove all rows in a partition using the
alter table command with the truncate option.
Ex:-
SQL>alter table MITE truncate partition p1;

Q4. What are Constraints? Explain different types of


constraints with an example for each.
Ans:- Constraints would be defined along with the columns in
a table to avoid invalid entries. For example, an
organization maintaining details regarding textbooks,
Purchases order and employee’s name wants to secure
these informations, they can enforce data integrity on the
related data objects.

Integrity Constraints:-
An integrity Constraint is a mechanism used by Oracle 8i
to prevent invalid data entry into the table. It is nothing
but enforcing rule for the columns in a table. The various
types of integrity constraints are explained below:

Domain integrity constraints


Maintain value according to the sections like ‘Not null’
condition, so that the user has to enter a value for the
column on which it is specified. ’Not null’ and ‘Check’
constraints fall under this category.

‘Not null’:-
We know that by default all columns in a table Null
values. When a ‘Not null’ constraint is enforced on a
columns or a set of columns in a table, It will not allow
Null values. ’Not Null’ integrity constraint can be defined
using alter table command ever when the table contains
rows. But the rows violating the constrain rule must be
sent exception Zero and Null are not equivalent.
SQL>create table IT(empno number(6) constraint eno Not
Null,
Empname varchar2(30));
Where eno is the constraint name. This command will
ensure that the user enters a value for the empno
column on the IT table, failing which it returns an error
message.

Check constraints:-
These are rules governed by logical expressions or Boolean
expressions. Check conditions can’t contain subquries.
The following example will help us to understand it much
better & creates a table IT_order with a check constraint
to restrict the values of ordid to be within 1000.
Example:-
SQL>create table IT_order (ordid number(4) constraint
checkit check (ordid>1000),orderdate date, commplan
character(l), custid number(6),shipdate , tatal
number(8,2));
Maintains uniqueness in a record:-
An entity is any data recorded in a database. Each entity
represents a table and each row of a table represents an
instance of that entity. This constraint is used to identity
each row in a table uniquely we need to use this
constraint.

Unique constraints:-
Usage of the unique key constraint is to prevent the
duplication of values within the rows of a specified column
or a set of columns in a table. Columns defined with this
constraint can also allow Null values. If unique key
constraint is defined in more than one column, It is said
to be composite unique key. In the above case
combination of columns can’t be duplicated. Maximum
combination of columns that’s composite unique key can
contain is 16.
Example:-
SQL>create table ITT(id number(6), stdprice
number(8,2),minprice number(8,2), startdate date,
enddate date constraint unidate unique);
The same constraint can be enforced using table level
syntax also

Example
SQL>create table IT(id number(6), stdprice number(8,2),
enddate date, startdate, constraint unitab
unique(enddate));
The above example prevents the duplication of values to
be entered in enddate column.

E.g.:-
SQL> create table MITE(empid number(6), empname
varchar2(30),
Constraint compuni unique(empid, empname));
In this case combination of columns custid and name
can’t be duplicated.
Primary key constraints:-
This constraint avoids duplication of rows does not Null
values, When enforced in a column or set of columns. As a
result it is used to identify a row. A table can have only
one primary key. Primary key constraint can’t be defined
in an alter table command when the table contains rows
having Null values.
Example:-
SQL> create table IT_customer (custid number(6)
constraint prim_con primary key, name varchar(45),
address varchar2(30), city char(30), repid
number(4),creditlimit number(8,2));

The above example are define the primary key on a single


column, so this is syntax for column level.

Example:-
SQL> create table ITT_item (item number(6), ordid
number(6),prodid number(6), actualprice number(8,2), qty
number(8,2), constraint prim_id
Primary key(itemid));
This constraint ensures that they don’t contain Null
values.

Referential integrity constraint:-

Enforces relations between tales One can either enable or


disable a constraint. The former enforces the
constraint and the latter will not enforce the rule, even
through the syntax would remain as it is in the data
dictionary. By default, the syntax would be enabled.
Further we can define a constraint either at table or
column level. If it is defined at the table level, then, it can
be enforced to any number of columns in a table. On the
other hand, if it is defined at the column level then, it
holds good only for the column for which it is defined.
Referential integrity constraints

Through the referential integrity constraints to establish a


‘parent-child’ or a ‘master-detail’ relationship between two
table 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.
E.g.:-
SQL>create table T_order (IT_order number(4), orderdate
date, commplan character(1), shipdate date, total
number(8,2), empid number(6), constraint fk_empid
foreign key(empid)references MITE(empid));

On delete cascade clause:-


If all the rows under the referenced key column in a
parent table are deleted, then all rows in the child table
with dependent foreign key column will also be deleted
automatically.

Basic concepts related to referential integrity are:


 Foreign key:- A column or combination of columns
included in the definition of referential integrity that would
refer to a referenced key.
 Referenced key:- It is a unique or a primary key, which is
defined on a column belonging to the parent table.
 Child table:- This table depends upon the values in the
referenced key of the parent table, which is referred, by a
foreign key.
 Parent table:- This table determines whether insertion or
updating of data can be done in child table. This table
would be referred by child’s table foreign key.

Example:-
SQL> create table IT_order (order number94), orderdate
date, commplan character(1), shipdate date, total
number(8,20, empid number(6) constraint fk_empid
references IT_customer(empid));
The above command creates a table IT_order and will
also enable a foreign key on empid column, which
would refer to the primary key on the empid foreign
key on
empid column, which would refer to the empid column of
the IT_customer table. Before enabling this constraint, we
ensure that empid column of the customer table has been
defined with either unique or primary key constraint. The
foreign key constraint ensures that all values in the
column empid in IT_order table have a corresponding
empid value in the IT_customer table.

The referential integrity constraint does not use foreign


key keyword to identify the columns that make up the
foreign key, because the constraint is defined at column
level on custid column, the foreign key is automatically
enforced on the custid column.

Example:-
SQL>create table IT_order (order number(4), orderdate
date, commplan character(1), ship_date date, tatal
number(8,2), empid number(6),
Constraint fk_empid references IT_customer(empid) on
delete cascade);

Foreign key keyword is an optional one and can be used


for a more understandable syntax and missing it doesn’t
cause any error. Because of the on-delete-cascade option
we find that deleting a particular empid value from the
IT_customer table, results in the deletion of the
corresponding rows from the order table also.

Referential integrity constraints with composite keys

A composite key can contain a maximum of 16 columns. It


must either refer to a composite unique key or a
composite key. To maintain referential integrity
constraints with foreign keys, each row in the child table
must satisfy one of the conditions mentioned below.

 The value of at least one of the columns, which make


up the foreign key, can be Null.
 The values of foreign key columns must match the
values of referenced key columns.
An option that could be used to set all constraints to
constraints to deferred or enable all constraints is
available and has the following syntax:

Set constraints all immediate;

This enables all constraint.

To disable all deferred;


Oracle 8i has an option to enforce a constraint rather
than enable it. Enforcement is applied to any future
inserts and updates, but does not care about data
already in the table. The syntax is the following:

Alter table <table name> enforce constraint <constraint


name>;

Q5. Explain the join concept and explain the different types of
joins.
Ans:- 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. The
syntax for joining tables is as follows:

Select columns from table1, tables where logical


expression;

The logical expression specifies how the tables are joined.


There are basically three different types of joins. They are:-
 Simple join
 Self join
 Outer join
 Simple join:-

It is 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, is called an equi-join.


Consider the following example.

SQL>select * from item, order_info where


item.ordid=order_info.ordid;
In the above statament , item.ordid=order info. Ordid
performs the join operation. It retrieves rows from both the
tables provide they both have the same ordid as specified
in the ‘where’ clause. Since the’where’clause uses
comparison operator equal to (=),to perform a join, it is
said to be an equi join.

Non equi-join:-

A non equi-join specifies the relational operators between


columns belonging to different tables by making use of the
relational operators (>,<,<=,>=,< >) other than=.

Example:-
SQL>select * from IT_customer,order_info where
IT_customer.custid>orde_info.custid and
IT_customer.repid=10;
The above example joins the rows of customer table to the
of order_info table provided custid’s belonging to customer
table are greater than custid’s belonging to order_info
table. Yet, it retrieves rows only when the second
expression.
i.e.,repid=10 is true.
Table aliases:-
Table aliases are used to make multiple table queries
shorter and more readable. As a result, we give an alias to
the table in the ‘from’ clause and use it instead of the
table name throughout the query. To prevent ambiguity in
a query we include table names in the select statements.
The following example is illustrative of the same.
E.g.,
SQL> select b.* ,o.*from IT_customer b.order_info o where
b.custid>o.custid and repid=10;
Where ‘o’ refers to order info table and ‘c’ refers to
customer table. The aliases, which are defined in, the
“from clauses is separated from the table name by spaces.
B.*,o.* will retrieve all columns from both tables provided
the conditions in the where clauses is satisfied.”

Self join:-
Joining of a table itself is known as a self join,i.e., it joins
one row in a table to another. It can compare each row of
the table to itself and also with other rows of the same
table.
Ex:-
SQL>select o.* from order_info 0,order_info u where
o.ship_date>=u.ord_date and o.custid=u.custid;
The above example will display only those rows from the
order_info table whose ship_date is greater than or equal
to the order_date provided they both have the ‘Ssame
custid’.

Outer join:-
The outer join extends the result of a simple join. An outer
join returns the rows returned by simple join as well as
those rows from one tables that do not match any row
from the other table. The symbol,(+), represents outer join.
Ex:-
SQL> select order_info.ordid,prodid,item_ordid form item,
order+info where order_info.ordid(+)=item Ordid;
The above example will retrieve rows from item table
which does not have any matching records in the
order_info table because of the presence of an outer join.

Q6. Explain View Database Object. Also explain the Partition


view And Object view with an example for each.

Ans:- A view is an imaginary table and it contains no data and


the tables upon which a view is based are called base
table. The advantages of views are as follows
 Table security: They provide table security by restricting
access to a predetermined set of rows or columns of a
table.
 Simplication of commands: They simplify commands for
the user because they allow them to select information
from multiple tables.
 Different perspective: They provide data in a different
perspective than that of a base table by renaming columns
without affecting the base table.
Syntax:-
Create view<view_name>[ column alias name…] as query
[with check option constraint]

E.g.SQL> create view emp1 (empnumber, name, salary,


deptnumber) as select empno,ename,sal,deptno from emp
where deptno=10 with check option;

In the above example, the view shows only employees


whose deptno is 10 Because of the check option we should
insert only those employee whose deptno is 10.

Function in view:-
Single row functions comprising number, chraracter, date,
group functions and express can also be used in views.
Consider the following example which illustrates the usage
expressions in a view.
E.x:
SQL>create view discount (quantity, ordid, price) as select
qty, ordid, actualprice/150 from item;
The above example finds the discount offered for a
product.

Partition View:-
The concept behind the partition views is entirely different
from that of the partition indexes. With partition views,
the data resides in separate tables. These tables are then
brought together at runtime using the relation operator
Union all. The syntax for a partition view given as
Create view<viewname> as
Select * from <tablename>
Union all
Select *from <tablename2>

Union all
Select * from <tablename3>;

Consider the following example,


Create * from sales as
Select * from <sales_94>
Union all
Select * from <sales95>
Union all
Select * from <sales96>
Union all
Select * from <sales97>;

Object View:-
Objects views allow the use relational data in object-
oriented applications. Hence we can define object views as
extensions of traditional relational views that allow us to
threat the relational date as object entities. Hence we can
select, insert, update and delete the relational data as if
they object entities.
Example:-
SQL> create table employees (eno integer primary key,
ename varchar2(25), add varchar2(25), street
varchar2(50), city varchar2(25), state varchar2(25), pin
varchar2(8), country varchar2(25));
To manipulate the above-created table, insert and update
statements are issued as follows:
Example:-
SQL> Insert into employees Values
(10,’shailza’,’sss’ ,’74NSK
salai’,Madras’,’Tamilnadu’,’600026’,’India’);

SQL> Update employees


Set street=’PostBox 123’ Where eno=10;
On the otherhand,an object-oriented database excepts the
manipulations tobe done using the two datatypes
emp_type and add-type.(The emp_type and add-type must
be created previously so as to include the fields
concerning the employee and his address respectively.

Q7. Explain sub queries and Multiple Sub queries with


example.
Ans:- Sub queries:- Nesting of queries, one within the other, is
termed as a subquery. A statement containing sub query
is called a parent statement. Sub queries are used to
retrieve data from tables, which depend on the value in
the table itself,

Example:-
SQL> select * from emp where deptno=(select deptno from
customer where sal=7500);

Sub queries that return several values


The above example used a sub query, which returned a
single value. Sub queries 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
sub query.

Example:-

SQL>select * from emp where deptno


deptno< any(select deptno from emp where sal<4000);
In the above example the subquery will display that
details of employee where the sal is less than 4000.

Multiple Subqueries:-
Oracle 8i places no limit on the number of queries include
in a where clause. Consider the following example, which
illustrates multiple queries.
Example:
SQL> select * from emp where sal=any(select sal from emp
where deptno<20) and deptno=any(select deptno from emp
where ename like ‘m%’);

A sub query itself can contain a sub query.

Ex:-
SQL>select * from emp where empno=(selct empno from
empwhere deptno=(select deptno from emp where
.sal<5000));

Correlated sub query:-

Sub query is evaluated once for the entire parent


statement whereas a correlated sub query evaluated once
per row processed by the parent statement. Consider the
following example, which returns rows for total, which are
greater than avg (total) with reference to ordid.
Ex:-
SQL>select ordid, orderdate, shipdate form order_info o
where shipdate<any (select orderdate from order_info
where 0.ordid=ordid);
Q8. Explain the Concept of Locking. Explain the types of locks
with reference to an example.
Ans:-The need for locking can be clearly understand with the
following discussion. Consider an organization where
multiples users want to access the same table say,
product. In such a case, the following situation may arise.

User1:-
Updates row 1 of product;
Commit;

User 2:-
Deletes row 1 of product;
Commit;

Since both the users are accessing the same row on the
same table at the same time it may end up in a situation
where user2 will delete the row that user 1 has updated.
To overcome this situation, Oracle 8i incorporates a
locking facility, which permits or denies access to other
users on a table or to certain rows in a table, when a user
is operating on them.

Types of locks:-
Locks are the mechanisms used to prevent destructive
between users accessing the same resource at the same
time. A resource can either be an entire table or a specific
row in a table. Thus provide a high degree of data
concurrency. Locks can be acquired at the 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. Rowlocks are
acquired automatically by Oracle 8i as a result of insert,
update, delete and select with for update clause
statement.

Select…for update clause:-

The select command when used with for clause of clause


places an exclusive lock on one or more updated later. The
following example locks the rows in which the value of
ordid is 200.
Example:-
SQL> select * from order_info where ordid –200 for update
of commplan_total;

The following update command corresponds to the above


example.

Example:
SQL> update order_info set commplan=’a’ where
ordid=200;

After updating the columns in the order_info table, other


users can perform other manipulations but can never
update the rows, which has been locked until the lock is
released. Meanwhile, other users can update other rows.

Table level lock:-


A table lock will protect table data thereby guaranteeing
data integrity when data is being accessed concurrently by
multiple users. A table can be held in several modes. They
are
 Share lock
 Share update lock
 Exclusive lock
Now let us discuss the locks one by one by one in order to
appreciate their performance. 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 user 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. The
following example locks table item in share mode.

SQL> lock table item in share mode;

 Share update lock


It locks 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 user form updating the same row, which has been
locked. One can enforce a share update lock by using
the ‘for’ update clause in the select statement. The
following example will lock the customer table in share
update mode.

Example:
SQL>lock table customer in share update mode;

NOTE:-

 Although a share update lock falls under the table


level category, it is effective only for rows.
 It allows many users to concurrently lock different
rows of a table.
 Exclusive lock
It is the most restrictive of 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 share lock but only one user can
place an exclusive lock on a table at a time, Where as
many users can place a share lock on the same table
at the same time.

Example:-
SQL>lock table price in exclusive mode;

Note:-
 Locks can be released by issuing either rollback
or commit.
No wait:-
If a user has locked a table without a ‘No wait’ clause in
the lock table format and if another user tries to violate
the above restrictions by trying to lock the table, then, he
will be made to wait indefinitely until the former issues a
commit or rollback statement. This delay could be avoided
by appending a ‘no wait’ clause in the lock table
command. The following example is illustrative of this
feature.

Example:-
SQL> lock table customer in exclusive mode nowait;

Deadlock:-
A deadlock occurs when two users have a lock, each on a
separate object, and, each wants to acquire a lock on the
other user’s object. When this happens, the first user has
to wait for the second user to release the lock, but the
second user will not release until the lock on the first
user’s object is freed. At this point, both the users are at
an impasse and cannot proceed with their business. In
such a case, Oracle 8i detects the deadlock automatically
and solves the problem by aborting one of the two
transactions.
The following tabular column clearly explains the mode of
functioning of the different discussed above.

User performs the following Lockmode Permitted by Another user


task
Share Shareupdate Exclusive
Establishing a share lock Yes No No
Establishing an share No Yes No
update lock
Establishing an exclusive No No No
lock
Querying a table Yes Yes Yes
BT 22-02
ORACLE 8i AND DISTRIBUTED DATABASE

1. Explain the following with an example:


(a) Column commands
(b) Compute commands
(c) Title commands

Ans:-
(a)Column commands:- SQL * PLUS uses column names
as default column headings while displaying query
results. We can display our own column heading with the
help of the following command

Column<col_name>heading<col_heading>;
The following example changes the column heading ‘qty’ to
‘quantity’.

Example:
SQL>column qty heading quantity,
SQL>select qty from it;

Note:
The new heading is effective until we exit from the current
SQL * Plus session.

Customizing column contents


When we display columns containing numeric values, we
can either accept the default SQL * Plus display format or
we can change it by issuing the following command.

Column<col_name> format model;


Consider the example, which displays total in the
following format.

Example:-
SQL>column total format $999,99;
SQL>Select total from ord.r_info;

(b)Compute commands:- To organize rows of report into


subsets and perform summation on group of rows, break
and compute commands are used. The break command
also suppresses duplicate values. The syntax is as follows.

Break on <break_column >skip n;

The following example inserts 2 blank lines between every


two different values of prodid.
Example:-
SQL> break on prodid skip 2;
SQL>select prodid from item;

To perform computations on the row in each subset we


use the ‘compute’ command. We can’t the ‘compute’
function without issuing a ‘break’ command.
Break on <col_name>
Compute function of column on break_column;

Title commands:-
Title commands compressing ‘ttitle’ and ‘btitle’ are used to
place top title and bottom title on each page. The
command is given below:
Ttitle position_clause char_value position_clause;
Btitle position_clause char_value position_clause;

To display ‘introduction’ and ‘conclusion’ at the top and


bottom, the following is used.

Example:-
SQL> ttitle center ‘introduction’;
SQL>btitle center ‘conclusion’;
SQL> select prodid from item;

To display at the top of the page like the one below,

INTRODUCTION
=============

PERSONAL REPORT SALESDEPARTMENT

2.Explain the various operators supported by by SQL*Plus.


Ans:- The following are the operators supported by SQL *
Plus:
 Arithmetic operators
 Comparison operators
 Logical operators

 Arithmetic operators:-
To perform calculations based the number values, we
include arithmetic expressions in SQL command. An
arithmetic expression consists of column names with
number data types and an arithmetic operator connecting
them. The arithmetic operators are

• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
Example:
SQL> select ordid, itemid, 100 * (actualprice + qty) from
IT_item Where prodid= 120;

In the above example, only after adding actual_price with


qty it is multiple by 100. It parenthesis is omitted then
multiplication will be performed first followed by addition.
Thus we can control the order of evaluation by using
parenthesis. We now move on to study about comparison
operators.
 Comparison operators
Comparison operators are used in conditions to compare
one expression with another. The comparison operators
are =,! =, <, >, <=, >=, between (to check between any two
values), in (to match with any of the values in the list), like
(to match a character pattern) and is Null (to check
whether it is Null).

The last four operators mentioned above can also be used


for checking the NOT conditions like NOT BETWEEN, b
and so on. The following example illustrates the
comparison operator “greater then”.

Example:
SQL>select * from EMP where sal>5000;

The above example displays the rows for which the sal is
greater than 5000.An example discussed below is used to
check for negations, (i.e. check for NOT conditions).

 Logical operators
A logical operator is used to combine the results of two
conditions to produce a single result.
The logical operators are

 AND
 NOT
 OR

And operator:-

Example:-
SQL> select * from emp where sal.4000 AND deptno<2;
And operator will display all the columns from EMP table
provided both the conditions mentioned below are
satisfied.

SQL*Plus supported by various operators:


The precedence of the operators
 Arithmetic operators ---------highest precedence
 Comparison operators
 Not logic operator
 AND logic operator
 OR logic operator-----------lowest precedence

3.Explain the Predefined exceptions and User-defined


exceptions in PL/SQL.
Ans:- Error condition in PL/SQL is termed as an
exception. They are two types of exceptions. They are:
 Predefined exceptions
 User-defined exceptions
An exception is raised when an error occurs. In that case,
normal execution stops and the control is immediately
transferred to the exception handling part of our PL/SQL
block. Predefined exceptions are raised automatically by
the system during runtime; whereas user defined
exceptions must be raised explicitly by using RAISE
statements.

 Predefined exceptions
The exception is raised implicitly when a PL/SQL program
violates Oracle 8i rule. The following are the predefined
exceptions supported by PL/SQL.

a) No_data_found:- This exception is raised when select


statement returns no rows.
b) Cursor_already_open:- This exception is raised when we
try to open a cursor, which is already opened.
c) Dup_val_on_index:-This exception is raised when we
insert duplicatevalues in a column, which is defined s
unique index.
d) Storage_error:- This exception is raised if PL/SQL runs
out of memory or if the memory is corrupted.
e) Program_error:- This exception is raised if PL/SQL has
an internal problem.
f) Zero_divide:- This exception is raised when we try to
divide a number by zero.
g) Invalid_cursor:-This exception is raised when we violate
cursor operation. For example, when we try to close a
cursor, which is not opened.
h) Login_denied:- This exception is raised when we try to
enter Oracle 8i using invalid user name & password.
i) Invalid_number:-This exception is raised if the
conversion of a character string to a number fails
because the string does not represent a valid number.
j) Too_many_rows:-Raised when the select into statement
returns more than one row.

Syntax for predefined exception is as follows:

Begin
Sequence_of_statements;

Exception

When <exception_name> then


Sequence_of_statements;
When others then /* the last exception in the
exception handler*/
sequence_of_statements;

end;

Example:-

Declare
Price item.actualprice%type;

Begin

Select actualprice into price from item


where qty=678;

exception

when no_data_found then


dbms_output.put_line(‘item missing’);

end;

 User-defined exception
A user-defined exception should be declared and raised
explicitly by a ‘raise’ statement. It can be declared only in
the declarative part of the PS/SQL block. The syntax is

<exception_name> exception;

The syntax for a ‘raise’ statement follows

raise<exception name>

The following is used to find out whether price per item is


zero or Null. Then it raises an exception named zero_price.

Example:-
Declare
Zero_price exception;
Price number(8,2);
Begin
Select actualprice into price item where ordid=400;
If price=0 or price is null then
Raise zero-price;
End if;

Exception
when zero-price then
Dbms_output.put_line(‘raised zero-price exception’);

End;

4. Explain elaborately about Cursors in PL/SQL with


examples.
Ans:- The Oracle 8i server to execute SQL statements rand
to store processed information uses a work area called
private SQL area. PL/SQL uses cursors to name the
private SQL area and ‘~’ access the stored information.
There are two types of cursors. They are:
 Explicit cursor
 Implicit cursor
A cursor can be declared in the declarative part of a
PL/SQL block, a subprogram or s package (which will be
dealt later).The syntax for declaring a cursor is as follows:

Cursor<cursor_name> is <select statement>;

Oracle 8i automatically opens a cursor for processing.


Cursors, when user-defined, can see off certain
limitations. Cursors can either be strong or weak
depending upon the way it is declared.

PL/SQL programs use a special database utility called the


DBMS-SQL package. This utility has a lot of in-built
procedures and functions. When a SQL statement has to
be executed dynamically the program calls in-built
functions and procedures of DBMS-SQL package. The
program opens a cursor for this dynamic SQL sttement to
get executed.

 Explicit Cursor
The set of rows returned by a query can contain zero or
multiple rows depending upon the query defined. These
rows are called active set. The cursor will point to the
current row in the active set.
After declaring a cursor, we can use the following
commands to controls 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 given below

Open< cursor_name>;

‘Fetch’ statement retrieves the current row and advances


the cursor to the next row to fetch the remaining rows.
Syntax for ‘fetch’ is as given below:

<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>;

Explicit cursor attributes when appended to the cursor


name allow us to access useful mation from the retrieved
rows. They are:-
• %notfound
• %found
• %rowcount
• %isopen

Notfound:-
After opening a cursor, a ‘fetch’ statement is used to fetch
rows from the active set, one at a time.
The attribute %notfound indicates whether fetch
statement returns row from the Active set. If the last
‘fetch’ fails to return a row, then %notfound evaluates to
true, else, it evaluates to false.

%found:-
The %found attributes is the logical opposite of
%notfound. It evaluates to true if the ‘fetch’ statement
succeeds. It would be evaluated to false if the last ‘fetch’
command fails because no more rows were available.

%Rowcount:-
The %rowcount attribute is returning the number of rows
fetched. Before the first fetch%rowcount is zero. When the
‘fetch’ statement returns a row, then the number is
incremented.

%Isopen:-
If the cursor is already open, then the attribute %isopen
evaluates to true, else it evaluates to false.

Cursor For Loop:-


A ‘cursor for’ loop can be used instead of explicit cursors
to simplify coding. A cursor for loop’ implicit opens a
cursor, repeatedly fetches rows from the active set; and
then, closes the cursor when all rows have been
processed. The syntax the ‘cursor for loop’ is as follow:

For<record_name> in <cursor_name> loop


Sequence_of_statements;
End loop;

 Implicit cursor
PL/SQL implicit declares cursors for all SQL data
manipulation statements, including queries that return
one row.
Implicit cursor attributes can be used to access
information about the most recently executed SQL
statement. The most recently executed SQL statement is
referred as ‘SQLCURSOR’.

The implicit cursor attributes are:


• %notfound
• %found
• %rowcount
• %isopen

%Notfound:-
%notfound attribute evaluates to true if DML statements
do not return any row, else it evaluates to false.

%Found:-
The %found attribute is the logical opposite of the
%notfound. The %found attribute is evaluated to true if
the SQL DML statement affects one or more rows, else it is
evaluated to false.

%Rowcount:-
The %rowcount attributes count the number of rows
returned by an SQL DML statement. Be %rowcount will
return zero if the DML statement does not affect any row.

%Isopen:-
Oracle 8i closes the cursor automatically after executing
its associated SQL statement. As a result, %isopen is
always evaluated to false.

5.What is Trigger? Give the syntax for a Trigger and explain


its parts. Also explain the types of triggers.
Ans:- A database trigger is a stored procedure that is fired
when an insert, update or delete statement is issued
against the associated table. Database trigger can’t be
used for the following purposes.

• To generate data automatically.


• To enforce complex integrity constraints.
• To customize complex security
authorizations.
• To maintain replicate tables.
• To audit data modifications.

Syntax for creating triggers:-


The syntax for creating a trigger is given below.

Create or replace Trigger <Trigger_name> 1 [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 trigger:-

A database trigger has three parts, namely, a trigger


statement, a trigger body and a trigger restriction.

Trigger statement :-

The trigger statement specifies the DML statements like


update, delete and insert and it fires the trigger body. It
also specifies the table to which the trigger is associated.

Trigger body:-
It is a PL/SQL block that is executed when a triggering
statement is issued.

Trigger Restriction:-

Restrictions on a trigger can be achieved using the WHEN


clause as shown in the above syntax. They can be
included in the definition of a row trigger, wherein, the
condition in the WHEN clause is evaluated for each row
that is affected by the trigger.

Note:-
A sub query can’t be included in the WHEN clause.

Types of Triggers:-

Triggers are categorized based on when are fired.

• Before
• After
• For each row
• For each statement (default)

Before/after Options
The before/after options can be used to specify when the
body should be fired with respect to the triggering
statement. If the user includes a before option, then,
Oracle 8i fires the trigger before executing the triggering
statement. On the other hand, If AFTER is used, then,
Oracle 8i fires the trigger after executing the triggering
statement.

For Each Row/Statement


The for each row/statement option when included in the
‘create trigger’ syntax specifies that the fires once per row.
By default, a database trigger fires for each statement.
Using a combination of the above options, we can assign
12 triggers to a database table. Only one trigger of each
type (discussed below) can be assigned to a table:-
• Before update row/statement
• Before delete row/ statement
• Before insert row/statement
• After update row/ statement
• After delete row/ statement
• After insert row/ statement
In general, each table can have four triggers (before/after/
statement /row) on statements (insert/ update/ delete).
Thus, we can assign twelve to a single table.

Note:-

We already know about DBMS_STANDARD, which provide


the language facility’ interact with Oracle 8i. This package
provides a procedure named raise_application_error to
issue user-defined error messages. The syntax is given
below.

Raise_application_error (error_number, ‘error_message’);

The error_number ranges from –20000 …-20999 and the


error_massage can be a character string.

Example:-

Create or replace trigger trig


Before insert on item for each row
Declare
Item.ident Item.Itemid%ytpe;
Begin
Select Itemid into Item.Ident from item where qty=4543;
If Item.Ident=1000 then
Raise_application_error (-20001, ‘enter some other
number’);
Endif;
End;

This example also illustrates the ‘BEFORE ROW’ trigger.


Oracle 8i fires this trigger before adding each row by using
the insert statement.
Oracle 8i fires it once before executing the trigger. There
are two variables namely, :old and :new which retain the
old and new values of the Ited in the database. The values
in these variables can be used in database manipulation
for Triggers.

Enabling and disabling triggers:-


A trigger can be either enabled or disabled. An enabled
trigger executes the trigger body if: the triggering
statement is issued. By default, triggers are enabled. A
disabled trigger does not execute the trigger body even if
the triggering statement is issued.
Syntax:-
Alter trigger <Trigger_name> disable;

Example:-
SQL> alter trigger trig disable;

To disable all the triggers associated with the table, we


can issue the following syntax.

SQL> alter table <table_name> disable all triggers;

If we can enable the trigger.


SQL>alter table <table_name> enable all triggers;

Dropping the triggers: -


To drop a trigger from the database, the drop trigger
command is used. The syntax follows.
Drop trigger <trigger_name>;

6.Explain with diagrams the various types of storage


structures.
Ans:- Database are stored almost invariably on disks, which
are slower than main memory and the DBMS thus has an
objective to minimize the number of disk accesses (disk i/o
‘s) when executing updates/retrievals.
A storage is defined as a\n arrangement
of data. Many can be devised, each with different
performance characteristics. No single storage structure is
optimal for all applications, but a good DBMS should many
different types of storage structures, so that different
portions of the database can be stored in different ways, and
the storage structure for a given portion can be changed as
performance requirements change or become better
understood.

Types of storage structures: -


Many different and varying types of storage structures exist.
These vary considered in their arrangement of the data from
one to the other; however there are some fairly standard
principles of database access which identify what is involved
in the overall process of locating and accessing particular
records. We define several commonly occurring storage
structures as following.

 Indexing:- An indexing storage structure is a storage


structure consisting of two separate files, an index file
and a data file. The index is basically a special kind of
stored file- it is a file which each entry (i.e. record)
consists of precisely two values, a data value and a
pointer; where the data value is a value for some field of
the indexed file, and the pointer identifies a record of
that file that has a value a value for that field. An index
on primary key field is called a primary key index; an
index on any other field is called a secondary index.

Tree structures:-
The notion of tree-structured or multi-level indices is
usually used for large indices. The reason for providing
an index in the first place is to remove the need for
physical sequential scanning of the indexed file.
However, physical sequential scanning is still needed in
the index. If the indexed file is very large, then the
index also can get quite sizeable and therefore scanning
the index may itself get quite time consuming.

 Hashing storage structure:-


The storage structure of hash addressing is a type of
storage structure, which exists at the internal level and
which provides fast, direct access to records based on a
given value for some field. Each record is physically
placed at a location whose address is some function of
some field of that record i.e. at the ‘hash address’. When
storing, the DBMS computes the hash address and then
informs the file manager where to store it.

Disadvantages of hashing:-

The technique of hashing as a storage structure has


several disadvantages .The physical of records within the
stored file will almost certainly not be the primary key
sequence, nor any other logically interpretable sequence,
and thus a hashed file usually does not have intra-file
clustering.

 Pointer chains storage structure:-


The pointer chains storage structure is a type of storage
structure which exists at the internal level and which
involves two separate files, a ‘parent’ file and a ‘child’ file,
with the overall structure being an example of the
‘parent/child organization’.

Advantages of pointer chains:-


The principle advantage of the pointer chain structure is
that the insertion/deletion algorithms are somewhat
simpler, and possibly more efficient, than the
corresponding algorithms for indexing. Also, the
structure will probably occupy less storage than the
corresponding index structure, because each parent
value appears only once instead of multiple times.

Disadvantages of pointer chains:-


The principal disadvantages of the pointer chain storage
structure are firstly that the structure is suitable for one
type of query only and may be a hindrance for others.
 Compression techniques
Compression techniques are used in combination with
storage structures for reducing the amount of storage
required for a collection of data.
Compression techniques are designed to exploit the
fact that data values are never completely random, but
display a considerable amount of predictability e.g an
alphabetically sorted list.

There are three different types of compression techniques.

 Different compression:-Differential compression is a


commonly used where each individual value is replaced
by some representation of the difference between it and
the value that immediately precedes it.
Different types of differential compression exist, one
known as front compression, another rear compression.

Front compression:-
Front compression is a differential compression technique
for compressing data by which characters at the front
each entry is the same as those in the previous entry are
by a corresponding count.

Rear compression:-
The rear compression technique is a which by data is
compressed, first by eliminating all trailing spaces, and
then by dropping all characters to the right of the one
required t distinguish the entry in question from it’s two
immediate neighbours. Second indicating the number of
characters recorded.

 Huffman compression technique


Huffman coding is a character encoding technique for
compressing data, however it is not used much in current
systems. Basically, the idea involves replacing characters
by bit string in such a way that different characters are
represented by strings of different length with the most
commonly occurring characters being represents by the
shortest strings.

 Hierarchic compression technique


The hierarchic compression technique is generally a
suitable technique where a given stored file is physically
sequenced (i.e. clustered) by values of some stored field ‘F’,
and also each distinct values of ‘F’ occurs in several
(consecutive) records of that file. Hierarchic compression
of the kind illustrated is only feasible if intra-file clustering
is in effect.

Vous aimerez peut-être aussi