Practical File of Advanced Database Management System Lab: CSP2301 Bachelor of Engineering

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 29

Practical File

Of
Advanced Database
Management System Lab
CSP2301
Bachelor OF ENGINEERING
(Department of Computer Science & Engineering)

Submitted to: Submitted by:


Name –Mrs. Shikha Name: Divij Kanwar
Roll no. - 1710991235

July – Dec (2019)

CHITKARA UNIVERSITY
PUNJAB, INDIA

CHITKARA UNIVERSITY INSTITUTE OF ENGINEERING AND


TECHNOLOGY
Roll No.: 1710991235 Name: Divij Kanwar

INDEX

S.No Experiment Date Signature

1 To implementation the concept of indexes, views,


sequence, clusters.
2 Introduction to PL/SQL Concepts, its features and
shows how PL/SQL meets the challenges of
database programming, and how you can reuse techniques
that you
know from other programming languages.
3 How to structure the flow of control through a PL/SQL
program. Connect the statements by simple but powerful
control structures that have a single entry and exit point.

Collectively, these structures can handle any situation.


Their proper use should lead naturally to a well-structured
program.
With PL/SQL mechanism called exception handling, design
4
"bulletproof” program so that it can continue operating in
the presence of errors.(System defined, user-defined)
To use PL/SQL to Raise application error and design
5
Pragma init exceptions.
Create a temporary work area in the system memory
6
whenever a SQL statement is executed. This temporary
work area will be used to store the data retrieved from the
database, and manipulate this data.
Create a cursor that can hold more than one row, but can
process only one row at a time.
Creating and calling a standalone function. The function
should return the total number of CUSTOMERS in the
7 customers table. Use the CUSTOMERS table, with
different columns like name, salary, department,
designation, DOJ
etc.
You can speed up PL/SQL procedures by compiling
8
them into native code residing in shared libraries. The
procedures are translated into C code, then compiled with
your usual C compiler and linked into the Oracle Database
process. creates a procedure ‘employer_details’ which gives
the
details of the employee.
How to bundle related PL/SQL code and data into
9
a package. The package might include a set of procedures
that forms an API, or a pool of type definitions and variable
declarations. The package is compiled and stored in the
database, where its contents can be shared by many
applications.

CSE 5E- Page 2


01
Roll No.: 1710991235 Name: Divij Kanwar

To create a pl/sql block structure which is fired when DML


10
statements like Insert, Delete, Update is executed on a
database table. A trigger is triggered automatically when an
associated DML statement is executed

CSE 5E- Page 3


01
EXPERIMENT NO.- 1
AIM: Implementation of indexes, views, sequence,

clusters. THEORY:

1. INDEXES
 An index is used to speed up select quires and where clauses but slows down with
update or insert when data is put into it. Creation or dropping of index does not
affect data in the table.
 Tablespace: These are logical partitions having physical space used to store data
files. Syntax: CREATE INDEX index_name ON table_name (col_name)
TABLESPACE tablespace_name;
 Two Type of Index:
 Implicit: Created Automatically
 Explicit: Created by DBA
 Index Creation Involves three steps:
 Naming of index.
 Specify the table at which column(s) to index.
 Indicate if the index is ascending or descending.

 TYPES OF INDEXES

 Simple Indexes
 Composite Indexes
 Unique Indexes
 Bitmap Indexes
 Function Based Indexes
 Reverse key Index
1. Simple Indexes: It is used to create index on single column.
Syntax: create index index_name ON table_name(column_name);
Program: CREATE INDEX RISHABH ON TEMP(NAME);
OUTPUT:

2. Composite indexes: It is used to create index on Multiple column


Syntax: create index index_name ON table_name (column_1,
column_2); Program: create index complex_idx on temp(salary,ename);
OUTPUT:

3. Unique indexes
Syntax: create unique index index_name ON table_name (column_1);
Program: create unique index unique_idx on temp(salary);
OUTPUT:

4. Bitmap indexes: These are created on column that have low cardinality and
are used with AND or OR operators.
Syntax: create bitmap index index_name on table_name (column_1);
Program: create bitmap index bitmap_idx on temp(egender);
OUTPUT:

5. Reverse indexes
Syntax: create index index_name on table_name (column_1) reverse;
Program: create index reverse_idx on temp(egender) reverse;
OUTPUT:
6. Index by function
Syntax: create index index_name on table_name ((function)column_1);
Program: create index function_idx on temp(upper(ename));
OUTPUT:

 DROP INDEX
Syntax: drop index index_name
Program: drop index drop_idx;
OUTPUT:

 REBUILD INDEX
Syntax: alter index index_name rebuild;
OUTPUT:

 Location of indexes: Syntax = select table_name, index_name, column_name from


all_ind_columns where table_owner = ‘XXXX’;
OUTPUT:
2. VIEWS
 A View is a logical representation of the subset of table. 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.

Features Simple View Complex View


Number of tables 1 Multiple
Contains Functions No They do contain functions.
Contain group of data No Yes
DML operations Yes Not Always

 Create Simple View


Syntax: CREATE VIEW view_name AS SELECT column1, column2 FROM
table_name WHERE condition;
Program: create view vu_emp as select * from emp where deptno=10;
Output:

 Drop view
Syntax: drop view view_name;
Output:
 Programs:
 Create a view from emp table consisting of employee no, name, commission
and salary increased with 20% of existing salary into the view?
Syntax: create view simpleview as select empno, ename, comm,(sal+sal*0.20) as
salary from emp

Output:

 Create a view that contains deptname, min, sal, max salary and avg. salary
keeping the name as comp_view?
Syntax: create or replace view comp_view(ename,maxsal,minsal,avgsal) as
select d.dname,max(e.sal),min(e.sal),avg(e.sal) from emp e join dept d on
d.deptno=e.deptno group by d.dname
select * from comp_view
Output:

 Create a view named as empvu20 that contains all the details of belonging to
deptno 20 but it should not support any dml operation while inserting data of
any employee other than any employee other than 20?
Syntax: create or replace view empvu20 as select * from emp where deptno=20
with check option constraint const_chk.
Output:

 Create a view containing empno, job, deptno=10 of dept 10 with no dml


operation?
Syntax: create or replace view empq as select * from emp where deptno=10 with
read only
Output:

3. SEQUENCE
 A sequence is a set of integers that are generated in order on demand.
 They are used in database many applications acquire row to contain a unique
value and sequence provide easy way to generate. It generates Number in equal
and application use them no. where they require unique value such as primary key
value.
 Features:
 Available to all users.
 Created using SQL statements.
 Have Min. and Max. values.
 They can be dropped but not reset.
 Sequences are incremented by amount specified which created.
 NEXTVALUE
 Returns the next value of sequences and returns a unique value of the
sequences.
 Output:

 CURRVAL
 Obtains the current value of sequences.
 Output:

 Syntax: create sequence sequence_name start with ‘starting number’ increment by


‘number’ maxvalue ‘number’
 Create Sequence: Syntax: CREATE SEQUENCE <sequence name> [Start with
start_num] [Increment by increment_number] [{MAXVALUE max_no |
NOMAX VALUE}] [{MINVALUE min_no | NOMIN VALUE}] [{CYCLE |
NOCYCLE}] [{CACHE | NOCACHE}] [{ORDER | NOORDER}]
 Example:
create table suraj123(name varchar(20),id number);
create sequence suraj111 start with 1 increment by 1 maxvalue 10;
insert into suraj123 values('siranjeet',angad.nextval);
insert into suraj123 values('stuti',angad.nextval);
insert into suraj123 values('sunny',angad.nextval);
insert into suraj123 values('supreet',angad.nextval);
select * from suraj123;

 OUTPUT:

 Alter Sequence: “Start with” can’t be altered.


Syntax: alter sequence sequence_name increment by increment_value;
Output:
 DROP Sequence
Syntax: DROP SEQUENCE
sequence_name; Output:

 Program:
 Create a sequence that start with 150 and grows up to 550 with cache
memory of 10 & a cycle?
Syntax: Create sequences seq2 start with 150 incremented by 1 maxvalue 550
cache 10 cycle.

4. CLUSTERS
 Cluster is used for improving Oracle performance. They are used to store data from
different table in same physical data block. They are useful in case when record
from a table are frequently queried together. Every cluster stores data as well as
maintain index to sort the data.
 Cluster Key: Column within cluster are called cluster key in foreign key of one
table that references primary key of another table.
 TYPES OF CLUSTER

 INDEX CLUSTER:

In an indexed cluster, Oracle Database stores together rows having the same cluster
key value. Each distinct cluster key value is stored only once in each data block,
regardless of the number of tables and rows in which it occurs. If you specify neither
INDEX nor HASHKEYS, then Oracle Database creates an indexed cluster by default.
Syntax: create cluster cluster_name(column_name type);
Example:
create cluster personall(deptno number(2))
create index c_idx on cluster personall
create table dept01 cluster personall(deptno) as select * from emp where
deptno=10;
OUTPUT:

CSE 5E- Page 10


01
 HASH CLUSTER

Syntax: create cluster cluster_name(column name type) hashkeys 20;


Example:
create cluster language (cust_lang varchar(2)) HASHKEYS 20;
OUTPUT:
Experiment No.-2

AIM: Introduction to PL/SQL concepts, its features and shows how PL/SQL meets the
challenges of database programming, and how you can reuse techniques that you know
from other programming languages.

Introduction: PL/SQL is a block structured language that enables developers to combine


the power of SQL with procedural statements. All the statements of a block are passed to
oracle engine, all at once which increases processing speed and decreases the traffic.

Features:

1. PL/SQL is basically a procedural language which provides the functionality of


decision making, iterations and many other features of procedural programming
languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers
which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL
block known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or OS
where oracle is operational.
6. PL/SQL offers extensive error checking.

Declarations Section:

This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in the
program.

Executable Commands

This section is enclosed between the keywords BEGIN and END and it is a mandatory
section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.

Exception Handling

Exception is unavoidable in the program which occurs at runtime that is handled by


exception handling section in the block. This section starts with the keyword
EXCEPTION. This optional section contains exception(s) that handle errors in the
program.

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

LOG File

A log, in a computing context, is the automatically produced and time-stamped


documentation of events relevant to a particular system. Virtually all software applications
and systems produce log files.

Similarity between PL/SQL and other PL:

1. Use of Exceptions.
2. Declaring Variables.
3. Input variables from user.
4. Declaring functions.
5. Loops can be used.

Advantages:

Reduction in Network Traffic: It is one of the greatest advantages of PL/SQL, as it executes


entire block of Oracle engine altogether; hence, bringing down the network traffic issues.

Error Handling: While execution of a PL/SQL program, it effectively handles all the errors
and gives user-friendly error messages to resolve the issues.

Procedural Language Capability: PL/SQL comprises of conditional checking tools or the


procedural language constructs like conditional statements, looping, and branching.

Block Structures: PL/SQL contains code blocks that can be nested into each other. Every
block forms a logical module that can be stored in database and can be reused later.

PLSQL Identifiers:

1. Declare variable

Variable_name datatype := value;


Eg: a number := 10;

2. To Display Variables
Dbms_output.putline(a);

3. Comments
Single line comment: _Hello_
Multiple line comment: /* Hello
Hi */
4. Datatype
 Number
Fixed-point or floating-point number with absolute value in range 1E-130
to (but not including) 1.0E126. A NUMBER variable can also represent.
 Float
ANSI and IBM specific floating-point type with maximum precision of 126
binary digits (approximately 38 decimal digits)
 Decimal
IBM specific fixed-point type with maximum precision of 38 decimal digits
 Character
Alphanumeric values that represent single characters or strings of
characters.
 Long
Variable-length character string with maximum size of 32,760 bytes
 Date
The DATE datatype is used to store fixed-length datetimes, which include
the time of day in seconds since midnight. Valid dates range from January 1,
4712 BC to December 31, 9999 AD.
 Time
Used to store time.
 LOB
Large Object (LOB) data types refer to large data items such as text,
graphic images, video clips, and sound waveforms. LOB data types allow
efficient, random, piecewise access to this data.

Problems:

1. Area of circle
2. Calculator

3. Area and Perimeter of circle


Experiment No.-3

AIM: How to structure the flow of control through a PL/SQL program. Connect the
statements by simple but powerful control structures that have a single entry and exit point.

Collectively, these structures can handle any situation. Their proper use should lead
naturally to a well-structured program.

 Conditional Control

IF-THEN-ELSIF

 The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause
lets you
add additional conditions.
 When using IF-THEN-ELSIF statements there are a few points to keep in mind.
 An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
 An IF-THEN statement can have zero to many ELSIF's and they must come before
the ELSE.
 Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
 Syntax:

IF (boolean_expression 1) THEN
S1; // Executes when the boolean expression 1 is true
ELSIF ( boolean_expression 2) THEN
S2; // Executes when the boolean expression 2 is true
ELSIF ( boolean_expression 3) THEN
S3; // Executes when the boolean expression 3 is true
ELSE
S4; // executes when the none of the above condition is true
END IF;
 CASE expression:
Like the IF statement, the CASE statement selects one sequence of statements to
execute. However, to select the sequence, the CASE statement uses a selector
rather than multiple Boolean expressions. A selector is an expression, the value of
which is used to select one of several alternatives.

Syntax:
CASE selector
WHEN 'value1' THEN
S1; WHEN 'value2'
THEN S2; WHEN
'value3' THEN S3;
...
ELSE; -- default
case END CASE;

Example:

Iterative Control
1. While Loop:
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.

Syntax:
WHILE condition LOOP
sequence_of_statements
END LOOP;
2. Basic Loop
Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.

Syntax:
LOOP
Sequence of statements;
END LOOP;

3. For Loop
A FOR LOOP is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.
Syntax:
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Sequential Control
1. GOTO
A GOTO statement in PL/SQL programming language provides an unconditional jump
from the GOTO to a labeled statement in the same subprogram.

Syntax:
GOTO label;
..
..
<< label >>
statement;

2. EXIT

The EXIT statement in PL/SQL programming language has the following two usages
−1. When the EXIT statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next statement
following the loop.

2. If you are using nested loops (i.e., one loop inside another loop), the EXIT
statement will stop the execution of the innermost loop and start executing the next
line of code after the block.
Syntax:
EXIT;
Program:

CSE 5E- Page 20


01
Experiment No. - 4

Aim: With PL/SQL mechanism called exception handling, design "bulletproof” program so
that it can continue operating in the presence of errors. (System defined, user-defined)

Introduction
An error occurs during the program execution is called Exception in PL/SQL.

An Exceptions is a condition that deals with error.

PL/SQL allows to catch such conditions using exception block in the program and an
appropriate action is taken against the error condition. There are two type of exceptions:

 System-defined Exceptions: Already defined by oracle


 User-defined Exceptions: Defined by

User Syntax:

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
System defined exception in PL/SQL are:

1. NO_DATA_FOUND (ORA -01403):


2. TOO_MANY_ROWS (ORA -01422):

3. CASE_NOT_FOUND (ORA -06592): It is raised when none of the choices in the


when clause of case statement is selected and also there is no else clause.

4. VALUE_ERROR (ORA -06502): It is raised when any attribute conversion, truncation or


size constraint error occurs.
5. ZERO_DIVIDE (ORA -01476): Is raised when a something is divvied by zero.

6. STORAGE_ERROR (ORA -06500): PL/SQL ran out of memory or memory got


corrupted.

7. ROW_TYPE_MISMATCH (ORA -06504): It is raised when cursor fetches value in


a variable having incomplete data type.

8. PROGRAM_ERROR (ORA -06501): It is raised when PL/SQL has internal problem.

9. DUP_VAL_ON_INDEX (ORA -00001): It is raised when duplicate values are inserted


in a column with unique index.

10. INVALID_NUMBER (ORA -01722): It is raised when conversion of character


string because string does not represent the valid number.

Programs:

Q. Make a program takes two input and shows the divide, but it should and shows the
divide, but the divisor is either 1 or 0.

Output:
Q. Generate a user defined invalid is exception for the customers_id that ranges less
than or equale to 0. The code must fetch name of the employee that matches with the id
of customers defined in the program also use predefined exception by oracle engine of
no data found.

Output:
Experiment No.-5

AIM: To use PL/SQL to Raise application error and design Pragma init exceptions.

Introduction: The pragma exception_init associates an exception with an oracle error


number. You can intercept any ORA- error and write a specific handler for it instead of
using the others handler. The keyword and the parameter description of pragma is

 Error_number: Any valid oracle number (It is always negative integer in the
range - 20000 ... -20999).
 Any valid oracle number (It is always negative)
Exception_name: A user defined exception declared.
 User Defined exception declared
 Pragma: Statement which is compiler directed.

SQLERRM: The function SQLERRM returns the error message associated with its
error- number argument. If the argument is omitted, it returns the error message
associated with the current value of SQLCODE. SQLERRM with no argument is
useful only in an exception handler. Outside a handler, SQLERRM with no argument
always returns
the normal, successful completion message. For internal exceptions, SQLERRM
returns the message associated with the Oracle error that occurred. The message
begins with the Oracle error code.

SQL Code: When an error occurs SQL code returns the error no. he SQLCODE option
holds the value returned by the Oracle RDBMS after the most recently attempted
SQL operation.

 If SQLCODE = 0, execution was successful.


 If SQLCODE > 0, execution was successful with a warning.
 If SQLCODE < 0, execution was not successful.
 SQLCODE = 100, "no data" was found. For example, a FETCH statement
returned no data because the cursor was positioned after the last row of the result
table.

Syntax:

DECLARE
deadlock_detected EXCEPTION;
PRAGMA EXCEPTION_INIT (deadlock_detected,
-60); BEGIN
NULL; -- Some operation that causes an ORA-00060
error EXCEPTION
WHEN deadlock_detected THEN
NULL; -- handle the error
END;
Programs:
Q. Find out whether user is allowed to vote by inputting age, if above 18 age, a person
can vote otherwise not?
Output:

Exception for Invalid Number

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy