DBMS Practical Report
DBMS Practical Report
LAB REPORT
CSE DEPARTMENT
BATCH : 2019-23
SUBMITTED BY:
UE193099 SARTHAK AGGARWAL
UE193109 SUKHANDEEP SINGH
UE193119 UTTAM SINGH
SUPERVISED BY:
INDEX
Sno Content Page
No
1 Introduction to SQL: 1
A. Types of SQL commands:
DDL : Create, Rename, Alter,Describe, Truncate
DML : Insert, Update, Delete,Select
DCL : Grant ,Revoke
TCL : Commit, Rollback, Savepoint
B. Use of CREATE AS, USER_CONSTRAINTS,TAB, SPOOL ON
5 Subqueries
A. Nested queries ( Single row, Multi row)
B. Correlated queries
3
6 Joins:
A. Cross Join
B. Natural Join
C. Inner Join
D. Outer Join(left ,right and full)
7 Views
A. Introduction
B. Types: Materialised and View Resolution
C. Features/Advantages
D. CREATE, DROP VIEW( using single table, Multiple
Tables E. INSERT UPDATE DELETE IN VIEWS
8 Indexes
A. Introduction
B. Types: Unique, Duplicate, simple, Composite
C. CREATE, DROP INDEX ( on single column, multiple columns)
9 Sequence
A. Introduction
B. CREATE, DROP SEQUENCE
C. USING SEQUENCE TO INSERT VALUES IN COLUMN OF A
TABLE(ex employee id, student rollno etc)
D. ALTER SEQUENCE
10 Introduction to PL/SQL
A. Syntax of PL/SQL
B. Control structures in PL/SQL and their syntax
11 Subprograms in PL/SQL:
A. Introduction to Procedures
Syntax of Procedures
Write procedure for P1 to P7
B. Introduction to Functions
Syntax of Functions
Write function for P1 to P7
12 Cursors in PL/SQL
A. Introduction
B. Advantages and Disadvantages of cursor
C. Types of cursors:Implicit and Explicit Cursors
Program:To count the number of records using implicit
cursor.
Program:To display records of 5 least paid employees using
explicit cursor.
Program:To display records of 5 highest paid employees
using explicit cursor.
14 Exception Handling
A. System defined Exception handling
B. User defined Exception handling
C. Write Programs to demonstrate A and B
15 Package in PL/SQL
A. Introduction to Package
B. Package Specification
C. Package Body
D. WAP to Implement Package for your project
ANNEXURE 1
TABLE 1 : EMPLOYEE
TABLE 2 : DEPARTMENT
1.
Introduction:
SQL stands for Structured Query Language. SQL lets you access and manipulate databases
❖ SQL can execute queries against a database
❖ SQL can retrieve data from a database
❖ SQL can insert records in a database
❖ SQL can update records in a database
❖ SQL can delete records from a database
❖ SQL can create new databases
❖ SQL can create new tables in a database
❖ SQL can create stored procedures in a database
❖ SQL can set permissions on tables, procedures, and views
1. DDL
A data definition language (DDL) is used to create and modify the structure of database
objects in a database. These database objects include views, schemas, tables, indexes, etc.It
is used to establish and modify the structure of objects in a database by dealing with
descriptions of the database schema.
● CREATE
It is used to create a new table.
SYNTAX
CREATE TABLE table_name (
column1 datatype,
7
column2 datatype,
column3 datatype,
.... );
CREATE TABLE PROGRAMME (
PROGRAMME_ID varchar2(6) not null constraint programme_pk primary key,
Type varchar2(15),
Extra_FEES number,
Max_Enroll number
)
● RENAME
This command is used to set a new name for any existing table.
SYNTAX
RENAME TABLE `current_table_name` TO `new_table_name`;
● ALTER
An alter command modifies an existing database table. This command can add up
additional columns ,drop existing columns and even change the data type of columns
involved in a database table.
Syntax
1. ALTER TABLE table_name ADD column_name datatype;
2.ALTER TABLE table_name modify(
column_name datatype
);
ALTER TABLE CUSTOMER ADD WEIGHT number(2);
● DESCRIBE
DESCRIBE is used to describe tables, that’s why we use DESCRIBE or
DESC(both are the same) command to describe the structure of a table.
SYNTAX
DESCRIBE <table_name>;
OR
DESC <table_name>;
DESC TABLE PROGRAMME;
● DROP
A DROP command is used to delete objects such as a table, index or view. A DROP
statement cannot be rolled back, so once an object is destroyed, there’s no way to
recover it.
SYNTAX
DROP TABLE table_name;
DROP TABLE TAKES_MEMBERSHIP;
8
● TRUNCATE
Similar to DROP, the TRUNCATE statement is used to quickly remove all records from
a table. However, unlike DROP that completely destroys a table, TRUNCATE preserves
its full structure to be reused later.
SYNTAX
TRUNCATE TABLE table_name;
TRUNCATE TABLE SALARY;
● SELECT
It is used to retrieve data from a database.We can fetch either the entire table or the
columns that we want according to some specified rules. The data returned is stored in
a result table
SYNTAX
SELECT column1, column2, ...
FROM table_name
WHERE condition;
SELECT
SELECT GOAL
FROM CUSTOMER
WHERE CUSTOMER_ID=1029;
SYNTAX
GRANT privileges
ON object
TO user;
10
● REVOKE
It withdraws user’s access privileges given by using the GRANT command.
SYNTAX
REVOKE privilege-type
ON [ TABLE ] { table-Name | view-Name }
FROM grantees
11
TCL-Transaction Control Language
Transaction Control Language commands are used to manage transactions in the database.
These are used to manage the changes made by DML-statements. It also allows statements
to be grouped together into logical transactions.
● ROLLBACK: This command restores the database to the last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SYNTAX
ROLLBACK TO savepoint_name;
B.
CREATE AS- Used to create copy of an existing table
12
TAB- The SQL Query tab shows the query code to be sent to the SQL server when this
database operation file is executed. This is helpful to verify that the database operation does what
you expect it to do.
SPOOL ON-
Spool on/off
Log the output of a MaxL Shell session to a file. Send standard output, informational messages, error messages,
and/or warning messages generated by the execution of MaxL statements to a file.
If FILE-NAME does not exist, it is created. If FILE-NAME already exists, it is overwritten. If a directory path is not
specified for FILE-NAME, FILE-NAME is created in the current directory of the MaxL Shell. Directories cannot be
created using the spool command.
Message logging begins with spool on and ends with spool off.
14
Example
spool on to 'output.txt';
{MaxL statements}
spool off;
Sends output of MaxL statements to a file called output.txt, located in the current directory where the MaxL Shell
was invoked, or in eas\console\bin if the MaxL Script Editor is being used.
spool on to 'c:\hyperion\output.txt';
Sends output of MaxL statements to a file called output.txt, located in the pre-existing directory specified by an
absolute path.
spool on to '../../../output.txt';
Sends output of MaxL statements to a file called output.txt, located in the pre-existing directory specified by a
relative path. The file would be located three directories above the current directory, or three directories above
as\console\bin if the MaxL Script Editor is being used.
2.CONSTRAINTS
Constraints are the rules enforced on the data columns of a table. These are used to limit the
type of data that can go into a table. This ensures the accuracy and reliability of the data in
the database.
Constraints could be either on a column level or a table level. The column level constraints
are applied only to one column, whereas the table level constraints are applied to the whole
table.
● NOT NULL Constraint − Ensures that a column cannot have NULL value.
● DEFAULT Constraint − Provides a default value for a column when none is specified.
● UNIQUE Constraint − Ensures that all values in a column are different.
● PRIMARY Key − Uniquely identifies each row/record in a database table.
● FOREIGN Key − Uniquely identifies a row/record in any of the given database tables.
● CHECK Constraint − The CHECK constraint ensures that all the values in a column
satisfies certain conditions.
● INDEX − Used to create and retrieve data from the database very quickly.
Constraints can be specified when a table is created with the CREATE TABLE statement or
you can use the ALTER TABLE statement to create constraints even after the table is
created.
15
1. Primary key
Primary Key is a field which uniquely identifies each row in the table. If a field in
a table as primary key, then the field will not be able to contain NULL values as
well as all the rows should have unique values for this field.
example:
create table MANAGER (
EMP_ID varchar2(6) not null c
onstraint manager_pk primary key,
First_name varchar2(15) not n ull,
Last_name varchar2(15),
Phone_no number not null,
Address varchar2(25),
DOB date,
Grade number,
Qualification varchar2(25)
)
2. Foreign key
Foreign Key is a field in a table which uniquely identifies each row of a another table.
That is, this field points to the primary key of another table. This usually creates a kind
of link between the tables.
3. UNIQUE
This constraint helps to uniquely identify each rowin the table. i.e. for a particular
column, all the rows should have unique values. We can have more than one UNIQUE
column in a table.
create table TRAINER (
EMP_ID varchar2(6) not null constraint trainer_pk primary key,
First_name varchar2(15) not null,
Last_name varchar2(15),
Contact number not null,
Address varchar2(25),
DOB date,
Grade number,
Unique(First_name,Last_name),
Experience varchar2(10)
)
4. NOT NULL
If we specify a field in a table to be NOT NULL.Then the field will never accept null
value. That is, you will be not allowed to insert a new row in the table without specifying
any value to this field.
create table TRAINER (
EMP_ID varchar2(6) not null constraint trainer_pk primary key,
First_name varchar2(15) not null,
Last_name varchar2(15),
Contact number not null,
Address varchar2(25),
DOB date,
Grade number,
Unique(First_name,Last_name),
Experience varchar2(10)
)
Behaviors of Foreign Key Table
3. OPERATORS
An operator is a reserved word or a character used primarily in an SQL
statement WHERE clause to perform operation(s), such as comparisons and
arithmetic operations. These Operators are used to specify conditions in an SQL
statement
- (Subtraction) Subtracts right hand operand from left hand operand. a - b will give -10
/ (Division) Divides left hand operand by right hand operand. b / a will give 2
1 ALL-The ALL operator is used to compare a value to all values in another value set.
ANY-The ANY operator is used to compare a value to any applicable value in the list as
3
per the condition.
BETWEEN--The BETWEEN operator is used to search for values that are within a set of
4
values, given the minimum value and the maximum value.
EXISTS-The EXISTS operator is used to search for the presence of a row in a specified
5
table that meets a certain criterion.
IN-The IN operator is used to compare a value to a list of literal values that have been
6
specified.
19
LIKE-The LIKE operator is used to compare a value to similar values using wildcard
7
operators.
NOT-The NOT operator reverses the meaning of the logical operator with which it is
8
used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This is a negate operator.
UNIQUE--The UNIQUE operator searches every row of a specified table for uniqueness
11
(no duplicates).
Comparison Operators
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Show Examples
Checks if the values of two operands are equal or not, if yes then (a = b) is not
=
condition becomes true. true.
Checks if the values of two operands are equal or not, if values (a <> b) is
<>
are not equal then condition becomes true. true.
20
Checks if the value of left operand is greater than the value of (a > b) is not
>
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right
< (a < b) is true.
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the (a >= b) is not
>=
value of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than or equal to the (a <= b) is
<=
value of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is not less than the value of (a !< b) is
!<
right operand, if yes then condition becomes true. false.
Checks if the value of left operand is not greater than the value
!> (a !> b) is true.
of right operand, if yes then condition becomes true.
B.
a. STRING FUNCTIONS
TRIM TRIM(‘ ABC ‘) ‘ABC’ Remove the space character or other
specified characters either from the
start or end of a string.
b.Numeric functions
RESULT: one = 1
Returns the value of e (the base of natural logarithms) raised to the power n.
LN Natural logarithm. Computes the logarithm of its single argument, the base of which is e.
LOG Logarithm. log(n, m) takes two arguments, where n is the base, and m is the value you are taking
the logarithm of.
Log(10,1000) = 3
Mod(10,3) = 1
EQL uses the fmod floating point remainder, as defined in the C/POSIX standard.
The unary (one argument) version takes only one argument (the number to be rounded) and
drops the decimal (non-integral) portion of the input. For example:
ROUND(8.2) returns 8
ROUND(8.7) returns 9
The binary (two argument) version takes two arguments (the number to be rounded and a positive
or negative integer that allows you to set the number of spaces at which the number is rounded).
The binary version always returns a double:
● Positive second arguments correspond to the number of places that must be returned
after the decimal point. For example:
ROUND(123.4567, 3) returns 123.457
Negative second arguments correspond to the number of places that must be returned before the
decimal point. For example:
ROUND(123.4, -3) returns 0
25
SIGN Returns the sign of the argument as -1, 0, or 1, depending on whether n is negative, zero, or
positive. The result is always a double.
RESULT: x = -1, y = 0, z = 1
SELECT SQRT(9) AS x
RESULT: x = 3
TRUNC Returns the number n truncated to m decimal places. If m is 0, the result has no decimal point or
fractional part.
The unary (one argument) version drops the decimal (non-integral) portion of the input. For
example:
SELECT TRUNC(3.14159265) AS x
RESULT: x = 3
The binary (two argument) version allows you to set the number of spaces at which the number is
truncated. The binary version always returns a double. For example:
SELECT TRUNC(3.14159265, 3) AS y
RESULT: y = 3.141
SIN(3.14159/6) = 0.499999616987256
26
COS(3.14159/3) = 0.500000766025195
TAN(3.14159/4) = 0.999998673205984
Power(2,8) = 256
TO_DURATION Casts a string representation of a timestamp into a number of milliseconds so that it can be used
as a duration.
c. Aggregate functions
Function Description
LISTAGG Aggregate strings from multiple rows into a single string by
concatenating them
d. Date functions
CURRENT_DATE ELECT
S 06-AUG-2017 Return the current
CURRENT_DATE FROM 19:43:44 date and time in
dual the session time
zone
SESSIONTIMEZONE ELECT
S 07:00
- Get the session
SESSIONTIMEZONE time zone
FROM dual;
SYSDATE YSDATE
S 01-AUG-17 Return the current
system date and
time of the
operating system
where the Oracle
Database resides.
SYSTIMESTAMP ELECT
S 01-AUG-17 Return the system
SYSTIMESTAMP FROM 01.33.57.929000 date and time
dual; 000 PM -07:00 that includes
fractional
seconds and time
zone.
TO_CHAR O_CHAR(
T unday, January
S Convert a D ATE
DATE'2017-01-01', 01, 2017 or an INTERVAL
'DL' ) value to a
character string in
a specified
format.
TRUNC RUNC(DATE
T 1-JUL-17
0 Return a date
'2017-07-16', 'MM') truncated to a
specific unit of
measure.
30
4 ORDERBY
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some databases sort the query results in an ascending order by
default.
Syntax
The basic syntax of the ORDER BY clause is as follows −
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
SELECT *
FROM TRAINER
ORDERBY Salary DESC;
SELECT *
FROM CUSTOMER
ORDERBY First_name;
GROUP BY
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into
groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER
BY clause.
SYNTAX
The basic syntax of a GROUP BY clause is. The GROUP BY clause must follow the conditions in the WHERE
clause and must precede the ORDER BY clause if one is used.
1.
SELECT Goal,Count (*)
FROM CUSTOMER
GROUPBY Goal;
2.
31
SELECT Experience,Count (*)
FROM TRAINER
GROUPBY Experience
3.
SELECT type,Count (*) FROM Equipment
GROUPBY Type
HAVING
The HAVING Clause enables you to specify conditions that filter which group results appear in the results.
The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions
on groups created by the GROUP BY clause.
Syntax
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
SELECT Grade
FROM TRAINER
GROUPBY Grade
HAVING Count(*)>3
SELECT Goal
FROM CUSTOMER
GROUPBY Goal
HAVING COUNT(*)>3
LIKE
SELECT *
FROM CUSTOMER
WHERE First_name
LIKE '_b%';
IN
SELECT *
FROM CUSTOMER
WHERE Goal IN ('Fat Loss','Muscle Gaining');
SELECT *
FROM MANAGER
WHERE Qualification IN ('BCA','BBA');
32
BETWEEN
SELECT *
FROM CUSTOMER
WHERE weight
BETWEEN 70 AND 90
SELECT *
FROM TRAINER
WHERE Experience
BETWEEN 0 AND 4
5.
SUBQUERIES
A subquery is a SQL query nested inside a larger query.
● The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or
inside another subquery.
● A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
SYNTAX
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name FROM table_name WHERE ... );
33
A single row subquery returns zero or one row to the outer SQL statement. wecan place a subquery
in a WHERE clause, a HAVING clause, or a FROM clause of a SELECT statement.
Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN,
ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.
CORRELATED SUBQUERY
Correlated subqueries are used for row-by-row processing. Each subquery is executed once for
every row of the outer query.
A correlated subquery is evaluated once for each row processed by the parent statement. The parent
statement can be a SELECT, UPDATE, or DELETE statement.
6.JOINS
CROSS JOIN
The SQL CROSS JOIN produces a result set which is the number of rows in the first table multiplied by the
number of rows in the second table if no WHERE clause is used along with CROSS JOIN.This kind of result is
called a Cartesian Product.
34
If WHERE clause is used with CROSS JOIN, it functions like an INNER JOIN.
An alternative way of achieving the same result is to use column names separated by commas after SELECT
and mentioning the table names involved, after a FROM clause.
Syntax:
SELECT *
FROM table1
CROSS JOIN table2;
SELECT C.CUSTOMER_ID,C.First_name,C.Phone_no,C.Goal,P.PROGRAMME_ID,P.TYPE
FROM CUSTOMER AS C
CROSS JOIN PROGRAMME AS P;
NATURAL JOIN
The SQL NATURAL JOIN is a type of JOIN THAT is structured in such a way that columns with the same
name of associated tables will appear once only.
Natural Join
- The associated tables have one or more pairs of identically named columns.
- The columns must be the same data type.
- Don’t use ON clauses in a natural join.
Syntax:
SELECT *
FROM table1
NATURAL JOIN table2;
SELECT MM.EMP_ID,M.First_name,M.Grade,M.Salary
FROM MANAGER AS M
NATURAL JOIN MANAGES_MEMEBERSHIP AS MM
INNER JOIN
The INNER JOIN selects all rows from both participating tables as long as there is a match between the
columns. An SQL INNER JOIN is the same as a JOIN clause, combining rows from two or more tables.
Syntax:
SELECT *
FROM table1 INNER JOIN table2
ON table1.column_name = table2.column_name;
OR
SELECT *
FROM table1
35
JOIN table2
ON table1.column_name = table2.column_name;
SELECT MM.EMP_ID,M.First_name,M.Grade,M.Salary
FROM MANAGER AS M
INNER JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID
OUTER JOINS
The SQL OUTER JOIN returns all rows from both the participating tables which satisfy the join condition
along with rows which do not satisfy the join condition.
The subtypes of SQL OUTER JOIN
The SQL LEFT JOIN (specified with the keywords LEFT JOIN and ON) joins two tables and fetches all
matching rows of two tables for which the SQL-expression is true, plus rows from the first table that do not
match any row in the second table.
SELECT *
FROM table1
LEFT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;
SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.email,M.Salary
FROM MANAGER AS M
LEFT JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID
The SQL RIGHT JOIN, joins two tables and fetches rows based on a condition, which is matching in both the
tables ( before and after the JOIN clause mentioned in the syntax below) , and the unmatched rows will also be
available from the table written after the JOIN clause ( mentioned in the syntax below ).
Syntax:
SELECT *
FROM table1
RIGHT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;
SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.email,M.Salary
FROM MANAGER AS M
RIGHT JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID
36
In SQL the FULL OUTER JOIN combines the results of both left and right outer joins and returns all
(matched or unmatched) rows from the tables on both sides of the join clause.
Syntax:
SELECT *
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;
SELECT MM.EMP_ID,M.First_name,M.Phone_no,M.Grade,M.Salary
FROM MANAGER AS M
FULL OUTER JOIN MANAGES_MEMEBERSHIP AS MM
ON M.EMP_ID=MM.EMP_ID
7.VIEWS
A view is nothing more than a SQL statement that is stored in the database with an associated
name. A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
● Structure data in a way that users or classes of users find natural or intuitive.
● Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
● Summarize data from various tables which can be used to generate reports.
Creating Views
Database views are created using the CREATE VIEW statement. Views can be created from a
single table, multiple tables or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you use them in a
normal SQL SELECT query.
Example
37
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example to create a view from the CUSTOMERS table. This view would be used to
have customer name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS
SELECT name, age
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is
an example for the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;
This would produce the following result.
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
+----------+-----+
Updating a View
A view can be updated under certain conditions which are given below −
● The SELECT clause may not contain the keyword DISTINCT.
● The SELECT clause may not contain summary functions.
● The SELECT clause may not contain set functions.
● The SELECT clause may not contain set operators.
● The SELECT clause may not contain an ORDER BY clause.
● The FROM clause may not contain multiple tables.
● The WHERE clause may not contain subqueries.
● The query may not contain GROUP BY or HAVING.
● Calculated columns may not be updated.
● All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So, if a view satisfies all the above-mentioned rules then you can update that view. The following
code block has an example to update the age of Ramesh.
SQL > UPDATE CUSTOMERS_VIEW
SET AGE = 35
WHERE name = 'Ramesh';
This would ultimately update the base table CUSTOMERS and the same would reflect in the view
itself. Now, try to query the base table and the SELECT statement would produce the following
result.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Dropping Views
Obviously, where you have a view, you need a way to drop the view if it is no longer needed. The
syntax is very simple and is given below −
DROP VIEW view_name;
8. INDEXES
Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very similar to
an index in the back of a book.
For example, if you want to reference all pages in a book that discusses a certain topic, you first
refer to the index, which lists all the topics alphabetically and are then referred to one or more
specific page numbers.
An index helps to speed up SELECT queries and WHERE clauses, but it slows down data input,
with the UPDATE and the INSERT statements. Indexes can be created or dropped with no effect on
the data.
Creating an index involves the CREATE INDEX statement, which allows you to name the index, to
specify the table and which column or columns to index, and to indicate whether the index is in an
ascending or descending order.
Indexes can also be unique, like the UNIQUE constraint, in that the index prevents duplicate entries
in the column or combination of columns on which there is an index.
Single-Column Indexes
A single-column index is created based on only one table column. The basic syntax is as follows.
CREATE INDEX index_name
ON table_name (column_name);
Unique Indexes
Unique indexes are used not only for performance, but also for data integrity. A unique index does
not allow any duplicate values to be inserted into the table. The basic syntax is as follows.
CREATE UNIQUE INDEX index_name
on table_name (column_name);
Composite Indexes
A composite index is an index on two or more columns of a table. Its basic syntax is as follows.
CREATE INDEX index_name
on table_name (column1, column2);
Whether to create a single-column index or a composite index, take into consideration the column(s)
that you may use very frequently in a query's WHERE clause as filter conditions.
Should there be only one column used, a single-column index should be the choice. Should there be
two or more columns that are frequently used in the WHERE clause as filters, the composite index
would be the best choice.
Implicit Indexes
Implicit indexes are indexes that are automatically created by the database server when an object is
created. Indexes are automatically created for primary key constraints and unique constraints.
You can check the INDEX Constraint chapter to see some actual examples on Indexes.
9 SEQUENCE
A sequence is a set of integers 1, 2, 3, ... that are generated in order on demand. Sequences are
frequently used in databases because many applications require each row in a table to contain a
unique value and sequences provide an easy way to generate them.
This chapter describes how to use sequences in MySQL.
Example
Try out the following example. This will create a table and after that it will insert a few rows in this
table where it is not required to give a record ID because its auto-incremented by MySQL.
mysql> CREATE TABLE INSECT
-> (
-> id INT UNSIGNED NOT NULL AUTO_INCREMENT,
-> PRIMARY KEY (id),
-> name VARCHAR(30) NOT NULL, # type of insect
-> date DATE NOT NULL, # date collected
-> origin VARCHAR(30) NOT NULL # where collected
);
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO INSECT (id,name,date,origin) VALUES
-> (NULL,'housefly','2001-09-10','kitchen'),
-> (NULL,'millipede','2001-09-10','driveway'),
-> (NULL,'grasshopper','2001-09-10','front yard');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM INSECT ORDER BY id;
+----+-------------+------------+------------+
| id | name | date | origin |
+----+-------------+------------+------------+
| 1 | housefly | 2001-09-10 | kitchen |
| 2 | millipede | 2001-09-10 | driveway |
| 3 | grasshopper | 2001-09-10 | front yard |
+----+-------------+------------+------------+
3 rows in set (0.00 sec)
42
Obtain AUTO_INCREMENT Values
The LAST_INSERT_ID( ) is an SQL function, so you can use it from within any client that
understands how to issue SQL statements. Otherwise PERL and PHP scripts provide exclusive
functions to retrieve auto-incremented value of last record.
PERL Example
Use the mysql_insertid attribute to obtain the AUTO_INCREMENT value generated by a query. This
attribute is accessed through either a database handle or a statement handle, depending on how
you issue the query. The following example references it through the database handle.
$dbh->do ("INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')");
my $seq = $dbh->{mysql_insertid};
PHP Example
After issuing a query that generates an AUTO_INCREMENT value, retrieve the value by calling the
mysql_insert_id( ) function.
mysql_query ("INSERT INTO INSECT (name,date,origin)
VALUES('moth','2001-09-14','windowsill')", $conn_id);
$seq = mysql_insert_id ($conn_id);
10.
A. PL/SQL SYNTAX
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and
defines all variables, cursors, subprograms, and other elements to be used in
the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a
2
mandatory section. It consists of the executable PL/SQL statements of the
program. It should have at least one executable line of code, which may be just
a NULL command to indicate that nothing should be executed.
44
Exception Handling
3
This section starts with the keyword EXCEPTION. This optional section contains
exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other
PL/SQL blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Delimiter Description
45
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
46
.. Range operator
B. CONTROL STRUCTURES
PL/SQL programming language provides the following types of decision-making statements. Click
the following links to check their detail.
IF - THEN statement
IF-THEN-ELSE statement
IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.
Case statement
Like the IF statement, the CASE statement selects one sequence of statements to
execute.
4
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression whose value is used to select one of
several alternatives.
48
5 The searched CASE statement has no selector, and it's WHEN clauses contain search
conditions that yield Boolean values.
nested IF-THEN-ELSE
6 You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or
IF-THEN-ELSIF statement(s).
PL/SQL provides the following types of loop to handle the looping requirements. Click the following
links to check their detail.
1 In this loop structure, sequence of statements is enclosed between the LOOP and the
END LOOP statements. At each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.
2 Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
3 Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
EXIT statement
1 The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
50
CONTINUE statement
2 Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.
GOTO statement
3 Transfers control to the labeled statement. Though it is not advised to use the GOTO
statement in your program.
11. PROGRAMS:
A. PROCEDURES:
begin
n:=val;
i := 2;
-- Assigning 1 to temp
temp := 1;
if temp = 1
then
dbms_output.put_line(n|| ' is prime');
else
dbms_output.put_line(n||' is not prime');
end if;
end;
begin
n:=val;
52
i := 2;
-- Assigning 1 to temp
temp := 1;
if temp = 1
then
dbms_output.put_line(n|| ' is prime');
else
dbms_output.put_line(n||' is not prime');
end if;
end;
for i in 1..series_length
LOOP
temp:=fir+sec;
fir:=sec;
sec:=temp;
dbms_output.put_line(sec);
END LOOP;
END;
53
P5: To generate factorial of a given number
t := t
||''
||l;
END LOOP;
IF t = s THEN
dbms_output.Put_line(t
||''
||' is palindrome');
ELSE
dbms_output.Put_line(s
||''
||' is not palindrome');
END IF;
END;
B. FUNCTIONS
P1: To check if a year is a leap or not .
create or replace NONEDITIONABLE function leap_year_func (
year in number
)
return VARCHAR
is
res varchar(5);
begin
IF MOD(year, 4)=0
AND
MOD(year, 100)!=0
OR
MOD(year, 400)=0 THEN
res :='true';
ELSE
res :='false';
END IF;
return res;
end;
-- Assigning 1 to temp
temp := 1;
if temp = 1
then
return (n || ' is prime');
else
return (n || ' is not prime');
end if;
end;
begin
n:=val;
i := 2;
56
-- Assigning 1 to temp
temp := 1;
if temp = 1
then
return (n || ' is prime');
else
return (n || ' is not prime');
end if;
end;
for i in 1..series_length
LOOP
temp:=fir+sec;
fir:=sec;
sec:=temp;
res:= res||sec||',';
END LOOP;
return res;
END;
57
t := t ||'' ||l;
END LOOP;
IF t = s THEN
return(t ||'' ||' is palindrome');
ELSE
return(s||'' ||' is not palindrome');
END IF;
END;
12. CURSORS
A. introduction
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds
is referred to as the active set.
You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors −
● Implicit cursors
● Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with the
FORALL statement. The following table provides the description of the most used attributes −
%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
60
The following program will update the table and increase the salary of each customer by 500 and
use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
62
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
• Using Cursor, we can perform row by row processing so we can perform row wise validation or
operations on each row.
• Cursors can provide the first few rows before the whole result set is assembled. Without using cursors,
the entire result set must be delivered before any rows are displayed by the application. So, using a cursor,
better response time is achieved.
• If we make updates to us without using cursors in your application then we must send separate SQL
statements to the database server to apply the changes. This can cause the possibility of concurrency problems
if the result set has changed since it was queried by the client. In turn, this raises the possibility of lost updates.
So using cursor, better concurrency Control can be achieved.
• Cursors can be faster than a while loop but at the cost of more overhead.
Disadvantages:
• Cursor in SQL is a temporary work area created in the system memory; thus, it occupies memory from
your system that may be available for other processes. So occupies more resources and temporary storage.
• Each time when a row is fetched from the cursor it may result in a network round trip. This uses much
more network bandwidth than the execution of a single SQL statement like SELECT or DELETE etc that
makes only one round trip.
• Repeated network round trips can degrade the speed of the operation using the cursor
C.
Program:To count the number of records using implicit
cursor.
IN our database, salary is determined by the grade, so, in the following programs we sort by grade.
dbms_output.put_line(e_name||' '||e_id);
end loop;
close exp_cursor;
end;
/
dbms_output.put_line(e_name||' '||e_id);
end loop;
close exp_cursor;
64
end;
/
13. TRIGGERS
TRIGGERS are stored programs that are fired by Oracle engine automatically when DML
Statements like insert, update, delete are executed on the table or some events occur.
The code to be excecuted in case of a trigger can be defined as per the requirement. You
can choose the event upon which the trigger needs to be fired and the timing of the
execution. The purpose of trigger is to maintain the integrity of information on the
database.
Benefits of Triggers
Following are the benefits of triggers.
DECLARE
66
<Declaration part>
BEGIN
<Execution part>
EXCEPTION
<Exception handling part>
END;
Syntax Explanation:
● The above syntax shows the different optional statements that are present in trigger
creation.
● BEFORE/ AFTER will specify the event timings.
● INSERT/UPDATE/LOGON/CREATE/etc. will specify the event for which the trigger
needs to be fired.
● ON clause will specify on which object the above-mentioned event is valid. For
example, this will be the table name on which the DML event may occur in the case
of DML Trigger.
● Command "FOR EACH ROW" will specify the ROW level trigger.
● WHEN clause will specify the additional condition in which the trigger needs to fire.
● The declaration part, execution part, exception handling part is same as that of the
other PL/SQL blocks. Declaration part and exception handling part are optional.
Oracle has provided two clauses in the RECORD-level trigger to hold these values. We
can use these clauses to refer to the old and new values inside the trigger body.
● :NEW – It holds a new value for the columns of the base table/view during the
trigger execution
● :OLD – It holds old value of the columns of the base table/view during the trigger
execution
This clause should be used based on the DML event. Below table will specify which
clause is valid for which DML statement (INSERT/UPDATE/DELETE).
INSTEAD OF Trigger
"INSTEAD OF trigger" is the special type of trigger. It is used only in DML triggers. It is
used when any DML event is going to occur on the complex view.
Consider an example in which a view is made from 3 base tables. When any DML event
is issued over this view, that will become invalid because the data is taken from 3 different
tables. So in this INSTEAD OF trigger is used. The INSTEAD OF trigger is used to modify
the base tables directly instead of modifying the view for the given event.
Example 1: In this example, we are going to create a complex view from two base table.
Then we are going to see how the INSTEAD OF trigger is used to issue UPDATE the
location detail statement on this complex view. We are also going to see how the :NEW
and :OLD is useful in triggers.
Step 1) Creating table 'emp' and 'dept' with appropriate columns
68
Code Explanation
Output
Table Created
Step 2) Now since we have created the table, we will populate this table with sample
values and Creation of Views for the above tables.
69
BEGIN
INSERT INTO DEPT VALUES(10,‘HR’,‘USA’);
INSERT INTO DEPT VALUES(20,'SALES','UK’);
INSERT INTO DEPT VALUES(30,‘FINANCIAL',‘JAPAN');
COMMIT;
END;
/
BEGIN
INSERT INTO EMP VALUES(1000,'XXX5,15000,'AAA',30);
INSERT INTO EMP VALUES(1001,‘YYY5,18000,‘AAA’,20) ;
INSERT INTO EMP VALUES(1002,‘ZZZ5,20000,‘AAA',10);
COMMIT;
END;
/
Code Explanation
Output
Code Explanation
Output
View created
ZZZ HR USA
YYY SALES UK
BEGIN
UPDATE guru99_emp_view SET location='FRANCE' WHERE employee_name=:'XXX’;
COMMIT;
END;
/
Code Explanation
● Code line 34-38: Update the location of "XXX" to 'FRANCE'. It raised the exception
because the DML statements are not allowed in the complex view.
Output
ORA-06512: at line 2
Step 5)To avoid the error encounter during updating view in the previous step, in this step
we are going to use "instead of trigger."
Code Explanation
● Code line 39: Creation of INSTEAD OF trigger for 'UPDATE' event on the
'guru99_emp_view' view at the ROW level. It contains the update statement to
update the location in the base table 'dept'.
● Code line 44: Update statement uses ':NEW' and ': OLD' to find the value of
columns before and after the update.
Output
Trigger Created
Step 6) Update of view after instead-of trigger. Now the error will not come as the "instead
of trigger" will handle the update operation of this complex view. And when the code has
executed the location of employee XXX will be updated to "France" from "Japan."
BEGIN
UPDATE guru99_emp_view SET location='FRANCE' WHERE employee_name='XXX';
COMMIT;
END;
/
Code Explanation:
Output:
ZZZ HR USA
YYY SALES UK
Compound Trigger
The Compound trigger is a trigger that allows you to specify actions for each of four timing
points in the single trigger body. The four different timing point it supports is as below.
It provides the facility to combine the actions for different timing into the same trigger.
74
AFTER STATEMENT IS
BEGIN
<Execution part>;
END AFTER STATEMENT;
END;
Syntax Explanation:
75
● The above syntax shows the creation of 'COMPOUND' trigger.
● Declarative section is common for all the execution block in the trigger body.
● These 4 timing blocks can be in any sequence. It is not mandatory to have all these
4 timing blocks. We can create a COMPOUND trigger only for the timings which are
required.
Example 1: In this example, we are going to create a trigger to auto-populate the salary
column with the default value 5000.
BEGIN
INSERT INTO EMP VALUES(1004,‘CCC’,15000,‘AAA’,30);
COMMIT;
END;
/
76
SELECT * FROM emp WHERE emp_no=1004;
Code Explanation:
● Code line 2-10: Creation of compound trigger. It is created for timing BEFORE
ROW- level to populate the salary with default value 5000. This will change the
salary to default value '5000' before inserting the record into the table.
● Code line 11-14: Insert the record into 'emp' table.
● Code line 16: Verifying the inserted record.
Output:
Trigger created
Triggers can be enabled or disabled. To enable or disable the trigger, an ALTER (DDL)
statement needs to be given for the trigger that disable or enable it.
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
The above program displays the name and address of a customer whose ID is given. Since there is
no customer with ID value 8 in our database, the program raises the run-time exception
NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
78
Exceptions are raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer by using the command RAISE.
Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined
exception. In the next section, we will give you an example on raising a user-defined exception. You
can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE statement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the user
enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
79
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a
SELECT INTO statement returns no rows. The following table lists few of the important pre-defined
exceptions −
Oracle
Exception SQLCODE Description
Error
15. Packages
I n PL/SQL, a package is a schema object that contains definitions for a group of related
functionalities. A package includes variables, c
onstants, c
ursors, e
xceptions, p
rocedures, functions,
and subprograms. It is compiled and stored in the Oracle Database.
Typically, a package has a specification and a body. A package specification is mandatory while the
package body can be required or optional, depending on the package specification.
Package specification
The package specification declares the public objects that are accessible from outside the package.
If a package specification whose public objects include cursors and subprograms, then it must have
a body which defines queries for the cursors and code for the subprograms.
Package body
A package body contains the implementation of the cursors or subprograms declared in the package
specification. In the package body, you can declare or define private variables, cursors, etc., used only
by package body itself.
A package body can have an initialization part whose statements initialize variables or perform other
one-time setups for the whole package.
A package body can also have an exception-handling part used to handle exceptions.
82
Why using PL/SQL packages
The package is a powerful feature of PL/SQL that you should use it in any project. The following are
the advantages of the package:
It means that you can enhance the code in the body of the package without affecting other
dependent packages or applications.
PL/SQL package concept is simple but powerful. They allow you to encapsulate the code and make
your application easier to develop and maintain.
83
CUSTOMER_METHODS
Doc
Details
Grants
References
Dependencies
Code
package CUSTOMER_METHODS
as
procedure add_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null
84
);
procedure update_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null
);
procedure delete_row (
p_CUSTOMER_ID in VARCHAR2 default null
);
end CUSTOMER_METHODS;
CUSTOMER_METHODS
Doc
Details
Grants
References
Dependencies
Code
)
is
begin
insert into CUSTOMER
( CUSTOMER_ID, LAST_NAME, ADDRESS, FIRST_NAME, GOAL, EMAIL_ID, DOB, HEIGHT,
WEIGHT, PHONE_NO)
values
( p_CUSTOMER_ID, p_LAST_NAME, p_ADDRESS, p_FIRST_NAME, p_GOAL, p_EMAIL_ID,
p_DOB, p_HEIGHT, p_WEIGHT, p_PHONE_NO);
end add_row;
procedure update_row (
p_CUSTOMER_ID in VARCHAR2 default null
,p_LAST_NAME in VARCHAR2 default null
,p_ADDRESS in VARCHAR2 default null
,p_FIRST_NAME in VARCHAR2 default null
,p_GOAL in VARCHAR2 default null
,p_EMAIL_ID in VARCHAR2 default null
,p_DOB in DATE default null
,p_HEIGHT in NUMBER default null
,p_WEIGHT in NUMBER default null
,p_PHONE_NO in NUMBER default null
)
is
begin
update CUSTOMER
set LAST_NAME=p_LAST_NAME, ADDRESS=p_ADDRESS, FIRST_NAME=p_FIRST_NAME,
GOAL=p_GOAL, EMAIL_ID=p_EMAIL_ID, DOB=p_DOB, HEIGHT=p_HEIGHT, WEIGHT=p_WEIGHT,
PHONE_NO=p_PHONE_NO
where
(CUSTOMER_ID = p_CUSTOMER_ID);
end update_row;
procedure delete_row (
p_CUSTOMER_ID in VARCHAR2 default null
)
is
begin
delete CUSTOMER
where
CUSTOMER_ID = p_CUSTOMER_ID;
end delete_row;
end CUSTOMER_METHODS;
86
16. QUERRIES:
OUTPUT
OUTPUT
87
3 Give the total salary paid to each job within each dept.
SELECT DEPT_NO,JOB,SALARY FROM EMPLOYEE ORDER BY DEPT_NO;
OUTPUT
4 Give total, max, min, avg salary of employee job wise for dept number and
display rows having avg salary greater than 1,00,000
SELECT * FROM (SELECT SUM(SALARY), AVG(SALARY) AVER, MAX(SALARY),
MIN(SALARY),JOB FROM EMPLOYEE WHERE DEPT_NO IN(1,2)
GROUP BY
JOB)WHERE AVER >100000;
OUTPUT
88
5 Give name, salary of employees having salary greater than the minimum salary of
Department ML
SELECT EMP_NAME,SALARY FROM EMPLOYEE WHERE SALARY > ( SELECT
MIN(SALARY) FROM EMPLOYEE WHERE DEPT_NO = (SELECT DEPTT_NO F
ROM
DEPARTMENT WHERE DEPTT_NAME='RESEARCH'))
OUTPUT
OUTPUT
OUTPUT
OUTPUT
OUTPUT-
90
10 List the name of employee who do the same job and get the salary greater
than salary of employee ID as E008.
SELECT EMP_NAME FROM EMPLOYEE WHERE JOB=(SELECT JOB F ROM EMPLOYEE
WHERE EMP_ID='E012') AND SALARY>(SELECT SALARY FROM EMPLOYEE WHERE
EMP_ID='E012');
OUTPUT
11 List the name and salary of the employee who get salary greater than the
average salary of department Research
SELECT EMP_NAME FROM EMPLOYEE W HERE SALARY > (SELECT AVG(SALARY) FROM EMPLOYEE
LEFT OUTER JOIN DEPARTMENT ON EMPLOYEE.DEPT_NO=DEPARTMENT.DEPTT_NO WHERE
DEPTT_NAME='RESEARCH');
OUTPUT
13 List name of employee who have at least one person reporting to them.
OUTPUT
92
14 Name of employee salary less than minimum salary of HR department and
are not of HR department.
SELECT EMP_NAME FROM EMPLOYEE W HERE SALARY > (SELECT MIN(SALARY)
FROM EMPLOYEE WHERE DEPT_NO = (SELECT DEPTT_NO FROM DEPARTMENT WHERE
DEPTT_NAME='HR')) AND DEPT_NO !=(SELECT DEPTT_NO FROM DEPARTMENT
WHERE DEPTT_NAME='HR');
OUTPUT
function)
OUTPUT-
OR WITHOUT AGGREGATE
93
OUTPUT-
OUTPUT-
OR WITHOUT AGGREGATE
OUTPUT-
94
END