Ii - Ii DBMS Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

DataBaseManagemenSystems 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

S.No. Name of the experiment Skill


Exercise – 1
Creation, altering and dropping of tables and inserting
1. Creating
rows into a table (use constraints while creating tables)
Tables
examples using SELECT command.
Exercise – 2
2. Queries (along with sub Queries) using ANY, ALL, IN, Queries
EXISTS, NOTEXISTS, UNION, INTERSET, Constraints.

Department of ECM 1
DataBaseManagemenSystems Lab

Example:- Select the roll number and name of the


student who secured fourth rank in the class.
Exercise – 3
3. Queries using Aggregate functions (COUNT, SUM, AVG, Queries
MAX and MIN), GROUP BY, HAVING and Creation and
dropping of Views.
Exercise – 4
Queries using Conversion functions (to_char,
to_number and to_date), string functions Queries using
4. (Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, conversion
initcap, length, substr and instr), date functions functions
(Sysdate, next_day, add_months, last_day,
months_between, least, greatest, trunc,round, to_char,
to_date)
Exercise – 5
Creation of a simple PL/SQL program which includes
declaration section, executable section and exception –
PL/SQL
5. Handling section (Ex. Student marks can be selected
Programs
from the table and printed for those who secured first
class and an exception can be raised if no records were
found).
Exercise – 6 Commit and
6. Insert data into student table and use COMMIT, Rollback
ROLLBACK and SAVEPOINT in PL/SQL block.
Exercise – 7
Develop a program that includes the features NESTED Programs
7.
IF, CASE and CASE expression. The program can be using Case
extended using the NULLIF and COALESCE functions.
Exercise – 8
Program development using WHILE LOOPS, numeric Programs
8. FOR LOOPS, nested loops using ERROR Handling, using Loops
BUILT –IN Exceptions, USE defined Exceptions, RAISE-
APPLICATION ERROR.
Exercise – 9
9. Programs development using creation of procedures, Procedures
passing parameters IN and OUT of PROCEDURES.
Exercise – 10
Program development using creation of stored Stored
10.
functions, invoke functions in SQL Statements and Functions
write complex functions.
Exercise – 11
11. Program development using creation of package Package
specification, package bodies, private objects, package
variables and cursors and calling stored packages.

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.

The four main categories of SQL statements are


as follows:

1.DML (Data Manipulation


Language) 2.
DDL (Data Definition Language) 3.
DCL (Data Control Language) 4.
TCL (Transaction Control
Language)

DML (Data Manipulation Language)

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.

DML statements include the following:

SELECT – select records from a table


INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records

DDL (Data Definition Language)

DDL statements are used to alter/modify a database or table structure and schema.
These statements handle the design and storage of database objects.

CREATE – create a new Table, database, schema


ALTER – alter existing table, column description
DROP – delete existing objects from database

Department of ECM 4
DataBaseManagemenSystems Lab

DCL (Data Control Language)

DCL statements control the level of access that users have on database objects.

GRANT – allows users to read/write on certain database objects


REVOKE – keeps users from read/write permission on database objects

TCL (Transaction Control Language)

TCL statements allow you to control and manage transactions to maintain the integrity
of data within SQL statements.

BEGIN Transaction – opens a transaction


COMMIT Transaction – commits a transaction
ROLLBACK Transaction – ROLLBACK a transaction in case of any error

SQL: create command

create is a DDL SQL command used to create a table or a database in relational database
management system.

Creating a Database

To create a database in RDBMS, create command is used. Following is the syntax,

CREATE DATABASE <DB_NAME>;

Example for creating Database


CREATE DATABASE Test;

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.

Following is the syntax,

Department of ECM 5
DataBaseManagemenSystems Lab

CREATE TABLE <TABLE_NAME>


(
column_name1 datatype1,
column_name2 datatype2,
column_name3 datatype3,
column_name4 datatype4
);

createtable command will tell the database system to create a new table with the given
table name and column information.

Example for creating Table


CREATE TABLE Student(
student_id INT,
name VARCHAR(100),
age INT);

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:

CREATE TABLE Test.Student(


student_id INT,
name VARCHAR(100),
age INT);

Most commonly used datatypes for Table columns

Here we have listed some of the most commonly used datatypes used for columns in
tables.

Datatype Use

INT used for columns which will store integer values.

FLOAT used for columns which will store float values.

DOUBLE used for columns which will store float values.

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).

DATE used for columns which will store date values.

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.

ALTER Command: Add multiple new Columns

Using ALTER command we can even add multiple new columns to any existing table.
Following is the syntax,

ALTER TABLE table_name ADD(


column_name1 datatype1,
column-name2 datatype2,
column-name3 datatype3);

Here is an Example for this,

ALTER TABLE student ADD(


father_name VARCHAR(60),
mother_name VARCHAR(60),
dob DATE);

The above command will add three new columns to the student table

ALTER Command: Add Column with default value

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,

ALTER TABLE table_name ADD(


column-name1 datatype1 DEFAULT some_value
);

Here is an Example for this,

Department of ECM 7
DataBaseManagemenSystems Lab

ALTER TABLE student ADD(


dob DATE DEFAULT '01-Jan-99'
);

The above command will add a new column with a preset default value to the table
student.

ALTER Command: Modify an existing Column

ALTER command can also be used to modify data type of any existing column. Following
is the syntax,

ALTER TABLE table_name modify(


column_name datatype
);

Here is an Example for this,

ALTER TABLE student MODIFY(


address varchar(300));

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.

ALTER Command: Rename a Column

Using ALTER command you can rename an existing column. Following is the syntax,

ALTER TABLE table_name RENAME


old_column_name TO new_column_name;

Here is an example for this,

ALTER TABLE student RENAME


address TO location;

The above command will rename address column to location.

ALTER Command: Drop a Column

ALTER command can also be used to drop or remove columns. Following is the syntax,

Department of ECM 8
DataBaseManagemenSystems Lab

ALTER TABLE table_name DROP(


column_name);

Here is an example for this,

ALTER TABLE student DROP(


address);

The above command will drop the address column from the table student

Truncate, Drop or Rename a Table

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,

TRUNCATE TABLE table_name

Here is an example explaining it,

TRUNCATE TABLE student;

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,

DROP TABLE table_name

Here is an example explaining it,

DROP TABLE student;

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

DROP DATABASE Test;

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,

INSERT INTO table_name VALUES(data1, data2, ...)

Lets see an example,

Consider a table student with the following fields.

s_id name age

INSERT INTO student VALUES(101, 'Adam', 15);

The above command will insert a new record into student table.

s_id name age

101 Adam 15

Department of ECM 10
DataBaseManagemenSystems Lab

Insert value into only specific columns


We can use the INSERT command to insert values for only some specific columns of a row.
We can specify the column names along with the values to be inserted like this,

INSERT INTO student(id, name) values(102, 'Alex');


The above SQL query will only insert id and name values in the newly inserted record.

Insert NULL value to a column


Both the statements below will insert NULL value into age column of the student table.
INSERT INTO student(id, name) values(102, 'Alex');
Or, INSERT INTO Student VALUES(102,'Alex', null);
The above command will insert only two column values and the other column is set to
null.
S_id S_Name age
101 Adam 15

102 Alex

Insert Default value to a column


INSERT INTO Student VALUES(103,'Chris', default)
S_id S_Name age

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.

INSERT INTO Student VALUES(103,'Chris')

Using UPDATE SQL command


Let's take an example of a real-world problem. These days, Facebook provides an option
for Editing your status update, how do you think it works? Yes, using the Update SQL
command.
Let's learn about the syntax and usage of the UPDATE command.

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

UPDATE student SET age=18 WHERE student_id=102;


S_id S_Name age

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.

Updating Multiple Columns


We can also update values of multiple columns using a single UPDATE statement.
UPDATE student SET name='Abhi', age=17 where s_id=103;
The above command will update two columns of the record which has s_id 103.

s_id name age


101 Adam 15

102 Alex 18

103 Abhi 17

UPDATE Command: Incrementing Integer Value


When we have to update any integer value in a table, then we can fetch and update the
value in the table in a single statement.
For example, if we have to update the age column of student table every year for every
student, then we can simply run the following UPDATE statement to perform the following
operation:

Department of ECM 12
DataBaseManagemenSystems Lab

UPDATE student SET age = age+1;


As you can see, we have used age = age + 1 to increment the value of age by 1.
NOTE: This style only works for integer values.
Using DELETE SQL command
using the Delete option, you can even delete a question asked by you. How do you think
that works? Yes, using the Delete DML command.

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

Delete all Records from a Table


DELETE FROM student;

The above command will delete all the records from the table student.

Delete a particular Record from a Table

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.

DELETE FROM student WHERE s_id=103;

The above command will delete the record where s_id is 103 from the table student.

S_id S_Name age

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

3 Aniseed Syrup 1 2 12 - 550 10


ml bottles

4 Chef Anton's Cajun 2 2 48 - 6 oz 22


Seasoning jars

5 Chef Anton's Gumbo 2 2 36 boxes 21.35


Mix

And a selection from the "OrderDetails" table:

Department of ECM 14
DataBaseManagemenSystems Lab

OrderDetailID OrderID ProductID Quantity

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40

SQL ANY Examples

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

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.

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:

Custo CustomerNa ContactName Address City PostalCod Country


merID me e

1 Alfreds Maria Anders Obere Str. Berlin 12209 Germany


Futterkiste 57

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados Constituci D.F.
y helados ón 2222

3 Antonio Antonio Mataderos México 05023 Mexico


Moreno Moreno 2312 D.F.
Taquería

4 Around the Thomas Hardy 120 London WA1 1DP UK


Horn Hanover
Sq.

5 Berglunds Christina Berguvsvä Luleå S-958 22 Sweden


snabbköp Berglund gen 8

IN Operator Examples

The following SQL statement selects all customers that are located in "Germany", "France"
and "UK":

Example

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');

Department of ECM 16
DataBaseManagemenSystems Lab

The following SQL statement selects all customers that are NOT located in "Germany",
"France" or "UK":

Example

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as
the suppliers:

Example

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);
The SQL EXISTS Operator
The EXISTS operator is used to test for the existence of any record in a subquery.
The EXISTS operator returns true if the subquery returns one or more records.

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;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate values, use
UNION ALL:
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

Department of ECM 17
DataBaseManagemenSystems Lab

SQL UNION Example

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;

SQL UNION ALL Example


The following SQL statement returns the cities (duplicate values also) from both the
"Customers" and the "Suppliers" table:
Example
SELECT City FROM Customers
UNION ALL
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

Using AVG() function


Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query to find average salary will be,
SELECT avg(salary) from Emp;
Result of the above query will be,
avg(salary)

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

Using COUNT() function


Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query to count employees, satisfying specified condition is,
SELECT COUNT(name) FROM Emp WHERE salary = 8000;
Result of the above query will be,
count(name)

Example of COUNT(distinct)
Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query is,
SELECT COUNT(DISTINCT salary) FROM emp;
Result of the above query will be,
count(distinct 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;

Using MAX() function


Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query to find the Maximum salary will be,
SELECT MAX(salary) FROM emp;
Result of the above query will be,
MAX(salary)

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;

Using MIN() function


Consider the following Emp table,
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000

Department of ECM 21
DataBaseManagemenSystems Lab

SQL query to find minimum salary is,


SELECT MIN(salary) FROM emp;
Result will be,
MIN(salary)

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;

Using SUM() function


Consider the following Emp table
eid name age salary

401 Anu 22 9000

402 Shane 29 8000

403 Rohan 34 6000

404 Scott 44 10000

405 Tiger 35 8000


SQL query to find sum of salaries will be,
SELECT SUM(salary) FROM emp;
Result of above query is,
SUM(salary)

41000

CREATE VIEW Statement

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.

Department of ECM 22
DataBaseManagemenSystems Lab

CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example: CREATE VIEW BrazilCustomers AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = "Brazil";
Updating a View:

A view can be updated with the CREATE OR REPLACE VIEW command.

CREATE OR REPLACE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Dropping a View:

A view is deleted with the DROP VIEW command.

Syntax: DROP VIEW view_name;

Eg. DROP VIEW BrazilCustomers;

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:

SELECT column1, column2, ...


FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

Department of ECM 23
DataBaseManagemenSystems Lab

ORDER BY DESC Example:

The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:

Eg. SELECT * FROM Customers


ORDER BY Country DESC;
ORDER BY Several Columns Example:

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

Queries using Conversion functions (to_char, to_number and to_date), string


functions(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr
and instr), datefunctions(Sysdate, next_day, add_months, last_day, months_between,
least, greatest, trunc,round, to_char, to_date)

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

These functions can be used on database columns.

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.

SELECT ROUND (unit_price) FROM product;

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.

Few of the character or text functions are as given below:

Function Name Return Value


LOWER (string_value) All the letters in 'string_value' is converted to lowercase.
UPPER (string_value) All the letters in 'string_value' is converted to uppercase.
INITCAP (string_value) All the letters in 'string_value' is converted to mixed case.
LTRIM (string_value, All occurrences of 'trim_text' is removed from the left of
trim_text) 'string_value'.
RTRIM (string_value, All occurrences of 'trim_text' is removed from the right of
trim_text) 'string_value' .
All occurrences of 'trim_text' from the left and right of
TRIM (trim_text FROM
'string_value' , 'trim_text' can also be only one character
string_value)
long .
Returns 'n' number of characters from 'string_value'
SUBSTR (string_value, m, n)
starting from the 'm' position.
LENGTH (string_value) Number of characters in 'string_value' in returned.
LPAD (string_value, n, Returns 'string_value' left-padded with 'pad_value' . The
pad_value) length of the whole string will be of 'n' characters.
RPAD (string_value, n, Returns 'string_value' right-padded with 'pad_value' . The
pad_value) length of the whole string will be of 'n' characters.
function concatenates two strings and returns the
CONCAT((string1,string2)
combined string.

For Example, we can use the above UPPER() text function with the column value as
follows.

SELECT UPPER (product_name) FROM product;

The following examples explains the usage of the above character or text functions

Function Name Examples Return Value


LOWER(string_value) LOWER('Good Morning') good morning
GOOD
UPPER(string_value) UPPER('Good Morning')
MORNING

Department of ECM 27
DataBaseManagemenSystems Lab

INITCAP(string_value) INITCAP('GOOD MORNING') Good Morning


LTRIM(string_value, trim_text) LTRIM ('Good Morning', 'Good) Morning
RTRIM ('Good Morning', '
RTRIM (string_value, trim_text) Good
Morning')
TRIM (trim_text FROM
TRIM ('o' FROM 'Good Morning') Gd Mrning
string_value)
SUBSTR (string_value, m, n) SUBSTR ('Good Morning', 6, 7) Morning
LENGTH (string_value) LENGTH ('Good Morning') 12
LPAD (string_value, n, pad_value) LPAD ('Good', 6, '*') **Good
RPAD (string_value, n, pad_value) RPAD ('Good', 6, '*') Good**
CONCAT((string1,string2) CONCAT('Happy',' coding') Happy coding

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.

Few date functions are as given below.

Function Name Return Value


ADD_MONTHS (date, n) Returns a date value after adding 'n' months to the date 'x'.
MONTHS_BETWEEN
Returns the number of months between dates x1 and x2.
(x1, x2)
Returns the date 'x' rounded off to the nearest century, year,
ROUND (x, date_format) month, date, hour, minute, or second as specified by the
'date_format'.
Returns the date 'x' lesser than or equal to the nearest century,
TRUNC (x, date_format) year, month, date, hour, minute, or second as specified by the
'date_format'.
NEXT_DAY (x, Returns the next date of the 'week_day' on or after the date 'x'
week_day) occurs.
It is used to determine the number of days remaining in a
LAST_DAY (x)
month from the date 'x' specified.
SYSDATE Returns the systems current date and time.

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

LAST_DAY( ) LAST_DAY ('01-Jun-19) 30-Jun-19


SYSDATE SYSDATE 15-JUL-19

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

TO_DATE () TO_DATE ('01-Jun-2008') 01-Jun-08(Sys date format)


NVL () NVL (null, 1) 1

Department of ECM 29
DataBaseManagemenSystems Lab

Experiment 5:

Creation of Simple PL/SQL Program which includes declaration section,


executable section and exception handling section (Ex. 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).

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.

PL/SQL Block structure:


DECLARE
declarations section;
BEGIN
executable command(s);
EXCEPTION
WHEN exception1 THEN
statement1;
WHEN exception2 THEN
statement2;
[WHEN others THEN]
/* default exception handling code */
END;

Displaying user Messages on the screen:

Department of ECM 30
DataBaseManagemenSystems Lab

Any programming tool requires a method through which messages can be


displayed to the user.
 dbms_output is a package that includes a number of procedure
and functions that accumulate information in a buffer so that it
can be retrieved later. These functions can also be used to display
message to the user.
 put_line: put a piece of information in the buffer followed by a end
of line marker.

Conditional control in PL/SQLSyntax:


IF <condition> THEN
<Action>
ELSEIF<condition>
<Action>
ELSE
<Action>
ENDIF;

The WHILE LOOP:


Syntax:
WHILE <condition>
LOOP
<Action>
END LOOP;
The FOR LOOP statement:
Syntax:
FOR variable IN [REVERSE] start—end
LOOP
<Action>
END LOOP;
Q1. WAP in PL/SQL for addition of two numbers.
declare
-- declare variable x, y and z of datatype number
x number;
y number;
z number;
begin
-- Here we Assigning 10 into x
x:=10;
-- Assigning 20 into x
y:=20;

Department of ECM 31
DataBaseManagemenSystems Lab

-- Assigning sum of x and y into z


z:=x+y;
--Print the Result
dbms_output.put_line('Sum is '||z);
end;

Output :
Sum is 30

Q2.WAP in PL/SQL to check the given number is even or odd.

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

Exception Handling in PL/SQL


An exception is an error which disrupts the normal flow of program
instructions. PL/SQL provides us the exception block which raises the
exception thus helping the programmer to find out the fault and resolve it.
There are two types of exceptions defined in PL/SQL
i. User defined exception.
ii. System defined exceptions.
Syntax to write an exception
WHEN exception THEN statement;

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.

1. Named system exceptions: They have a predefined name by the system


like ACCESS_INTO_NULL, DUP_VAL_ON_INDEX, LOGIN_DENIED etc.
the list is quite big.
So we will discuss some of the most commonly used exceptions:
create table student(sid int , sname varchar(20), marks int);
insert into student values(1, 'Suraj',100);
insert into student values(2, 'Praveen',97);
insert into student values(3, 'Jessie', 99);

a) NO_DATA_FOUND: It is raised WHEN a SELECT INTO statement


returns no rows.
For eg:
DECLARE
temp varchar(20);
BEGIN
SELECT sid into temp from student where sname='Robin';
exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR');
dbms_output.put_line('there is no name as');
dbms_output.put_line('Robin in Student table');
end;
/

OUTPUT:
ERROR
there is no name as Robin in Student table

Department of ECM 33
DataBaseManagemenSystems Lab

b) TOO_MANY_ROWS:It is raised WHEN a SELECT INTO statement


returns more than one row.

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)

2. User defined exceptions:


This type of users can create their own exceptions according to the need
and to raise these exceptions explicitly raise command is used.

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.

Using Savepoint and Rollback


Following is the table class,

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;

UPDATE class SET name = 'Abhijit' WHERE id = '5';

SAVEPOINT A;

INSERT INTO class VALUES(6, 'Chris');

SAVEPOINT B;

INSERT INTO class VALUES(7, 'Bravo');

SAVEPOINT C;

SELECT * FROM class;


NOTE: SELECT statement is used to show the data stored in the table.
The resultant table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
7 Bravo
Now let's use the ROLLBACK command to roll back the state of data to the savepoint B.
ROLLBACK TO B;

Department of ECM 38
DataBaseManagemenSystems Lab

SELECT * FROM class;


Now our class table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit
6 Chris
Now let's again use the ROLLBACK command to roll back the state of data to
the savepoint A
ROLLBACK TO A;

SELECT * FROM class;


Now the table will look like,
id name
1 Abhi
2 Adam
4 Alex
5 Abhijit

Insert data into student table and use COMMIT, ROLLBACK and SAVEPOINT
in PL/SQL block.

Create table stu(name varchar(10),branch varchar(10)); Insert

into stu values(‘sai’,’it’);

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:

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

Here we are going to see an example of Nested If –

Example of Nested- If Statement: Greatest of three number

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.

 CASE statement uses "selector" rather than a Boolean expression to


choose the sequence.
 The value of the expression in the CASE statement will be treated as
a selector.
 The expression could be of any type (arithmetic, variables, etc.)
 Each alternative is assigned with a certain pre-defined value (selector), and
the alternative with selector value that matches the conditional expression
value will get executed.
 Unlike IF-THEN-ELSIF, the CASE statement can also be used in SQL
statements.
 ELSE block in CASE statement holds the sequence that needs to be
executed when none of the alternatives got selected.

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.

Example 1: Arithmetic Calculation using Case

In this example, we are going to do arithmetic calculation between two numbers


55 and 5.

DECLARE

a NUMBER :=55;

Department of ECM 44
DataBaseManagemenSystems Lab
b NUMBER :=5;

arth_operation VARCHAR2(20) :='MULTIPLY';

BEGIN

dbms_output.put_line('Program started.' );

CASE (arth_operation)

WHEN 'ADD' THEN dbms_output.put_line('Addition of the numbers are: '|| a+b


);

WHEN 'SUBTRACT' THEN dbms_output.put_line('Subtraction of the numbers


are: '||a-b );

WHEN 'MULTIPLY' THEN dbms_output.put_line('Multiplication of the numbers


are: '|| a*b

);

WHEN 'DIVIDE' THEN dbms_output.put_line('Division of the numbers are:'||


a/b);

ELSE dbms_output.put_line('No operation action defined. Invalid 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:

SELECT NULLIF(100,100)FROM dual;

Result: NULL

SELECT NULLIF(100,200) FROM dual;


Result: 100

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 syntax for the COALESCE function in Oracle/PLSQL is:


COALESCE( expr1, expr2, ... expr_n )

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:

SELECT COALESCE( address1, address2, address3 ) result


FROM suppliers;

The above COALESCE function is equivalent to the following IF-THEN-ELSE


statement:

IF address1 is not null THEN


result := address1;

ELSIF address2 is not null THEN

Department of ECM 47
DataBaseManagemenSystems Lab

result := address2;

ELSIF address3 is not null THEN


result := address3;

ELSE
result := null;

END IF;

The COALESCE function will compare each value, one by one.

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;

FOR Loop with IN REVERSE keyword

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:= &range;
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.

Program on WHILE LOOP:


PL/SQL Program for Reverse of a Number

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;

PL/SQL Program to Reverse a String

declare
str1 varchar2(50):='&str';
str2 varchar2(50);
len number;
i number;

begin

Department of ECM 51
DataBaseManagemenSystems Lab
len:=length(str1);

for i in reverse 1..len


loop
str2:=str2 || substr(str1,i,1);
end loop;

dbms_output.put_line('Reverse of String is:'||str2);


end;

HANDLE the RAISE APPLICATION ERROR EXCEPTION

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

Enter value for sid: 101


old 2: v_sid student.sid%type:=&sid;
new 2: v_sid student.sid%type:=101;
the student is registered for 3courses

PL/SQL procedure successfully completed.

Department of ECM 52
DataBaseManagemenSystems Lab

Experiment 9

Aim: To develop programs using creation of procedures, passing parameters IN


and OUT of procedures
Procedures and Functions:
A subprogram is a program unit/module that performs a particular task. These
subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or
program which is called the calling program.
A subprogram can be created
At the schema level
Inside a package
Inside a PL/SQL block
Procedure to find minimum of two numbers:
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;

Output:
Minimum of (23, 45): 23
PL/SQL procedure successfully completed.

Recursive Function to find factorial of a given number:


DECLARE
num number;
factorial number;

FUNCTION fact(x number)


RETURN number
IS
f number;

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

PL/SQL procedure successfully completed.

Department of ECM 54
DataBaseManagemenSystems Lab
Experiment-10

Aim: Program development using creation of stored functions,


invoke functions in SQL Statements and write complex
functions.

Function can be used as a part of SQL expression i.e. we can use


them with select/update/merge commands. One most important
characteristic of a function is that, unlike procedures, it must return
a value.

CREATE OR REPLACE FUNCTION <function_name>


(<variable_name> IN <datatype>,
<variable_name> IN <datatype>,...)
RETURN <datatype> IS/AS
variable/constant declaration;
BEGIN
-- PL/SQL subprogram body;
EXCEPTION
-- Exception Handling block ;
END <function_name>;
function_name is for defining function's name and variable_name is the variable
name for variable used in the function.
CREATE or REPLACE FUNCTION is a keyword used for specifying the name of
the function to be created.
IN mode refers to READ ONLY mode which is used for a variable by which it will
accept the value from the user. It is the default parameter mode.
RETURN is a keyword followed by a datatype specifying the datatype of a value
that the function will return.
Most part of the above code is similar to the one used for defining a stored
procedure.
In the code below we have a program to demonstrate the use of function for
adding two numbers.
set serveroutput on;

CREATE OR REPLACE FUNCTION Sum(a IN number, b IN number) RETURN


Number IS
c number;
BEGIN
c := a+b;
RETURN c;
END;
OUTPUT

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

Aim: Program development using Creation of package specification, package


bodies, private objects, package variables and cursors, calling stored packages

Description:

Package: Package is a collection of procedure of function or both

STEP1: DECLARING PACKAGE

Defining Package Specification Syntax

CREATE[OR REPLACE] PACKAGE package_name


IS|AS
[variable_declaration ...]
[constant_declaration ...]
[exception_declaration ...]
[cursor_specification ...]
[PROCEDURE[Schema..] procedure_name
[(parameter {IN,OUT,INOUT} datatype [,parameter])]
]
[FUNCTION[Schema..] function_name
[(parameter {IN,OUT,INOUT} datatype [,parameter])]
RETURN return_datatype
]
END[package_name];

Department of ECM 58
DataBaseManagemenSystems Lab
OUTPUT:

STEP2: DECLARING PACKAGE BODY

Creating Package Body Syntax

CREATE[OR REPLACE] PACKAGE BODY package_name


IS|AS
[private_variable_declaration ...]
[private_constant_declaration ...]
BEGIN
[initialization_statement]
[PROCEDURE[Schema..] procedure_name
[(parameter [,parameter])]
IS|AS
variable declarations;
constant
declarations;
BEGIN
statement(s);
EXCEPTION
WHEN...
END
]
[FUNCTION[Schema..] function_name
[(parameter [,parameter])]
RETURN return_datatype
IS|AS

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:

STEP3: PROGRAM USING PROCEDURE IN THE PACKAGE

Department of ECM 60
DataBaseManagemenSystems Lab

Department of ECM 61
DataBaseManagemenSystems Lab

EXPERIMENT 12

AIM: Develop programs using features parameters in a cursor, FOR UPDATE


CURSOR, WHERE CURRENT of clause and CURSOR variables
Description:
Cursor:
Cursor is the work area which Oracle reserves for internal processing of SQL
statements. This work area is private for oracles reserved are called cursor.
In PL/SQL block SELECT statement can not return more than one row at a
time. So Cursor use to some group of rows (more than one row) for
implementing certain logic to get all the group of records.
Classification of CURSORS

1. Implicit Cursor or Internal Cursor : Manage for Oracle


itself or internal process itself.
2. Explicit Cursor or User-defined Cursor: Manage for
user/programmer or external processing.

CREATE TABLE EMP1 as follows

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

Perform the Following


1. Creating Views (With and Without Check Option),
2. Selecting from a View
3. Dropping Views,
SOLUTION:
SQL> CREATE TABLE EMPLOYEE (
SSN VARCHAR2 (20) PRIMARY KEY,
FNAME VARCHAR2 (20),
LNAME VARCHAR2 (20),
ADDRESS VARCHAR2 (20),
SEX CHAR (1),
SALARY INTEGER,
SUPERSSN REFERENCES EMPLOYEE (SSN),
DNO REFERENCES DEPARTMENT (DNO));
SQL> DESC EMPLOYEE;
Name Null? Type
----------------------------------------- -------- ----------------------------
SSN NOT NULL VARCHAR2(20)
FNAME VARCHAR2(20)
LNAME VARCHAR2(20)
ADDRESS VARCHAR2(20)
SEX CHAR(1)
SALARY NUMBER(38)
SUPERSSN VARCHAR2(20)
DNO NUMBER(38)
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSECE01‘,‘JOHN‘,‘SCOTT‘,‘BANGALORE‘,‘M‘, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY)
VALUES (‘RNSCSE01‘,‘JAMES‘,‘SMITH‘,‘BANGALORE‘,‘M‘, 500000);

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)

SQL> CREATE VIEW sales_staff AS


2 SELECT fname, ssn, dno
3 FROM employee
4 WHERE dno =5
5 WITH CHECK OPTION CONSTRAINT sales_staff_cnst;
View created.
2. Selecting from a View

SQL> select * from sales_staff;


3. Drop View

SQL>DROP VIEW sales_staff;

Department of ECM 67

You might also like