Ii - Ii DBMS Lab
Ii - Ii DBMS Lab
II Year – II
L T P C
Semester Database Management Systems
Course Code : Lab
1005202210 0 0 3 1.5
COURSE OBJECTIVES:
1. To provide a sound introduction to the discipline of database management as a
subject in its own right, rather than as a compendium of techniques and product-
specific tools.
2. To familiarize the participant with the nuances of database environments towards
information oriented data-processing oriented framework.
3. To give a good formal foundation on the relational model of data
4. To present SQL and procedural interfaces to SQL comprehensively
5. To give an introduction to systematic database design approaches covering
conceptual design, logical design and an overview of physical design
COURSE OUTCOMES:
Strength
At the end of the course, the student will POs
CO’s of
have the ability to: Mapped
mapping
Understand, appreciate and effectively PO1 1
CO1 explain the underlying concepts of PO2 2
database technologies PO4 2
CO2 Design and implement a database schema PO1 2
for a given problem-domain PO2 1
PO1 2
CO3 Normalize a database PO2 2
PO4 2
CO4 Populate and query a database using SQL PO1 2
DML/DDL commands. PO2 2
LIST OF EXPERIMENTS
Department of ECM 1
DataBaseManagemenSystems Lab
Department of ECM 2
DataBaseManagemenSystems Lab
Exercise – 12
12. Develop programs using features parameters in a Cursors
CURSOR, FOR UPDATE CURSOR, WHERE CURRENT of
clause and CURSOR variables.
Exercise – 13
13. Develop Programs using BEFORE and AFTER Triggers, Triggers
Row and Statement Triggers and INSTEAD OF Triggers.
Exercise – 14 For a given set of relation tables perform the
following:
a. Creating Views Views
14,
b. Dropping Views
c. Selecting from a View
Department of ECM 3
DataBaseManagemenSystems Lab
Experiment 1:
Aim: Creation, altering and dropping of tables and inserting rows into a table (use
constraints while creating tables) examples using SELECT command.
Description: SQL language is divided into four types of primary language statements:
DML, DDL, DCL and TCL. Using these statements, we can define the structure of a
database by creating and altering database objects, and we can manipulate data in a
table through updates or deletions. We also can control which user can read/write data
or manage transactions to create a single unit of work.
DML statements affect records in a table. These are basic operations we perform on data
such as selecting a few records from a table, inserting new records, deleting unnecessary
records, and updating/modifying existing records.
DDL statements are used to alter/modify a database or table structure and schema.
These statements handle the design and storage of database objects.
Department of ECM 4
DataBaseManagemenSystems Lab
DCL statements control the level of access that users have on database objects.
TCL statements allow you to control and manage transactions to maintain the integrity
of data within SQL statements.
create is a DDL SQL command used to create a table or a database in relational database
management system.
Creating a Database
The above command will create a database named Test, which will be an empty schema
without any table.
To create tables in this newly created database, we can again use the create command.
Creating a Table
createcommand can also be used to create tables. Now when we create a table, we have
to specify the details of the columns of the tables too. We can specify the names and
datatypes of various columns in the create command itself.
Department of ECM 5
DataBaseManagemenSystems Lab
createtable command will tell the database system to create a new table with the given
table name and column information.
The above command will create a new table with name Student in the current database
with 3 columns, namely student_id, name and age. Where the column student_id will only
store integer, name will hold upto 100 characters and age will again store only integer
value.
If you are currently not logged into your database in which you want to create the table
then you can also add the database name along with table name, using a dot operator .
For example, if we have a database with name Test and we want to create a table Student
in it, then we can do so using the following query:
Here we have listed some of the most commonly used datatypes used for columns in
tables.
Datatype Use
Department of ECM 6
DataBaseManagemenSystems Lab
used for columns which will be used to store characters and integers,
VARCHAR
basically a string.
CHAR used for columns which will store char values(single character).
used for columns which will store text which is generally long in length. For
example, if you create a table for storing profile information of a social
TEXT
networking website, then for about me section you can have a column of type
TEXT.
Using ALTER command we can even add multiple new columns to any existing table.
Following is the syntax,
The above command will add three new columns to the student table
ALTER command can add a new column to an existing table with a default value too. The
default value is used when no value is inserted in the column. Following is the syntax,
Department of ECM 7
DataBaseManagemenSystems Lab
The above command will add a new column with a preset default value to the table
student.
ALTER command can also be used to modify data type of any existing column. Following
is the syntax,
Remember we added a new column address in the beginning? The above command will
modify the address column of the student table, to now hold upto 300 characters.
Using ALTER command you can rename an existing column. Following is the syntax,
ALTER command can also be used to drop or remove columns. Following is the syntax,
Department of ECM 8
DataBaseManagemenSystems Lab
The above command will drop the address column from the table student
In this tutorial we will learn about the various DDL commands which are used to re-
define the tables.
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not
destroy the table's structure. When we use TRUNCATE command on a table its (auto-
increment) primary key is also initialized. Following is its syntax,
The above query will delete all the records from the table student.
In DML commands, we will study about the DELETE command which is also more or less
same as the TRUNCATE command. We will also learn about the difference between the
two in that tutorial.
DROP command
DROP command completely removes a table from the database. This command will also
destroy the table structure and the data stored in it. Following is its syntax,
The above query will delete the Student table completely. It can also be used on
Databases, to delete the complete database. For example, to drop a database,
Department of ECM 9
DataBaseManagemenSystems Lab
The above query will drop the database with name Test from the system.
RENAME query
RENAME command is used to set a new name for any existing table. Following is the
syntax,
RENAME TABLE old_table_name to new_table_name
Here is an example explaining it.
RENAME TABLE student to students_info;
The above query will rename the table student to students_info.
Using INSERT SQL command
Data Manipulation Language (DML) statements are used for managing data in database.
DML commands are not auto-committed. It means changes made by DML command are
not permanent to database, it can be rolled back.
Talking about the Insert command, whenever we post a Tweet on Twitter, the text is stored
in some table, and as we post a new tweet, a new record gets inserted in that table.
INSERT command
Insert command is used to insert data into a table. Following is its general syntax,
The above command will insert a new record into student table.
101 Adam 15
Department of ECM 10
DataBaseManagemenSystems Lab
102 Alex
101 Adam 15
102 Alex
103 chris 14
Suppose the column age in our tabel has a default value of 14.
Also, if you run the below query, it will insert default value into the age column, whatever
the default value may be.
Department of ECM 11
DataBaseManagemenSystems Lab
UPDATE command
UPDATE command is used to update any record of data in a table. Following is its general
syntax,
UPDATE table_name SET column_name = new_value WHERE some_condition;
WHERE is used to add a condition to any SQL query, we will soon study about it in detail.
Lets take a sample table student,
student_id name age
101 Adam 15
102 Alex
103 chris 14
101 Adam 15
102 Alex 18
103 chris 14
In the above statement, if we do not use the WHERE clause, then our update query will
update age for all the columns of the table to 18.
102 Alex 18
103 Abhi 17
Department of ECM 12
DataBaseManagemenSystems Lab
Let's study about the syntax and the usage of the Delete command.
DELETE command
DELETE command is used to delete data from a table.
Following is its general syntax,
DELETE FROM table_name;
Let's take a sample table student:
s_id name age
101 Adam 15
102 Alex 18
103 Abhi 17
The above command will delete all the records from the table student.
In our student table if we want to delete a single record, we can use the WHERE clause to
provide a condition in our DELETE statement.
The above command will delete the record where s_id is 103 from the table student.
101 Adam 15
102 Alex 18
Department of ECM 13
DataBaseManagemenSystems Lab
Experiment-2
Aim: Queries (along with sub Queries) using ANY, ALL, IN, EXISTS, NOTEXISTS, UNION,
INTERSET, Constraints.
Description:
The SQL ANY and ALL Operators:
The ANY and ALL operators are used with a WHERE or HAVING clause
The ANY operator returns true if any of the subquery values meet the condition.
The ALL operator returns true if all of the subquery values meet the condition.
ANY Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);
ALL Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name FROM table_name WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Demo Database
Below is a selection from the "Products" table in the Northwind sample database:
ProductID ProductName SupplierID CategoryID Unit Price
1 Chais 1 1 10 boxes 18
x 20 bags
2 Chang 1 1 24 - 12 oz 19
bottles
Department of ECM 14
DataBaseManagemenSystems Lab
1 10248 11 12
2 10248 42 10
3 10248 72 5
4 10249 14 9
5 10249 51 40
The ANY operator returns TRUE if any of the subquery values meet the condition.
The following SQL statement returns TRUE and lists the productnames if it finds ANY
records in the OrderDetails table that quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
The following SQL statement returns TRUE and lists the productnames if it finds ANY
records in the OrderDetails table that quantity > 99:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity
> 99);
SQL ALL Example
The ALL operator returns TRUE if all of the subquery values meet the condition.
The following SQL statement returns TRUE and lists the productnames if ALL the records
in the OrderDetails table has quantity = 10:
Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity
= 10);
Department of ECM 15
DataBaseManagemenSystems Lab
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Below is a selection from the "Customers" table in the Northwind sample database:
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France"
and "UK":
Example
Department of ECM 16
DataBaseManagemenSystems Lab
The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":
Example
The following SQL statement selects all customers that are from the same countries as
the suppliers:
Example
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
Example
SELECT SupplierName
FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
Each SELECT statement within UNION must have the same number of columns
The columns must also have similar data types
The columns in each SELECT statement must also be in the same order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Department of ECM 17
DataBaseManagemenSystems Lab
The following SQL statement returns the cities (only distinct values) from both the
"Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Department of ECM 18
DataBaseManagemenSystems Lab
Experiment 3:
Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
Aim: Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING and Creation and dropping of Views.
Description:
Aggregate Functions
These functions return a single value after performing calculations on a group of values.
Following are some of the frequently used Aggregrate functions.
1. AVG() Function
Average returns average value after calculating it from values in a numeric column.
Its general syntax is,
SELECT AVG(column_name) FROM table_name
8200
2. COUNT() Function
Count returns the number of rows present in the table either based on some condition or
without condition.
Its general syntax is,
SELECT COUNT(column_name) FROM table-name
Department of ECM 19
DataBaseManagemenSystems Lab
Example of COUNT(distinct)
Consider the following Emp table
eid name age salary
Department of ECM 20
DataBaseManagemenSystems Lab
3. MAX() Function
MAX function returns maximum value from selected column of the table.
Syntax of MAX function is,
SELECT MAX(column_name) from table-name;
10000
4. MIN() Function
MIN function returns minimum value from a selected column of the table.
Syntax for MIN function is,
SELECT MIN(column_name) from table-name;
Department of ECM 21
DataBaseManagemenSystems Lab
6000
5. SUM() Function
SUM function returns total sum of a selected columns numeric values.
Syntax for SUM is,
SELECT SUM(column_name) from table-name;
41000
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.
Department of ECM 22
DataBaseManagemenSystems Lab
ORDER BY Statement
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the
records in descending order, use the DESC keyword.
ORDER BY Syntax:
Department of ECM 23
DataBaseManagemenSystems Lab
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
The following SQL statement selects all customers from the "Customers" table, sorted by
the "Country" and the "CustomerName" column. This means that it orders by Country,
but if some rows have the same Country, it orders them by CustomerName:
1.SELECT * FROM Customers
ORDER BY Country, CustomerName;
2. SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
GROUP BY Statement
The GROUP BY statement group rows that have the same values into summary rows, like
"find the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.
Department of ECM 24
DataBaseManagemenSystems Lab
GROUP BY Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
GROUP BY Examples:
1. The following SQL statement lists the number of customers in each country:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
2. The following SQL statement lists the number of customers in each country, sorted
high to low:
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
Department of ECM 25
DataBaseManagemenSystems Lab
Experiment-4
1) Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric
values as input and return numeric values as output. Few of the Numeric functions are:
Function
Return Value
Name
ABS (x) Absolute value of the number 'x'
CEIL (x) Integer value that is Greater than or equal to the number 'x'
FLOOR (x) Integer value that is Less than or equal to the number 'x'
TRUNC (x, y) Truncates value of number 'x' up to 'y' decimal places
ROUND (x, y) Rounded off value of the number 'x' up to the number 'y' decimal places
The following examples explains the usage of the above numeric functions
Function Return
Examples
Name Value
ABS (1) 1
ABS (x)
ABS (-1) 1
CEIL (2.83) 3
CEIL (x) CEIL (2.49) 3
CEIL (-1.6) -1
FLOOR (2.83) 2
FLOOR (x) FLOOR (2.49) 2
FLOOR (-1.6) -2
ROUND (125.456, 1) 125.5
ROUND (125.456, 0) 125
ROUND (x, y)
ROUND (124.456, -1) 120
ROUND (124.456, -2) 100
TRUNC (140.234, 2) 140.23
TRUNC (x, y)
TRUNC (-54, 1) -54
TRUNC (142, -1) 140
Department of ECM 26
DataBaseManagemenSystems Lab
For Example: Let's consider the product table used in sql joins. We can use ROUND to
round off the unit_price to the nearest integer, if any product has prices in fraction.
2) String Functions:
Character or text functions are used to manipulate text strings. They accept strings or
characters as input and can return both character and number values as output.
For Example, we can use the above UPPER() text function with the column value as
follows.
The following examples explains the usage of the above character or text functions
Department of ECM 27
DataBaseManagemenSystems Lab
3) Date Functions:
These are functions that take values that are of datatype DATE as input and return values
of datatypes DATE, except for the MONTHS_BETWEEN function, which returns a number
as output.
The below table provides the examples for the above functions
Return
Function Name Examples
Value
ADD_MONTHS ( ) ADD_MONTHS ('16-Sep-19', 3) 16-Dec-19
MONTHS_BETWEEN( ) MONTHS_BETWEEN ('16-Dec-19', '16-Sep-19') 3
NEXT_DAY( ) NEXT_DAY ('15-Jul-19', 'thursday') 18-JUL-19
Department of ECM 28
DataBaseManagemenSystems Lab
ROUND()
ROUND (TO_DATE ('27-jul-00'),'year') 01-JAN-01
ROUND (TO_DATE ('27-jul-00'),'month') 01-AUG-00
01-JAN-00
TRUNC() TRUNC (TO_DATE ('27-jul-00'),'year') 01-JUL-00
TRUNC (TO_DATE ('27-jul-00'),'month')
4) Conversion Functions:
These are functions that help us to convert a value in one form to another form. For Ex:
a null value into an actual value, or a value from one datatype to another datatype like
NVL, TO_CHAR, TO_NUMBER, TO_DATE.
Few of the conversion functions available in oracle are:
Function Name Return Value
Converts Numeric and Date values to a character string value. It
TO_CHAR (x [,y])
cannot be used for calculations since it is a string value.
TO_DATE (x [, Converts a valid Numeric and Character values to a Date value.
date_format]) Date is formatted to the format specified by 'date_format'.
If 'x' is NULL, replace it with 'y'. 'x' and 'y' must be of the same
NVL (x, y)
datatype.
The below table provides the examples for the above functions
Function
Examples Return Value
Name
TO_char (sysdate,'dd-month-year')
TO_CHAR () 15-july -twenty nineteen
Department of ECM 29
DataBaseManagemenSystems Lab
Experiment 5:
Introduction:
PL/SQL bridges the gap between database technology and procedural
programming languages. It can be thought of as a development tool that
extends the facilities of Oracle’s SQL database language. Via PL/SQL you
can insert, delete, update and retrieve table data as well as writing loops or
branching to another block of code.
Department of ECM 30
DataBaseManagemenSystems Lab
Department of ECM 31
DataBaseManagemenSystems Lab
Output :
Sum is 30
DECLARE
-- Declare variable n, r of datatype number
n NUMBER := &n;
r NUMBER;
BEGIN
-- Calculating modulo
r := MOD(n, 2);
IF r = 0 THEN
dbms_output.Put_line('Even');
ELSE
dbms_output.Put_line('Odd');
END IF;
END;
Output
Enter value for n: 7
Given number is odd
Department of ECM 32
DataBaseManagemenSystems Lab
Note:
When other keyword should be used only at the end of the exception
handling block as no exception handling part present later will get executed
as the control will exit from the block after executing the WHEN OTHERS.
System defined exceptions:
These exceptions are predefined in PL/SQL which get raised WHEN
certain database rule is violated.
System-defined exceptions are further divided into two categories:
1. Named system exceptions.
2. Unnamed system exceptions.
OUTPUT:
ERROR
there is no name as Robin in Student table
Department of ECM 33
DataBaseManagemenSystems Lab
DECLARE
temp varchar(20);
BEGIN
-- raises an exception as SELECT
-- into trying to return too many rows
SELECT sname into temp from student;
dbms_output.put_line(temp);
EXCEPTION
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too many
rows');
end;
Output:
error trying to SELECT too many rows
c) VALUE_ERROR: This error is raised WHEN a statement is executed that
resulted in an arithmetic, numeric, string, conversion, or constraint
error. This error mainly results from programmer error or invalid data
input.
DECLARE
temp number;
BEGIN
SELECT sname into temp from student where
sname='Suraj';
dbms_output.put_line('the sname is '||temp);
EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
dbms_output.put_line('Change data type of
temp to varchar(20)');
END;
Department of ECM 34
DataBaseManagemenSystems Lab
Output:
Error
Change data type of temp to varchar(20)
RAISE_APPLICATION_ERROR:
It is used to display user-defined error messages with error number whose
range is in between -20000 and -20999. When RAISE_APPLICATION_ERROR
executes it returns error message and error code which looks same as Oracle
built-in error.
Example:
DECLARE
myex EXCEPTION;
n NUMBER :=10;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
RAISE_APPLICATION_ERROR(-20015,
'Welcome to DBMS LAB');
END;
Output:
Error report:
ORA-20015: Welcome to DBMS LAB
ORA-06512: at line 13
1
4
9
16
Department of ECM 35
DataBaseManagemenSystems Lab
25
36
Note: The output is based on Oracle Sql developer, the output order might
change IF you’re running this code somewhere else.
Student marks can be selected from the table and printed for those who
secured first class and an exception can be raised if no records were found
Create table student (sid, sname, sclass);
Program:
declare
stu_id number;
stu_name
varchar(20); cursor
stu_cur is
select
sid,sname from
student
where sclass='first';
Begin
Open stu_cur;
Loop
fetch stu_cur into
stu_id,stu_name;
exit when stu_cur%notfound;
dbms_output.put_line('student_id: '|| stu_id ||
'student_name:'||stu_name); end loop;
close stu_cur;
end;
/
Output:
student_id: 1student_name:abhi
student_id: 2student_name:sai
student_id: 5student_name:ish
PL/SQL procedure successfully completed.
Department of ECM 36
DataBaseManagemenSystems Lab
Experiment-6:
Aim: Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT
inPL/SQL block.
Commit Rollback and Savepoint SQL commands
Transaction Control Language (TCL) commands are used to manage transactions in the
database. These are used to manage the changes made to the data in a table by DML
statements. It also allows statements to be grouped together into logical transactions.
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
When we use any DML command like INSERT, UPDATE or DELETE, the changes made
by these commands are not permanent, until the current session is closed, the changes
made by these commands can be rolled back.
To avoid that, we use the COMMIT command to mark the changes as permanent.
Following is commit command's syntax,
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used
with SAVEPOINT command to jump to a savepoint in an ongoing transaction.
If we have used the UPDATE command to make some changes into the database, and
realise that those changes were not required, then we can use the ROLLBACK command
to rollback those changes, if they were not commited using the COMMIT command.
Following is rollback command's syntax,
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback
to that point whenever required.
Following is savepoint command's syntax,
SAVEPOINT savepoint_name;
Department of ECM 37
DataBaseManagemenSystems Lab
In short, using this command we can name the different states of our data in any table
and then rollback to that state using the ROLLBACK command whenever required.
id name
1 Abhi
2 Adam
4 Alex
Lets use some SQL queries on the above table and see the results.
INSERT INTO class VALUES(5, 'Rahul');
COMMIT;
SAVEPOINT A;
SAVEPOINT B;
SAVEPOINT C;
Department of ECM 38
DataBaseManagemenSystems Lab
Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT
in PL/SQL block.
Savepoint h;
Savepoint created
SQL> set serveroutput on;
SQL> begin
savepoint g;
insert into stu values('ruhi','cse');
exception
when dup_val_on_index then
rollback to g;
commit;
end;
/
SQL>Rollback to h;
Rollback completed
Department of ECM 39
DataBaseManagemenSystems Lab
Experiment 7
Develop a program that includes the features NESTED IF, CASE And CASE
Expression. The program can be extended using the NULLIF and COALESCE
function
Decision making statements are those who will decide the flow-control
of SQL statements based on the conditions. It gives the programmer a better
control of preventing a particular code from executing (diagram 1) or choosing a
desired code based on the condition (diagram 2). Below is the pictorial
representation of the "Decision Making Statement".
Department of ECM 40
DataBaseManagemenSystems Lab
NESTED-IF Statement
The NESTED-IF statement is basically allowed programmers to place one
or more 'IF' condition inside another 'IF' condition's <action_block> other
than normal statements.
Each 'IF' condition should have a separate 'END IF' statement which
marks the end-of-scope of that particular <action_block>.
The 'IF' statement will consider the nearest 'END IF' statement as an
endpoint for that particular condition.
The pictorial representation for NESTED-IF is shown below diagram.
Department of ECM 41
DataBaseManagemenSystems Lab
Syntax Explanation:
In the above syntax, the outer IF contains one more IF statement in its
action block.
The condition1 returns <TRUE>, then control will be executing
<action_block1> and checks the condition2.
If condition2 also returns <TRUE>, then <action_block2> will also be
executed.
In case of condition2 evaluates to <FALSE> then, SQL will skip the
<action_block2>.
In this example, we are going to print the greatest of three numbers by using
Nested-If statement. The numbers will be assigned in the declare part, as you
can see in the code below, i.e Number= 10,15 and 20 and the maximum number
will be fetched using nested-if statements.
DECLARE
a NUMBER :=10;
b NUMBER :=15;
c NUMBER :=20;
Department of ECM 42
DataBaseManagemenSystems Lab
BEGIN
dbms_output.put_line('Program started.' );
if ( a > b)THEN
/*Nested-if l */
dbms_output.put_line('Checking Nested-IF 1');
IF( a > c ) THEN
dbms_output.put_line('A is greatest');
ELSE
dbms_output.put_line('C is greatest');
END IF;
ELSE
/*Nested-if2 */
dbms_output.put_line('Checking Nested-IF 2' );
IF( b > c ) THEN
dbms_output.put_line('B is greatest' );
ELSE
dbms_output.put_line('C is greatest' );
END IF;
END IF;
dbms_output.put_line('Program completed.' );
END;
Output:
Program started.
Checking Nested-IF 2
C is greatest
Program completed.
Statement processed.
CASE STATEMENT:
Department of ECM 43
DataBaseManagemenSystems Lab
A CASE statement is similar to IF-THEN-ELSIF statement that selects one
alternative based on the condition from the available options.
Syntax:
CASE (expression)
WHEN <valuel> THEN action_blockl;
WHEN <value2> THEN action_block2;
WHEN <value3> THEN action_block3;
ELSE action_block_default;
END CASE;
In the above syntax, the expression will return a value that could be of any
type (variable, number, etc.).
Each 'WHEN' clause is treated as an alternatives which have <value> and
<action_block>.
The 'WHEN' clause which matches the value as that of the expression will
be selected, and the corresponding <action_block> will be executed.
'ELSE' block is optional which hold the <action_block_default> that needs
to be executed when none of the alternatives match the expression value.
The 'END' marks the end of the CASE statement, and it is a mandatory
part of the CASE.
DECLARE
a NUMBER :=55;
Department of ECM 44
DataBaseManagemenSystems Lab
b NUMBER :=5;
BEGIN
dbms_output.put_line('Program started.' );
CASE (arth_operation)
);
END CASE;
dbms_output.put_line('Program completed.' );
END;
Output:
Program started.
Multiplication of the numbers are: 275
Program completed.
Statement processed.
NULLIF:
The Oracle NULLIF() function accepts two arguments. It returns a null value if the
two arguments are equal. In case the arguments are not equal, the NULLIF() function
returns the first argument.
Department of ECM 45
DataBaseManagemenSystems Lab
Syntax
The syntax for the NULLIF function in Oracle/PLSQL is:
NULLIF( expr1, expr2 )
Parameters or Arguments
expr1
First value to compare. Must be either a numeric value or a value that is the same
datatype as expr2.
expr2
Second value to compare. Must be either a numeric value or a value that is the
same datatype as expr1.
Returns
The NULLIF function returns NULL if expr1 and expr2 are equal.
The NULLIF function returns expr1 if expr1 and expr2 are not equal.
Note
expr1 can be an expression that evaluates to NULL, but it cannot be the literal
NULL.
For example:
Result: NULL
NULLIF('apples', 'apples')
Result: NULL
NULLIF('apples', 'oranges')
Result: 'apples'
NULLIF(NULL, 12)
Department of ECM 46
DataBaseManagemenSystems Lab
Result: ORA-00932 error (because expr1 cannot be the literal NULL)
COALESCE function:
The Oracle COALESCE() function accepts a list of arguments and returns the first one
that evaluates to a non-null value.
Syntax
The following example returns one because it is the first non-null argument:
SELECT
COALESCE(NULL,1)
FROM
dual;
RESULT
----------
1
The following example returns null because all arguments are null:
SELECT
COALESCE(NULL,NULL,NULL)
FROM
dual;
Example
The COALESCE function can be used in Oracle/PLSQL.
You could use the coalesce function in a SQL statement as follows:
Department of ECM 47
DataBaseManagemenSystems Lab
result := address2;
ELSE
result := null;
END IF;
Department of ECM 48
DataBaseManagemenSystems Lab
Department of ECM 49
DataBaseManagemenSystems Lab
Experiment 8
AIM: To implement PL/SQL program development using WHILE LOOPS,
numeric For Loops, nested loops using error handling, BUILT IN Exceptions,
user defined exceptions, RAISE Application Error.
Program on numeric For Loop: print the value of v_counter variable from 1 to 10.
BEGIN
FOR v_counter IN 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(v_counter);
END LOOP;
END;
BEGIN
FOR v_counter IN REVERSE 1..10 LOOP
DBMS_OUTPUT.PUT_LINE(v_counter);
END LOOP;
END;
Program on nested FOR Loop: Print the prime numbers below the given
range using Built in Exceptions
DECLARE
N integer;
L integer;
C integer:=0;
I number;
J number;
BEGIN
N:= ⦥
L:=N-1;
For I In 1..L LOOP
For J IN 1..I LOOP
IF mod(I,J)=0 then
C:=C+1;
END IF;
END LOOP;-- END OF INNER FOR LOOP
IF C=2 THEN
dbms_output.put_line(' '|| I);
END IF;
C:=0;
END LOOP;-- END OF OUTER FOR LOOP
Department of ECM 50
DataBaseManagemenSystems Lab
EXCEPTION
WHEN value_error THEN
dbms_output.put_line('Error');
END;
OUTPUT:
range: 10
2
3
5
7
Statement processed.
declare
n number;
i number;
rev number:=0;
r number;
begin
n:= &n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;
declare
str1 varchar2(50):='&str';
str2 varchar2(50);
len number;
i number;
begin
Department of ECM 51
DataBaseManagemenSystems Lab
len:=length(str1);
PROGRAME
declare
v_sid student.sid%type:=&sid;
v_total_courses number;
begin
if v_sid<0 then
raise_application_error(-20000,’an id cannot be –ve’);
else
select count(*) into v_total_courses from student where sid=v_sid;
dbms_output.put_line(‘the student is registered for
‘||v_total_courses||’courses’);
end if;
end;
/
OUTPUT
Department of ECM 52
DataBaseManagemenSystems Lab
Experiment 9
Output:
Minimum of (23, 45): 23
PL/SQL procedure successfully completed.
Department of ECM 53
DataBaseManagemenSystems Lab
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
Output:
Factorial 6 is 720
Department of ECM 54
DataBaseManagemenSystems Lab
Experiment-10
Department of ECM 55
DataBaseManagemenSystems Lab
Function Created
For calling the function Sum following code will be executed
set serveroutput on;
DECLARE
no1 number;
no2 number;
result number;
BEGIN
no1 := &no1;
no2 := &no2;
result := Sum(no1,no2);
dbms_output.put_line(‘Sum of two nos=’||result);
END;
OUTPUT
Enter value for no1:5
Enter value for no2:5
Sum of two nos=10
PL/SQL procedure successfully created.
Now, let’s take an example to demonstrate Declaring, Defining and
Invoking a simple PL/SQL function which will compute and return
the reverse of a number.
set serveroutput on;
declare
a int;
c int;
n int;
rev int:=0;
r int;
// Defining function
function reverse_it( x IN int)
return int
as
z int;
// function code
Department of ECM 56
DataBaseManagemenSystems Lab
begin
n := x;
while (n > 0)
loop
r := mod(n, 10);
rev := (rev * 10) + r;
n := trunc(n / 10);
end loop;
z := rev;
return z;
end ;
BEGIN
a := 123456789;
c := reverse_it(a);
dbms_output.put_line('the reverse of number is ' || c);
END;
OUTPUT:
the reverse of number is 987654321
Department of ECM 57
DataBaseManagemenSystems Lab
EXPERIMENT 11
Description:
Department of ECM 58
DataBaseManagemenSystems Lab
OUTPUT:
Department of ECM 59
DataBaseManagemenSystems Lab
variable declarations;
constant declarations;
BEGIN
statement(s);
EXCEPTION
WHEN...
END
]
[EXCEPTION
WHEN built-in_exception_name_1 THEN
User defined statement (action) will be taken;
]
END;
OUTPUT:
Department of ECM 60
DataBaseManagemenSystems Lab
Department of ECM 61
DataBaseManagemenSystems Lab
EXPERIMENT 12
SOURCE CODE:
DECLARE
cursor c_emp is select ename, deptno, salary from emp1 order by salary desc;
ename1 emp1.ename%type;
deptno1 emp1.deptno%type;
salary1 emp1.salary%type;
BEGIN
open c_emp;
dbms_output.put_line('ENAME DEPTNO SALARY');
loop
fetch c_emp into ename1,deptno1,salary1;
exit when c_emp%notfound;
dbms_output.put_line(ename1 ||' ' ||deptno1||' ' || salary1);
Department of ECM 62
DataBaseManagemenSystems Lab
end loop;
close c_emp;
End;
OUTPUT:
Department of ECM 63
DataBaseManagemenSystems Lab
Experiment-13
Database Triggers:-
Database triggers are procedures that are stored in the database and are
implicitly
executed(fired) when the contents of a table are changed.
Use of Database Triggers:-
Database triggers support Oracle to provide a highly customized database
management
system. Some of the uses to which the database triggers can be put to customize
management information in Oracle are as follows:-
• A Trigger can permit DML statements against a table any if they are issued,
during regular business hours or on predetermined weekdays.
• A trigger can also be used to keep an audit trail of a table along with the
operation
performed and the time on which the operation was performed.
• It can be used to prevent invalid transactions.
• Enforce complex security authorizations.
How to apply DataBase Triggers:-
A trigger has three basic parts:-
1. A triggering event or statement.
2. A trigger restriction
3. A trigger action.
Types of Triggers:-
Using the various options , four types of triggers can be created:-
1. Before Statement Trigger:- Before executing the triggering statement, the
trigger action is executed.
2. Before Row Trigger:- Before modifying the each row affected by the
triggering statement and before appropriate integrity constraints, the trigger is
executed if
the trigger restriction either evaluated to TRUE or was not included.’
www.jntufastupdates.com
3. After Statement Trigger:- After executing the triggering statement and
applying
any deferred integrity constraints, the trigger action is executed.
4. After row Trigger:- After modifying each row affected by the triggering
statement and possibly applying appropriate integrity constraints, the trigger
action is executed for the current row if the trigger restriction either evaluates to
TRUE or was not included.
Syntax For Creating Trigger:-
The syntax for Creating the Trigger is as follows:-
Create or replace Trigger<Triggername> {Before,After} {Delete, Insert, Update } On
<Tablename> For Each row when Condition
Declare
Department of ECM 64
DataBaseManagemenSystems Lab
<Variable declarations>;
<Constant Declarations>;
Begin
<PL/SQL> Subprogram Body;
Exception
Exception Pl/SQL block;
End;
How to Delete a Trigger:-
The syntax for Deleting the Trigger is as follows:-
Drop Trigger <Triggername>;
.
Department of ECM 65
DataBaseManagemenSystems Lab
Experiment-14
For a given EMPLOYEE tables
Department of ECM 66
DataBaseManagemenSystems Lab
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE02‘,‘HEARN‘,‘BAKER‘,‘BANGALORE‘,‘M‘, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE03‘,‘EDWARD‘,‘SCOTT‘,‘MYSORE‘,‘M‘, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE04‘,‘PAVAN‘,‘HEGDE‘,‘MANGALORE‘,‘M‘, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE05‘,‘GIRISH‘,‘MALYA‘,‘MYSORE‘,‘M‘, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE06‘,‘NEHA‘,‘SN‘,‘BANGALORE‘,‘F‘, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSACC01‘,‘AHANA‘,‘K‘,‘MANGALORE‘,‘F‘, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSACC02‘,‘SANTHOSH‘,‘KUMAR‘,‘MANGALORE‘,‘M‘, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSISE01‘,‘VEENA‘,‘M‘,‘MYSORE‘,‘M‘, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSIT01‘,‘NAGESH‘,‘HR‘,‘BANGALORE‘,‘M‘, 500000);
Creating View
The query that defines the sales_staffview references only rows in department 5.
Furthermore, the CHECK OPTION creates the view with the constraint (named
sales_staff_cnst) that INSERT and UPDATE statements issued against the view
cannot result in rows that the view cannot select.
1. Creating Views (With and Without Check Option)
Department of ECM 67