You are on page 1of 38

EXPERIMENT NO:1

AIM:To Study Mapping of EER schema to Relational Model

THEORY:
Step 1: Mapping of Regular Entity Types
For each regular entity type, create a relation R that includes all the simple attributes of E
Called entity relations
Each tuple represents an entity instance
Step 2: Mapping of Weak Entity Types
For each weak entity type, create a relation R and include all simple attributes of the entity
type as attributes of R
Include primary key attribute of owner as foreign key attributes of R
Step 3: Mapping of Binary 1:1 Relationship
Types
For each binary 1:1 relationship type
• Identify relations that correspond to entity types participating in R
Possible approaches:
• Foreign key approach
• Merged relationship approach
• Crossreference or relationship relation
Step 4: Mapping of Binary 1:N Relationship
Types
For each regular binary 1:N relationship type
• Identify relation that represents participating entity type at N-side of relationship type
• Include primary key of other entity type as foreign key in S
• Include simple attributes of 1:N relationship type as attributes of
Alternative approach
• Use the relationship relation (cross-reference) option as in the third option for binary 1:1
relationships
Step 5: Mapping of Binary M:N Relationship
Types
For each binary M:N relationship type
• Create a new relation S
• Include primary key of participating entity types as foreign key attributes in S
• Include any simple attributes of M:N relationship type
Step 6: Mapping of Multivalued Attributes
For each multivalued attribute
• Create a new relation
• Primary key of R is the combination of A and K
• If the multivalued attribute is composite, include its simple components
Step 7: Mapping of N-ary Relationship
Types
For each n-ary relationship type R
• Create a new relation S to represent R
• Include primary keys of participating entity types as foreign keys
• Include any simple attributes as attributes
CONCLUSION:
The concepts of mapping a given EER diagram into Relational model was successfully studied and
implemented.
EXPERIMENT:2
Aim: To study Views,Joins and triggers in SQL

Theory:

Joins:
An SQL join clause combines records from two or more tables in a database. It creates a set that
can be saved as a table . A JOIN is a means for combining fields from two tables by using values common
to each. SQL specifies four types of JOIN: INNER, OUTER, LEFT, and RIGHT. A table can JOIN to
itself in a self-join.

Considering the following example we will explain all th joins:


CREATE TABLE department
(
DepartmentID INT,
DepartmentName VARCHAR(20)
);

CREATE TABLE employee


(
LastName VARCHAR(20),
DepartmentID INT
);

Employee table :
LastName DepartmentID
Rafferty 31
Jones 33
Steinberg 33
Robinson 34
Smith 34
John NULL

Department table:
DepartmentID DepartmentName
31 Sales
33 Engineering
34 Clerical
35 Marketing

Inner Join:
The INNER JOIN keyword return rows when there is at least one match in both tables.The
query compares each row of A with each row of B to find all pairs of rows which satisfy the join-
predicate. When the join-predicate is satisfied, column values for each matched pair of rows of A and B
are combined into a result row. The result of the join can be defined as the outcome of first taking the
Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every
record in table B)—then return all records which satisfy the join predicate.
For ex: SELECT *
FROM employee
INNER JOIN department ON employee.DepartmentID = department.DepartmentID;

OUTPUT:
Employee.LastName Employee.DepartmentID Department.Dep Department.DepartmentID
Robinson 34 Clerical 34
Jones 33 Engineering 33
Smith 34 Clerical 34
Steinberg 33 Engineering 33
Rafferty 31 Sales 31

Equi-join:
An equi-join is a specific type of comparator-based join, that uses only equality comparisons in
the join-predicate.

SELECT *
FROM employee
JOIN department ON employee.DepartmentID = department.DepartmentID;

Natural join:
A natural join is a type of equi-join where the join predicate arises implicitly by comparing
all columns in both tables that have the same column-names in the joined tables. The resulting joined
table contains only one column for each pair of equally named columns.

SELECT *
FROM employee
NATURAL JOIN department;

O/P:
DepartmentID Employee.LastName Department.DepartmentName
34 Smith Clerical
33 Jones Engineering
34 Robinson Clerical
33 Steinberg Engineering
31 Rafferty Sales

Outer join:
An outer join does not require each record in the two joined tables to have a matching record.
The joined table retains each record—even if no other matching record exists. Outer joins subdivide
further into left outer joins, right outer joins, and full outer joins, depending on which table's rows are
retained (left, right, or both).

Left outer join:


The result of a left outer join (or simply left join) for table A and B always contains all
records of the "left" table (A), even if the join-condition does not find any matching record in the "right"
table (B). This means that if the ON clause matches 0 (zero) records in B (for a given record in A), the
join will still return a row in the result (for that record)—but with NULL in each column from B. A left
outer join returns all the values from an inner join plus all values in the left table that do not match to the
right table

SELECT *
FROM employee
LEFT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;
LastName DepartmentID Department.Department NameDepartment.DepartmentID
Jones 33 Engineering 33
Rafferty 31 Sales 31
Robinson 34 Clerical 34
Smith 34 Clerical 34
John NULL NULL NULL
Steinberg 33 Engineering 33

Right outer join:


A right outer join (or right join) closely resembles a left outer join, except with the
treatment of the tables reversed. Every row from the "right" table (B) will appear in the joined table at
least once. If no matching row from the "left" table (A) exists, NULL will appear in columns from A for
those records that have no match in B.

SELECT *
FROM employee
RIGHT OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;

LastName DepartmentID Department.DepartmentName Department.DepartmentID


Smith 34 Clerical 34
Jones 33 Engineering 33
Robinson 34 Clerical 34
Steinberg 33 Engineering 33
Rafferty 31 Sales 31
NULL NULL Marketing 35

Full outer join:


A full outer join combines the effect of applying both left and right outer joins. Where
records in the FULL OUTER JOINed tables do not match, the result set will have NULL values for every
column of the table that lacks a matching row. For those records that do match, a single row will be
produced in the result set (containing fields populated from both tables).

SELECT *
FROM employee
FULL OUTER JOIN department ON employee.DepartmentID = department.DepartmentID;

LastName DepartmentID Department.DepartmentName Department.DepartmentID


Smith 34 Clerical 34
Jones 33 Engineering 33
Robinson 34 Clerical 34
John NULL NULL NULL
Steinberg 33 Engineering 33
Rafferty 31 Sales 31
NULL NULL Marketing 35

Self-join:
A self-join is joining a table to itself.

Employee Table:
EmployeeID LastName Country DepartmentID
123 Rafferty Australia 31
124 Jones Australia 33
145 Steinberg Australia 33
201 Robinson United States 34
305 Smith Germany 34
306 John Germany NULL

An example solution query could be as follows:

SELECT F.EmployeeID, F.LastName, S.EmployeeID, S.LastName, F.Country


FROM Employee F
INNER JOIN Employee S ON F.Country = S.Country
WHERE F.EmployeeID < S.EmployeeID
ORDER BY F.EmployeeID, S.EmployeeID;

Which results in the following table being generated.


Employee Table after Self-join by Country

EmployeeID LastName EmployeeID LastName Country


123 Rafferty 124 Jones Australia
123 Rafferty 145 Steinberg Australia
124 Jones 145 Steinberg Australia
305 Smith 306 John Germany

VIEWS:
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.

Creating a VIEW

The syntax for creating a VIEW is:

CREATE VIEW view_name AS


SELECT columns
FROM table
WHERE predicates;
For Example

CREATE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and suppliers.supplier_name = 'IBM';

This would create a virtual table based on the result set of the select statement. You can now query the
view as follows:

SELECT *
FROM sup_orders;

Updating a VIEW

You can update a VIEW without dropping it by using the following syntax:

CREATE OR REPLACE VIEW view_name AS


SELECT columns
FROM table
WHERE predicates;
For Example

CREATE or REPLACE VIEW sup_orders AS


SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and suppliers.supplier_name = 'Microsoft';

Dropping a VIEW

The syntax for dropping a VIEW is:

DROP VIEW view_name;


For Example

DROP VIEW sup_orders;

Triggers:
Triggers are a special kind of Stored Procedure that executes automatically when a user tries to
modify a database. Triggers are built for SELECT, UPDATE, INSERT and DELETE statements;
whenever a user tries to executes these queries to perform a transaction, triggers stop him and keep our
database secure

Create Trigger Trigger_Name


on dbo.table_name
AFTER INSERT
AS
BEGIN
PRINT 'INSERTION IS NOT ALLOWED !! '
ROLLBACK TRANSACTION
end

For example if we don't want our user to update data in the database we would follow up with this trigger:

create Trigger updateTrigger


on dbo.tableName
AFTER UPDATE
AS
BEGIN
PRINT 'UPDATION IS NOT ALLOWED'
ROLLBACK TRANSACTION
END

To prevent deletion:

create Trigger Delete_Trigger


on dbo.tableName
AFTER DELETE
AS
BEGIN
PRINT 'DELETION IS NOT ALLOWED'
ROLLBACK TRANSACTION
END

Practical performed in lab


JOINS..
Q. TO PERFORM INNER JOIN

Q.TO PERFORM LEFT OUTER JOIN.


Q.TO PERFORM RIGHT OUTER JOIN.

Q.TO PERFORM FULL OUTER JOIN.

Q.TO DISPLAY ALL INSTRUCTOR WITH THEIR RESPECTIVE COURSE ID


Query : To perform nested loop join

select stid ,stname,c.cid cname


from (select * from student where class='D12') as a1 join course as c
on a1.cid=c.cid

VIEWS AND TRIGGER


Query 1: To create a view which displays the name and id of instructor along with the
number of courses taught by the person.

Create view work as


selectID,name,no_courses=(select count(*) from teaches t where instructor.id=t.ID)
from instructor

select *from work

Query 2: Attempt to delete a tuple ..given a tuple value.

delete from stud where ID=c111


Query 3: To drop a view

drop view stud

Triggers
create trigger Message on Author

after insert, update, delete

as

begin

print 'You have inserted or modified or deleted Author table'

end

insert into Author

values(4,'Def','Cast Away')

update Author

set b_title='Two States'

where id='2'
Conclusion: Thus we have studied and implemented joins,triggers and
views successfully.
EXPERIMENT:3

AIM: To study Horizontal fragmentation ,Vertical Fragmentation and Mixed Fragmentation.

THEORY:

Data fragmentation allows you to break a single object into two or more segments, or fragments. The
object might be a user’s database, a system database, or a table. Each fragment can be stored at any site
over a computer network.

Horizontal Fragmentation:

A horizontal fragment of a relation is a subset of the tuples in that relation. The tuples that belong to the
horizontal fragment are specified by a condition on one or more attributes of the relation. Often, only a
single attribute is involved. Horizontal fragmentation divides a relation "horizontally" by grouping rows to
create subsets of tuples, where each subset has a certain logical meaning. These fragments can then be
assigned to different sites in the distributed system. Derived horizontal fragmentation applies the
partitioning of a primary relation, which are related to the primary via a foreign key. This way, related
data between the primary and the secondary relations gets fragmented in the same way. Each horizontal
fragment on a relation R can be specified by a sCi(R) operation in the relational algebra. A set of
horizontal fragments whose conditions C1, C2, ..., Cn include all the tuples in R—that is, every tuple in R
satisfies (C1 OR C2 OR ... OR Cn)—is called a complete horizontal fragmentation of R. In many cases a
complete horizontal fragmentation is also disjoint; that is, no tuple in R satisfies (Ci AND Cj) for any i j.

Vertical Fragmentation
Each site may not need all the attributes of a relation, which would indicate the need for a different type
of fragmentation. Vertical fragmentation divides a relation "vertically" by columns. A vertical fragment of
a relation keeps only certain attributes of the relation. The vertical fragmentation is not quite proper
because, if the two fragments are stored separately, we cannot put the original employee tuples back
together, since there is no common attribute between the two fragments. It is necessary to include the
primary key or some candidate key attribute in every vertical fragment so that the full relation can be
reconstructed from the fragments. A vertical fragment on a relation R can be specified by a pLi (R)
operation in the relational algebra. A set of vertical fragments whose projection lists L1, L2, ..., Ln include
all the attributes in R but share only the primary key attribute of R is called a complete vertical
fragmentation of R

Mixed Fragmentation :

We can inter mix the two types of fragmentation, yielding a mixed fragmentation. For example, we may
combine the horizontal and vertical fragmentations of the EMPLOYEE relation given earlier into a
mixed fragmentation that includes six fragments. In this case the original relation can be reconstructed
by applying UNION and OUTER UNION (or OUTER JOIN) operations in the appropriate order. In general, a
fragment of a relation R can be specified by a SELECT-PROJECT combination of operations pL(sC(R)). If C
= TRUE (that is, all tuples are selected) and L ATTRS(R), we get a vertical fragment, and if C TRUE and L =
ATTRS(R), we get a horizontal fragment. Finally, if C TRUE and L ATTRS(R), we get a mixed fragment.
Notice that a relation can itself be considered a fragment with C = TRUE and L = ATTRS(R).

CONCLUSION :

Studied horizontal vertical and hybrid fragmentation.


HORIZONTAL FRAGMENTATION

SELECT * into b1
from book
where copies_sold>40
select * into b2
from book
where copies_sold<=40

2.select * into a1
from author
where a_id<3
select * into a2
from author
where a_id>=3

Derived horizontal fragmentation

Q. Find number of copies sold my author martin.


Q.TO find the number of copies sold by author Korth

VERTICAL FRAGMENTATION
1.Select author_name,b_title into Au1
From author

2. select a_id,b_title into a3


from author
select author_name, b_title into a4
from author
Mixed fragmentation

select id,b_title from Author


where id<='3'

EXPERIMENT NO:4

AIM: - To implement complex queries in SQL

Theory: -
Some queries require that existing values in database to be fetched and then used in a comparison condition. Such
queries can be formulated using complex nested techniques. These queries are known as complex queries. Complex
queries are nested but nested queries may or may not be complex. Complex queries can be combination of one or
more nested queries. Complex queries are often hard or impossible to write as a single block or a
union/intersection/difference of SQL blocks. We study two ways of composing multiple SQL blocks to express a
complex query: derived relations and with clause.

 Derived Relations

SQL allows a sub query expression to be used in the from clause. If we use such an expression, then we must give the
result relation a name, and we can rename attributes. We do this renaming using as clause. This sub query generates
a relation consisting of the names of all branches and their corresponding average account balances. The sub query
result is named branch_avg with attributes branch_name and avg_balance. To illustrate the use of a sub query
expression in the from clause, consider the query shown in example no.1.

 With clause

Complex queries are much easier to write and understand if we structure them by breaking them into smaller views
that we then combine, just as we structure programs by breaking them into procedures. The with clause provides a
way of defining a temporary view whose definition is available only to the query in which the with clause occurs.
Consider example no. 2 which selects accounts with maximum balance, if there are many accounts with same
maximum balance, all of them are selected.

There are many techniques for writing complex queries. Some of them are given below

 Using exists clause

The exists clause in SQL is used to check whether the result of a correlated nested query is empty or not. The result
of exists is a Boolean value true or false. (Refer example no. 3)

 Using aggregate functions

Complex queries can be written using aggregate functions like count, avg, min, max.
Refer example no. 2 and 3 where we have used max and avg functions of SQL.

avg(balance) -
This function is used to calculate average of the integer amount “balance”.

min(balance) –
This function is used to calculate minimum amount from an integer parameter balance.
max(balance) –
This function is used to calculate minimum amount from an integer parameter balance.
count() –
This aggregate function is used to count number of tuples in a particular relation.

Group by or having clause or both can be used with these aggregate functions.
For example,
group by att_name will group the resulting table according to that attribute name.
having count(e_id)>2 will display those tuples which have e_id greater than 2.

 IN operator in SQL –

The IN operator allows you to specify multiple values in a WHERE clause.


Refer example no. 4 for the use of IN operator.

 BETWEEN operator in SQL –

The BETWEEN operator selects a range of data between two values. The values can be numbers, text, or dates.
Refer example no. 5 for the use BETWEEN operator.
 ALL operator in SQL –

For a row in a sub query with >ALL to satisfy the condition specified in the outer query, the value in
the column introducing the sub query must be greater than each value in the list of values returned by
the sub query.
Refer example no. 6 for the use of ALL operator.

 ANY operator in SQL –

>ANY means that for a row to satisfy the condition specified in the outer query, the value in the
column that introduces the sub query must be greater than at least one of the values in the list of
values returned by the sub query.
Refer example no. 7 for the use of ANY operator.

 EXCEPT operator in SQL –

The except operation automatically eliminates duplicates. If we want to retain all duplicates, we must write except
all in place of except. Refer example no. 8 for except operator.

CONCLUSION: -

Thus, we seen and understood the structure and different operators used in order to write complex query. We
have implemented complex queries successfully.

CODE AND OUTPUT :

Example no. 1

“Find the average account balance of those branches where average account balance is
greater than 1200”

Ans.

select branch_name,avg_balance
from (select branch_name,avg(balance)
from account
group by branch_name)as branch_avg(branch_name,avg_balance)
where avg_balance > 1200

Example no.2

“Fi nd an account number having maximum balance using with


clause”

Ans.

with max_balance(value) as(


select MAX(balance) from account
)
select acno
from account,max_balance
where account.balance = max_balance.value
Example no. 3

“To find employee first and last name which is present in dependent table”

Ans.

select e.fname,e.lname
from employee as e
where exists( select * from dependent_emp where e.ssn=Essn and sex='Male')

Example no. 4

“Find an account number from depositor which is also there in borrower”

Ans.

select * from depositor where acno in (select acno from borrower)


Example no. 5

“Find all the details of the employee having last name between “Gala” and “Naik””
Ans.

select * from employee where lname between 'Gala' and 'Naik'

Example no. 6

“Find the account details of account/accounts having balance <12000”

Ans.

select * from account where balance > all(select balance from account where
balance<12000)
Example no. 7

“Find the details of the account having balance > 15000 using ANY operator”

Ans.

select * from account where balance > any(select balance from account where
balance>15000)

Example no. 8

“Find all the customers who have an account but no loan at the bank”

Ans.
(select acno from depositor)except(select acno from borrower)

EXPERIMENT :5

AIM:To implement connectivity between frontend( VB 6.0 )with backend (Microsoft SQL Server)

PROCEDURE:
Perform the above two steps for remaining text boxes also

Now run the form

CONCLUSION:

Thus we have learnt how to establish connectivity between


frontend(VB 6.0) and backend (Microsoft SQL Server) with successful
implementation.
EXPERIMENT:6

Aim: To implement Abstract Data Type in Oracle

Theory:

An object-oriented database must provide support for all data types not just the built in data types such
as character, integer, and float. To understand abstract data types lets take two steps back by taking off
the abstract and then the data from abstract data type. We now have a type, a type would be defined as a
collection of a type values. A simple example of this is the Integer type, it consists of values 0, 1, 2, 3, etc.
If we add the word data back in we would define data type as a type and the set of operations that will
manipulate the type. If we expand off our integer example, a data type would be an integer variable, an
integer variable is a member of the integer data type. Addition, subtraction, and multiplication are
examples of operations that can be performed on the integer data type.

If we now add the word abstract back in we can define an abstract data type (ADT) as a data type, that is
a type and the set of operations that will manipulate the type. The set of operations are only defined by
their inputs and outputs. The ADT does not specify how the data type will be implemented, all of the
ADT’s details are hidden from the user of the ADT. This process of hiding the details is called
encapsulation. If we extend the example for the integer data type to an abstract data type, the operations
might be delete an integer, add an integer, print an integer, and check to see if a certain integer exists.
Notice that we do not care how the operation will be done but simply how do invoke the operation.

The ability to create new data types when needed and then use these data types is called data abstraction, and
the new data types are called abstract data types (ADTs).

Examples
1. To define a new datatype to store a person's address

CREATE OR REPLACE TYPE persons_address AS OBJECT (


streetNumber NUMBER,
streetName VARCHAR2(30),
citySuburb VARCHAR2(30),
state VARCHAR2(4),
postCode NUMBER
);

2. Define a employee_type; define a "raise_sal" member function; and create a table based on our new type:

CREATE TYPE employee_t AS OBJECT (


name VARCHAR2(30),
ssn VARCHAR2(11),
salary NUMBER,
MEMBER FUNCTION raise_sal RETURN NUMBER)
/

CREATE TYPE BODY employee_t AS


MEMBER FUNCTION raise_sal RETURN NUMBER IS
BEGIN
RETURN salary * 1.1;
END;
END;
/

-- Test the memer function


SELECT employee_t('Frank', '12345', 1000).raise_sal() from dual;

-- Create table based on employee_t


CREATE TABLE emp2 OF employee_t;
INSERT INTO emp2 VALUES ( employee_t('Frank', '12345', 1000) );
SELECT x.raise_sal() FROM emp2 x;

Conclusion:
Thus Abstract Data Type in Oracle was studied and implemented successfully.

Oracle Code and Output

Oracle Code and Output


SQL> CREATE OR REPLACE TYPE ADDRTYPE AS OBJECT
2 ( PINCODE NUMBER,
3 STREET VARCHAR2(10),
4 CITY VARCHAR2(10),
5 STATE VARCHAR2(10));
6/

Type created.

SQL> CREATE OR REPLACE TYPE AUTHORTYPE AS OBJECT


2 (NAME VARCHAR2(10),
3 ADDRESS ADDRTYPE);
4/

Type created.

SQL> CREATE TABLE AUTHORS OF AUTHORTYPE;

Table created.

SQL> INSERT INTO AUTHORS VALUES


2 ('NAVATHE',ADDRTYPE(4321,'MANPADA','PANVEL','MH'));

1 row created.

SQL> INSERT INTO AUTHORS VALUES


2 ('SANGHOI',ADDRTYPE(3245,'LBSMARG','DADAR','TN'));

1 row created.

SQL> SELECT * FROM AUTHORS;

NAME
----------
ADDRESS(PINCODE, STREET, CITY, STATE)
--------------------------------------------------------------------------
SUJATA
ADDRTYPE(400020, 'CST', 'MUMBAI', 'MAH')

NAVATHE
ADDRTYPE(4321, 'MANPADA', 'PANVEL', 'MH')

SANGHOI
ADDRTYPE(3245, 'LBSMARG', 'DADAR', 'TN')

SQL> DESC AUTHORS;


Name
Null? Type
----------------------------------------- -------- ----------------------
NAME
VARCHAR2(10)
ADDRESS
ADDRTYPE

SQL> DESC ADDRTYPE;


Name
Null? Type
----------------------------------------- -------- ----------------------
PINCODE
NUMBER
STREET
VARCHAR2(10)
CITY
VARCHAR2(10)
STATE
VARCHAR2(10)
SQL> set desc depth 2;
SQL> desc authors;
Name
Null? Type
----------------------------------------- -------- ----------------------------
NAME
VARCHAR2(10)
ADDRESS
ADDRTYPE
PINCODE
NUMBER
STREET
VARCHAR2(10)
CITY
VARCHAR2(10)
STATE
VARCHAR2(10)

Retrive city & state from author table?

SQL> select z.address.city from authors z ;

ADDRESS.CI
----------
MUMBAI
PANVEL
DADAR

SQL> select z.address.city,z.address.state from authors z;

ADDRESS.CI ADDRESS.ST
---------- ----------
MUMBAI MAH
PANVEL MH
DADAR
TN
Q)Change the city value for authors who lives in Mumbai to Delhi?

SQL> update authors a


2 set a.address.city='delhi'
3 where name='sujata';

0 rows updated.

SQL> update authors a


2 set a.address.city='delhi'
3 where a.address.state='MAH';

1 row updated.

Q)Delete the record for the authors who lives in Mumbai.

SQL> delete from authors a


2 where a.address.city='DADAR';

1 row deleted.

SQL> select * from authors;


NAME
----------
ADDRESS(PINCODE, STREET, CITY, STATE)
----------------------------------------------------------
SUJATA
ADDRTYPE(400020, 'CST', 'delhi', 'MAH')

NAVATHE
ADDRTYPE(4321, 'MANPADA', 'PANVEL', 'MH')

Q) Drop type Address_ty.

SQL> drop type addrtype;


drop type addrtype
*
ERROR at line 1:

ORA-02303: cannot drop or replace a type with type or table dependents

SQL> drop type addrtype FORCE;

Type dropped.
EXPERIMENT NO:7

AIM: To Implement Varray In Oracle

THEORY:
 VARRAY stands for variable-size array. It is an array that can be either manipulated as a
whole or individually as elements.
 It has a maximum size and can contain 0 to any number of
elements up to the maximum specified.
 VARRAY is stored in-line. That means the data of a column of VARRAY type is stored along
with the remaining data of the row.
 You can use VARRAY data type for:
A column in a relational table
A PL/SQL variable
A PL/SQL parameter of procedure or function
A PL/SQL function return type
A data attribute of an object type

SYNTAX:

CREATE TYPE array_name AS VARRAY (limit)


OF data_type
Array_name is the name of the VARRAY data type.
Limit is the maximum number of elements that the array can have
Data_type is the type of each element of the array. It can be any standard type or
object type.

Example:
First create an object type called PROJECT_TYPE to store the name of a project and the role
played by the employee in that project.
create type project_type as object
(
name varchar2(50),
role varchar2(20)
);
Create a VARRAY that can contain up to 5 elements of PROJECT_TYPE.
create type projectlist as VARRAY(5) of project_Type;

CONCLUSION:
Varrays in oracle was successfully studied and implemented

ORACLE CODE:

Create a table with VARRAY column:


CREATE OR REPLACE TYPE vcarray AS VARRAY(10) OF VARCHAR2(128);
CREATE TABLE varray_table (id number, col1 vcarray);
INSERT INTO varray_table VALUES (1, vcarray('A'));
INSERT INTO varray_table VALUES (2, vcarray('B', 'C'));
INSERT INTO varray_table VALUES (3, vcarray('D', 'E', 'F'));
Commit;
SELECT t1.id, t2.column_value
FROM varray_table t1, TABLE(t1.col1) t2;

OUTPUT:
EXPERIMENT: 8
AIM: To implement Nested Tables in Oracle

THEORY:

 An ordered group of items of type TABLE are called nested tables. Nested tables can contain multiple
columns and can be used as variables, parameters, results, attributes, and columns.
 They can be thought of as one column database tables. Rows of a nested table are not stored in any
particular order.
 The size of a nested table can increase dynamically, i.e., nested tables are unbounded. Elements in a
nested table initially have consecutive subscripts, but as elements are deleted, they can have non-
consecutive subscripts.
 Nested tables can be fully manipulated using SQL, Pro*C, OCI, and PL/SQL. The range of values for nested
table subscripts is 1..2147483647.
 To extend a nested table, the built-in procedure EXTEND must be used. To delete elements, the built-in
procedure DELETE must be used.
 An uninitialized nested table is atomically null, so the IS NULL comparison operator can be used to see if a
nested table is null.
 Oracle8 provides new operators such as CAST, THE, and MULTISET for manipulating nested tables.

Examples :

The following example illustrates how a simple nested table is created.


a) First, define a Object type as follows:
SQL> CREATE TYPE ELEMENTS AS OBJECT (
2> ELEM_ID NUMBER(6),
3> PRICE NUMBER(7,2));
4> /
b) Next, create a table type ELEMENTS_TAB which stores ELEMENTS objects:

SQL> CREATE TYPE ELEMENTS_TAB AS TABLE OF ELEMENTS;


2> /
c) Finally, create a database table STORAGE having type ELEMENTS_TAB as one of its columns:
SQL> CREATE TABLE STORAGE (
2> SALESMAN NUMBER(4),
3) ELEM_ID NUMBER(6),
4) ORDERED DATE,
5) ITEMS ELEMENTS_TAB)
6) NESTED TABLE ITEMS STORE AS ITEMS_TAB;

CONCLUSION:

The use of Nested tables in oracle was successfully studied and implemented

CODE AND OUTPUT:

SQL> CREATE TYPE texp AS OBJECT


2 (
3 CompanyName
4 varchar2(20),
5 Position
6 varchar2(20),
7 NoOfYears
8 number(2)
9 );
10 /

Type created.
SQL> CREATE TYPE texptbl AS TABLE OF texp;
2 /

Type created.
SQL> CREATE TABLE employee
2 (
3 Name varchar2(20),
4 Experiences
5 texptbl
6 )
7 NESTED TABLE Experiences STORE AS Experiences_tab;

Table created.

SQL> insert into employee values


2 (
3 'jag',
4 texptbl
5 (
6 texp('abc company','Software
7 Engineer',3),
8 texp('xyz company','System Analyst',2),
9 texp('mnp company','Research fellow',4)
10 )
11 );
1 row created.
SQL> select a.CompanyName,a.NoOfYears from
2 table(select experiences from employee where
3 name='jag') a

COMPANYNAME NOOFYEARS
-------------------- ----------
abc company 3
xyz company 2
mnp company 4

SQL> select a.CompanyName,a.NoOfYears from


2 the(select experiences from employee where name='jag')
3 a
4 /

COMPANYNAME NOOFYEARS
-------------------- ----------
abc company 3
xyz company 2
mnp company 4

SQL> select a.* from


2 table(select experiences from employee where
3 name='jag') a
4 /

COMPANYNAME POSITION NOOFYEARS


-------------------- -------------------- ----------
abc company Software 3
Engineer

xyz company System Analyst 2


mnp company Research fellow 4

SQL> INSERT INTO TABLE(SELECT experiences FROM employee WHERE name= 'jag')
2 VALUES
3 (
4 texp('efg company','Professor',2)
5 );

1 row created.
SQL> UPDATE
2 TABLE(SELECT experiences FROM employee WHERE name
3 = 'jag')
4 set NoOfYears=5
5 where CompanyName='abc company';

1 row updated.

SQL> DELETE FROM


2 TABLE(SELECT experiences FROM employee WHERE name
3 = 'jag')
4 where CompanyName='abc company';

1 row deleted.

You might also like