0% found this document useful (0 votes)
36 views20 pages

Understanding Functional Dependencies and Normalization

unit 4 ,5

Uploaded by

vidhyag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views20 pages

Understanding Functional Dependencies and Normalization

unit 4 ,5

Uploaded by

vidhyag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-IV

FUNCTIONAL DEPENDENCIES
o The Functional Dependencies are constraints on the set of legal relations. It
defines the relationship between the attributes in a relation. If A and B are
attributes of the relation R, B is functionally dependent of A (represented as
A→B), if each value of A is associated with exactly one value of B.
o It is a property of the meaning or semantics of the attributes in a relation. The
semantics indicates how attributes relate to one another, and specify the
functional dependencies between attributes. When a functional dependency is
present, the dependency is specified as a constraint between the attributes.
o The Determinant refers to the attribute or group of attributes on the left-hand
side of the arrow of a functional dependency. When a functional dependency
exists, the attribute or group of attributes on the left-hand side of the arrow is
called the determinant.

Example:

<$> The EMPLOYEE relation consists of two attributes. They are emp_name and
emp_no. If the values of the EMPLOYEE relation represent the set of all possible
values for emp_name and emp_no attributes then the following dependencies hold:
emp_name→emp no
emp_no→ emp name
<$> The set of all possible values for attributes of a relation and consequently hold for all
time, to ignore all trivial functional dependencies. A dependency is trivial if it is
impossible for it not to be satisfied. A dependency is trivial if and only if, the right-hand
side is a subset of the left-hand side. The trivial dependencies for the above relation
EMPLOYEE include:
❖ empno, empname -> empname
❖ emp_no, emp name -> emp no
<$> The main characteristics of functional dependencies that we use in normalization are:
❖ They have a one-to-one relationship between attribute(s) on the left-and
right-hand side of a dependency.
❖ They hold for all time.
❖ They are nontrivial
<$> For each functional dependency, the users ensure that all the attributes on the right-
hand side are functionally dependent on the determinant on the left-hand side.

Inference Rules for Functional Dependencies:

The set of all functional dependencies that are implied by a given set of functional
dependencies X is called the closure of X, written X+.
The set of rules to help compute X + from X. A set of inference rules, called Armstrong's
axioms, specifies how new functional dependencies can be inferred from given ones.
The Armstrong's axioms are as follows:
❖ Reflexivity. If B is a subset of A, then A~> B.
❖ Augmentation. If A->B, then A, C-> B, C.
❖ Transitivity. If A->B and B-> C, then A->C.
(A, B, and C be subsets of the attributes of the relation R)
To simplify the above rules by using the additional rules:
❖ Self-determination. A->A.
❖ Decomposition. If A->B, C, then A->B and A->C.
❖ Union. If A->B and A->C, then A~>B, C.
❖ Composition. If A->B and C->D then A, C -> B, D.

Reflexivity and self-determination state that a set of attributes always determines


any of its subsets or itself.
Augmentation states that adding the same set of attributes to both the left-and right-
sides of a dependency results in another valid dependency. Transitivity states that
functional dependencies are transitive.
The Decomposition states that we can remove attributes from the right-hand side of
a dependency (We can decompose A->B, C, D functional dependency into the set of
dependencies A-> B, A-> C and A-> D). The Union states that combine a set of
dependency into a single functional dependency. The composition is more general
than union and states that we can combine a set of non-overlapping dependencies to
form another valid dependency.
For each set of attributes A, we can determine the set A+ of attributes that are
functionally determined by A based on F. A+ is called the closure of A under F.
NORMALIZATION
■ It is the formal process for deciding which attributes should be grouped together in a
relation. In this process we analyze and decompose the complex relations and transform
them into smaller, simpler, and well-structured relations. It is used to avoid unnecessary
duplication of data. .
♦ It is the process of successive reduction of a given set of relations to a better form.
A normal form is a state of a table that results from applying simple rules regarding
functional dependencies to that table. It consists of several normal forms.
 First Normal Form (1NF) →The multi-valued attributes (called repeating groups)
should be removed, i.e. elimination of repeating groups.
 Second Normal Form (2NF) →The partial functional dependencies have to removed,
i.e. elimination of redundant data.
 Third Normal Form (3NF) →The transitive dependencies have to be removed,
[Link] of columns not dependent on the key.
 Boyce-Codd Normal Form (BCNF) →The remaining anomalies that result from
functional dependencies are removed.
 Fourth Normal Form (4NF) → Multi-valued dependencies are removed, i.e. isolation
of independent multiple relationships.
 Fifth Normal Form (5NF) →Any remaining anomalies are removed. In this normal
form we isolate semantically related multiple relationships.
FIRST NORMAL FORM
1. Discuss about 1NF. (Part-B)
❖ The First Normal Form (1NF) is a relation in which the intersection of each row and
column contains one and only value.
❖ To transform the unnormalized table to first normal form, we identify and remove the
repeating groups within the table. A repeating group is a set of columns that store
similar information that repeats in the same table. Consider the following table, which
contains the contact tracking information.
Create table contacts (contactid integer not null, l_name varchar(20) not null,
f_name varchar(20), contact_datel date, contact_desc1 varchar(50), contact_date2 date,
contact_desc2 varchar(50));
Contacts conversation
Contact-id Contact_id
L_name Contact_date
F_name Contact_desc

Figure: contacts-conversation relationship


❖ The above data structure contains a repeating group of the date and description of two
conversations. To eliminate the repeating group, the group is moved to another table,
which is then related to the parent table. The primary key of the parent table (contacted)
is stored in the second table. Moving the repeating group into another table allows any
number of conversations to be recorded and searched easily.
■ Create table contacts (contact_id integer not null, l_name varchar(20) not null,
f_name varchar(20));
■ Create table conversation(contact_id integer not null, contact_date date,
contact_desc varchar(50));
SECOND NORMAL FORM (2NF)
1. Explain about Second Normal Form. (Part-B)
• It is based on the concept of full functional dependency. Full functional dependency
indicates that if A and B are attributes of a relation, B is fully funtionally dependent on
A, if B is functionally dependent on A, but not on any proper subset of A.
. A relation in the first normal form will be in the second normal form if one of following
conditions is satisfied:
o The primary key consists of only one attribute (field or column).
o No non-key attributes exist in the relation. All the attributes in the. relation are
components of the primary key.
o Every non-key attribute is functionally dependent on the full set of primary key
attributes.
• Consider the following table, which contains the employee information
Create table employee (emp_no integer not null, l_name varchar(20) not null,
f_name varchar(20), dept_code integer, description varchar(50));
. The above table contains redundant data, namely the department description, which
depends only on the dept_code and does not vary base d on the value of the emp_no,
which is the primary key of the table.

employee
emp_no department
l_name dept_code
f_name
description
dept_code

Figure: employee_department Relationship

THIRD NORMAL FORM

1. Explain about 3NF. (Part-B)


❖ A relation is in Third Normal Form (3NF) if it is in second normal form and when no
transitive dependencies exist. Transitive dependency is a condition where A, B and C are
attributes such that if
A→B and B→ C, then C is transitively dependent on A via B. Transitive dependency is a
type of functional dependency. Consider the following functional dependencies:
■ emp_no → department and department → dept_head
❖ The transitive dependency emp_no → dept_head exists via the department attribute. A
transitive dependency in a relation is a functional dependency between two or more non-
key attributes. The columns in each table should be a group of columns in which the data
in each column contributes to the description of each row in the table. For a given row
with a unique key, each column appearing in that row should contribute to the description
of that row. Consider the following table contacts, which contains the following fields:
♦ Create table contacts (contact_id integer not null, l_name varchar(20) not null,
f_name varchar(20), company_name varchar(20), company_location
varchar(50));

❖ In the above relation contact_id is the primary key, so that all the remaining attributes are
functionally dependent on this attribute. However, there is a transitive dependency-
companylocation is dependent on company_name and company_name is functionally
dependent on contacted. There are update anomalies in the contacts table as follows:

Insertion Anomaly. A new company cannot be insertion to the contacts table until a
contact person has been assigned to that company.
Deletion Anomaly. If a company that has only one contact person is deleted from the
table, we lose the information about the company, as the company information is
associated with that person.
Modification Anomaly. If a company changes its location, we will have to make the
change in all the records whenever the company name appears.
contacts
company
contact_id
Company_id
l_name
company_name
f_name
company_location
Company_id

Figure: contacts_company relationship

BOYCE-CODD NORMAL FORM (BCNF)


1. Explain about BCNF. (Part-B)
❖ A relation is in BCNF if and only if every determinant is a candidate key. To test whether
a relation
is in BCNF, we identify all the determinants and make sure that they are candidate
keys.
❖ A determinant is an attribute or a group of attributes on which some other attribute is
fully functionally dependent. The BCNF is based on functional dependencies that
take into account all candidate keys in a relation.
❖ Consider 'A' and 'B' are attributes in relation R, 'B' is functionally dependent on 'A'
(denoted by A→ B), if each value of 'A' is associated with exactly one value of 'B'.
The contacts tables, the attributes l _ n a m e , f_name and company_id are functionally
dependent on contact_id. These dependencies are expressed as follows:
Contact_id →l_name and contact_id → f_name

Contact_id→ company_id and contact_id→{l_name, f_name,

company_id}
❖ The left-hand side and the right-hand side of a functional dependency are sometimes
called the determinant and dependent, respectively. The determinant and the
dependent are set of attributes.
Comparison of 3NF and BCNF:
❖ The difference between 3NF and BCNF is that for a functional dependency A→ B,
the 3NF allows this dependency in a relation i f ' B ' is a primary-key attribute and 'A'
is not a candidate key, where as BCNF the 'A' must be a candidate key. The BCNF is
a stronger form of the 3NF, such that every relation in BCNF is also in the 3NF. A
relation in the 3NF is not necessarily in BCNF. The three design goals for relational-
database design are:
 BCNF or 3NF.
 Lossless Join.
 Dependency Preservation.
FOURTH NORMAL FORM
1. Explain about 4NF. (Part-B)
O A table is in the Fourth Normal Form (4NF) if it is in BCNF and does not have any
independent multi-valued parts of the primary key. This normal form is related to the
concept of a Multivalued Dependency (MVD). A relation schema R is in 4NF with
respect to a set of D of functional and
multivalued dependencies if, for all multivalued dependencies in D + of the form α→β,
where
α R , and β R, at least one of the following holds:
■ α β is a trivial functional dependency.
■ α is a superkey for schema R.
Multivalued Dependencies:
O The new form of constraint is multivalued dependency. It is used to define a normal form
for relation schemas. This normal form called Fourth Normal Form (4NF) is more
restrictive than BCNF.
Example:
Consider the table employee that has attributes Name, Project and Hobby. A row in the
employee table represents the fact that an employee works for a project and has a hobby.
But an employee can work in more than one project and can have more than one project
and can have more than one hobby. The employee projects and hobbies are independent
of one another.

Name Project Hobby


Alexis Microsoft Reading
Alexis Oracle Mtisic
Mathews Intel Movies
Mathews Sybase Riding
O The above table (relation) has two MVDs- (Name, Project) and (Name, Hobby). To resolve
this by decomposing the employee table into two tables that satisfies the 4NF.

Name Project
Name Hobby
Alexis Microsoft
Alexis Reading
Alexis Oracle
Alexis Music
Mathews Intel
Mathews Movies
Mathews Sybase
Mathews Riding
p F
F

contacts company Phone /


contact id contact id contact id
lname companyname Phonenumber
fname companylocation

Figure: contacts_company_phone relationship

FIFTH NORMAL FORM (5NF)


1. Explain about 5NF. (Part-B)
❖ It is a relation that has no join dependency. Join dependency is a type of dependency. In
a relation R with subsets of the attributes of R denoted as A, B,...., Z, a relation R
satisfies a join dependency if and only if, every legal value of R is equal to the join of its
projections on A,B,...,Z.
❖ Consider the chemical analysis labs, which test products of various companies. Three
tables exist lab, product, and company. Companies can offer one or more products, labs
can test one or more products from one or more companies, a product can be tested in
one or more labs, and can be offered by one or more companies. If a lab is equipped to
analyze a product from a given company, this can be recorded in a table with the
following structure.
■ Create table l a b p r o d u c t c o m p a n y ( l a b _ i d integer not null,
product_id integer not null, company_id integer not null);
❖ The table contains three foreign keys expressing two relationships: the relationship
between labs and products and that between labs and companies.
❖ A lab can test the same product for all companies who offer a given product, the
following structure will be better:
■ Create table labproduct (lab_id integer not null, product_id integer not
null);
■ Create table labcompany (lab id integer not null, product_id integer not
null);
❖ This allows the products that a given lab can test to be recorded and the companies where
products can be tested by a lab to be recorded with fewer entries.

DENORMALIZATION
The normalization need not always improve database
performance. So sometimes we will have to
denormalizes the tables.
 It is the process of increasing redundancy in the database either for convenience or to
improve performance. Proper denormalization takes place after a model has been
fully normalized.
 In the real word, with live data, demanding users and real demands on performance
and ease of use, this flexibility is fundamental to success.
 The normalization is analysis, not design. Design encompasses issues, particularly
related to performance, ease of use, maintenance, and straightforward completion of
business tasks, things that are unaccounted for in normalization.

UNIT-IV COMPLETED

UNIT-V
PL/SQL
HISTORY OF PL/SQL
❖ The PL/SQL version 1.0 was introduced with Oracle 6.0 in 1991. Version 1.0 had
very limited capabilities. It was for batch processing.
❖ The versions 2.0, 2.1, and 2.2 has the following features:
■ The transaction control statements SAVEPOINT, ROLLBACK, and
COMMIT.
■ The DML statements INSERT, DELETE, and UPDATE. -
■ The extended data types Boolean, BINARYINTEGER, PL/SQL records,
and PL/SQL tables.
■ Built-in functions-character, numeric, conversion, and date functions.
■ Built-in packages.
■ The control structures sequence, selection, and looping.
■ Database access through work areas called cursors.
■ Error handling.
■ Modular programming with procedures and functions.
■ Stored procedures, functions, and packages.
■ Programmer-defined subtypes.
❖ DDL support through the DBMS SQL package.
❖ The PL/SQL wrapper.
❖ The DBMS JOB job scheduler.
❖ File I/O with the UTF FILE package.
❖ The PL/SQL version 8.0, also known as PL/SQL8, came with Oracle8, the
"Object-relational" database software.

EXCEPTIONS
The errors in PL/SQL are known as exceptions. It occurs when
an unwanted situation arises during the exception of a
program.
o When an exception occurs, control of the current program block shifts to
another section of the program, known as the exception section, to handle
exceptions. If the exception handler exists, it is performed.
o If the exception handler does not exist in the current block, control propagates
to the outer blocks. PL/SQL provides ways to trap and handle errors, and it is
possible to create PL/SQL programs with full protection against errors.
The syntax of an anonymous block is given below:
DECLARE
Declaration of constants, variables, cursors, and exceptions
BEGIN
/* Exception is raised here. */
EXCEPTION
/* Exception is trapped here. */
END;

General Syntax:
EXCEPTION
WHEN exceptionnamel [OR exceptionname2,...] THEN
Executable statements
[WHEN exceptionname3 [OR exceptionname4,...]
THEN
Executable statements]
[WHEN OTHERS THEN
Executable statements]

Write Short Notes on Nested Record. (Part-B)

❖ The PL/SQL records are similar in structure to rows in the database table. They
consist of components of any scalar type, PL/SQL record type, or PL/SQL table type.
These components are known as fields, and they have their own values.
❖ It is based on a cursor, a table's row, or a user-defined record type. A record can be
explicitly declared based on a cursor or a table.
CURSOR Cursorname IS
SELECT query;
Recordname CursorName%ROWTYPE;
❖ A record can also be based on another composite data type called TABLE.

Creating a PL/SQL Record:

❖ To create a user-defined record by the following ways:


■ Create a RECORD type
■ Declare a record with that RECORD type

General Syntax:
TYPE recordtypename IS RECORD
(fieldnamel datatype|variabIe%TYPE|[Link]%TYPE|
table%ROWTYPE[[NOT NULL]:=|DEFAULT Expression]
[, fieldname2... , FieldName3...];
recordname recordtypename;

Example 1:
TYPE employeerectype IS RECORD
(elast VARCHAR2(15), (esal NUMBER(8,2));
employee_rec employee_rectype;
❖ In the above declaration employee_rectype is the user-defined RECORD type. The
record employee_rec is a record declared with the user-defined record type
employee_rectype.

Example 2:
❖ It is also declared with the %TYPE attribute.
TYPE employee_rectype IS RECORD
(eid NUMBER(4) NOT NULL:=123,
(esal [Link]%TYPE);
employee_rec employee_rectype;
❖ The not null constraint can be used for any field to prevent Null values, but that field
must be initialized with a value.
Referencing Fields in a Record:
❖ The fields in a record are referenced with the record name as a qualifier.
[Link]
❖ The recordname and field name are joined by a dot(.)
■ [Link]
Working With Records:

❖ To assign values to a record from columns in a row by using the SELECT statement or
the FETCH statement. The order of fields in a record must match the order of columns
in the row. A record can be assigned to another record if both records have the same
structure.
❖ A record can be set to NULL, and all fields will be set to NULL.
■ Example: Employee_rec:=NULL;
❖ A record declared with %ROWTYPE has the same structure as the table's row.
■ Emp_rec employee%ROWTYPE;
❖ The emp_rec assumes the structure of the EMPLOYEE table. The fields in emp_rec
take their column names and their data types from the table.

Nested Records:
❖ To create a nested record by including a record into another record as a field. A nested
record is a record used as a field in another record. The record containing another
record is called the enclosing record.
Example:
DECLARE
TYPE address_rectype IS RECORD
(first VARCHAR(15), street VARCHAR2(25));
TYPE all_address_rectype IS RECORD
(home_address address rectype);
address_rec all_address_rectype;
❖ In the above example all_address_rectype nests address_rectype as a field type. The
nesting record makes code more readable and easier to maintain.
PROCEDURES

1. Explain about Procedures with Example. (Part-C)


Write down the General Syntax of a Procedure. (Part-A)
List out the Types of Parameters (Part-A)
Write short Notes on Actual and Formal Parameters. (Part-B)

❖ A procedure is a named PL/SQL program block that can perform one or more tasks. A
procedure is the building block of modular programming.

General Syntax:
CREATE (OR REPLACE] PROCEDURE
Procedurename [(Parameterl,
[,Parameter2...])]
IS
[Constant/variable declarations]
BEGIN
Executable statements
[EXCEPTION
exception handling statement]
END [procedurename];
❖ The above syntax procedurename is a user-supplied name. The parameter list has the
names of parameters passed to the procedure by the calling program as well as the
information passed from the procedure to the calling program. The local constants and
variables are declared after the reserved word IS.
❖ The executable statements are written after BEGIN and before EXCEPTION or END.
There must be at least one executable statement in the body. The reserved word
EXCEPTION and the exception-handling statements are optional.
Calling a Procedure:
❖ A call to the procedure is made through an executable PL/SQL statement. The
procedure is called by specifying its name along with the list of parameters (if any) in
parenthesis. The call statement ends with a semicolon.
General Syntax:
procedurename[(parameterl,....)];
Procedure Header:
❖ The procedure definition that comes before the reserved word IS is called the procedure
header. The procedure header contains the name of the procedure and the parameter list
with data types.

Example:
CREATE OR REPLACE PROCEDURE monsal
(vsal IN [Link]%TYPE)
❖ The parameter list in the header contains the name of a parameter along with its type.
Procedure Bodv:
❖ It contains declaration, executable, and exception-handling sections. The declaration
and exception-handling sections are optional. The executable section contains action
statements, and it must contain at least one.
❖ It stats after the reserved word IS. If there is no local declaration, IS is followed by the
reserved word BEGIN. The body ends with the reserved word END.

Parameters:
❖ It is used to pass values back and forth from the calling environment to the oracle server.
The values passed are processed and/or returned with a procedure execution. These are
three types of
parameters: IN, OUT, and IN OUT.
Parameter Type U se
IN Passes a value into the program; read-only type of value; it cannot be
changed; default parameter type. Example: constants, literals and
expressions.
OUT Passes a value back from the program; write-only type of value; cannot
assign a default value. If a program is successful value is assigned.
Example: variable
IN OUT Passes a value in and returns a value back; value is read from and then
written to.
Example: variable

Actual and Formal Parameters:


❖ The parameters passed in a call statement are called the actual parameters. The
parameter names in the header of a module are called the formal parameters. The actual
parameters and their matching formal parameters must have the same data type.
❖ In a procedure call, the parameters are passed without data types. The procedure header
contains formal parameters with data types, but the size of the data type is not required.
Procedure Call: Search_emp(543, last)
Procedure Header: PROCDURE SEARCH_EMP(EMPNO IN NUMBER,
LAST OUT VARCHAR2)

Actual and Formal Parameters

Matching Actual and Formal Parameters:


❖ There are two different ways in PL/SQL to link formal and actual parameters:
❖ In positional notation, the forma) parameter is linked with an actual parameter
implicitly by position. Positional notation is more commonly used for parameter
matching.
❖ In named notation, the formal parameter is linked with actual parameters
explicitly by name. The formal parameter and actual parameters are linked the
call statement with the symbol =>.

General Syntax:
❖ formalparametername => argumentvalue
Example:
❖ EMPNO => 543
❖ To execute this procedure from the SQL*Plus environment (SQL> prompt) with the
EXECUTE command.
Example: SQL> EXECUTE dependent_info
Example:
SQL> CREATE OR REPLACE PROCEDURE SEARCH_EMP (EMPID IN NUMBER,
LAST OUT VARCHAR2, FIRST OUT VARCHAR2)
IS
BEGIN
SELECT LNAME,FNAME INTO LAST,FIRST FROM EMPLOYEE5 WHERE
EMPLOYEEID=EMPID;
EXCEPTION
WHEN OTHERS THEN [Link](EMPID);
END SEARCH EMP;

Procedure with Parameters

SQL> DECLARE
VLAST [Link]%TYPE;
VFIRST [Link]%TYPE;
VID [Link]
%TYPE :=&EMP_ID;
BEGIN
SEARCH_EMP(VID,VLAST,VFIRST);
IF VLAST IS NOT NULL THEN
DBMS_OUTPUT.PUT_LINE(VID);
DBMS_OUTPUT,PUT_LINE(VLAST||’ ‘||
VFIRST); END I F ;
END;
FUNCTIONS

1. Explain about Functions. (Part-C)


List out the Characteristics of Functions (Part-A)
■ A function is a named PL/SQL block. It is also a stored block. The main difference
between a function and a procedure is that a function always returns a value to the
calling block.

Characteristics of Functions:
❖ A function can be passed zero or more parameters of IN, OUT and IN OUT types.
❖ A function must have an explicit RETURN statement in the executable section to return
a value.
■ The data type of the return value must be declared in the function header.
■ A function cannot be executed as a stand-alone program.
General syntax:
CREATE [OR REPLACE] FUNCTION functional name
[(parameterl [, parameter2„..])]
RETURN Datatype
IS
[Constant |Variable declarations]
BEGIN
executable statements
RETURN returnvalue
[EXCEPTION
Exception_handling statements
RETURN returnvalue]
END [functionname];
❖ The RETURN statement does not have to be the last statement in the body of a function.
The body may contain more than one RETURN statement, but only one is executed with
each function call.
Function Header:
❖ The function header comes before the reserved word IS. The header contains the name of
the function, the list of parameters (if any), and the RETURN data type.
Function Body:
❖ The body of a function must contain at least one
executable statement.
RETURN Data Types:
❖ A function can return a value with a scalar data type, such as VARCHAR2, NUMBER,
BINARY INTEGER, or BOOLEAN. It can also return a composite or complex data type,
such as PL/SQL table, a PL/SQL record, a nested table, VARRAY or LOB.
Calling a Function:
❖ A function is called by mentioning its name along with its parameters (if any).
Example:
vsalary:=get_salary(&emp_id);
❖ In the above example, the function call, the function get_salary is called from an
assignment statement with the substitution variable emp_id as its actual parameter. The
function returns the employee's salary, which is assigned to the variable vsalary.
Example:
SQL> CREATE OR REPLACE FUNCTION GET_DEPTNAME(DEPTID1 IN
NUMBER) RETURN VARCHAR2 IS
VDEPTNAME VARCHAR(12);
BEGIN
SELECT DEPTNAME INTO VDEPTNAME FROM DEPT5 WHERE
DEPTID=DEPTID1;
RETURN VDEPTNAME;
END GET_DEPTNAME;
Functions with Parameters
Function Call:
SQL> DECLARE
VDEPTID [Link]%TYPE;
VDEPTNAME VARCHAR2(12);
VEMPID [Link]%TYPE:=&EMP_ID;
BEGIN
SELECT DEPTID INTO VDEPTID FROM EMPLOYEES WHERE
EMPLOYEEID=VEMPID;
VDEPTNAME:=GET_DEPTNAME(VDEPTID);
DBMS_OUTPUT.PUT_LINE( VEMPID);
DBMS_OUTPUT.PUT_LINE(VDEPTNAME);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(VEMPID);
END;
❖ The function returns the department name back to the calling block. The calling block
then prints the employee's information along with the department name.
Calling a Function from an SQL Statement:
❖ A stored function block can be called from an SQL statement.
Example: SELECT get deptname(10) FROM dual;
PACKAGES
1. Explain about Packages with Example. (Part-B)
Write down the Syntax for Package. (Part-A)
What is Package? (Part-A)
A package is a collection of PL/SQL objects. The objects in a package are grouped
within BEGIN and END blocks. A package may contain objects from the following list:
 Cursors
 Scalar variables
 Composite variables
 Constants
 Exception names
 TYPE declarations for records and tables Procedures
 Functions
 Oracle has many built-in packages. Example: DBMSOUTPUT. The objects in a
package can be declared as public objects, which can be referenced from outside
or as private objects, which are known only to the package.
 When an object in the package is referenced for the first time, the entire package
is loaded into memory. All package elements are available from that point on,
because the entire package stays in memory. This one-time loading improves
performance and is very useful when the functions and procedures in it are
accessed frequently.
Structure of a Package:
A package has a specification and a body. The package specification tells us how to call
different modules within a package.
Package Specification:
 A package specification does not contain any code, but it does contain information about
the elements of the package.
 It contains definitions of functions and procedures declarations of global or public
variables, and anything else that can be declared in a PL/SQL block’s declaration
section. The objects in the specification section of a package are called public objects.
General Syntax:
CREATE [OR REPLACE] PACKAGE
packagename
IS
[constant, variable and type declarations]
[exception declarations]
[cursor specification]
[function specification]
[procedure specification]
END [packagename];
Examplel:
Package team
IS players constant integer:=12;
player_on EXCEPTION;
FUNCTION team_average(points IN NUMBER, players IN NUMBER) RETURN
NUMBER; End team;
Example2:
CREATE OR REPLACE PACKAGE COURSEINFO
IS
PROCEDURE FINDTITLE (ID IN [Link]%TYPE,
TITLE OUT [Link]%TYPE);
FUNCTION HASPREREG (ID IN [Link]%TYPE)
RETURN BOOLEAN;
FUNCTION FINDPREREG(ID IN [Link]%TYPE)
RETURN VARCHAR2;
END COURSEINFO;
/
Package Created.

The package specification for the courseinfo package is shown above contains the
specification of a procedure called findtitle and functions name hasprereg and findprereg.

Package Body:

 It contains actual programming code for the modules described in the specification
section. It also contains code for the modules not described in the specification section.
 The module code in the body without a description in the specification is called a private
module, or a hidden module, and it is not visible outside the body of the package.

General Svntax:
Package body packagename
IS
[variable and type declarations]
[cursor specifications and SELECT queries]
[header and body of functions]
[header and body of procedures]
[BEGIN
executable statements]
[EXCEPTION
exception handlers]
END [packagename];

 To reference an object is a package use [Link] notation. If you do not


use dot notation to reference an object, the compilation will fail.
 Within the body of package, you do not have to use dot notation for that packages
objects, but you definitely have to use dot notation to reference an object from another
package.

Example:

If [Link] <10 then

There is a set of rules that you must follow in writing a package's body:
 The variables, constants, exceptions, and so on declared in the
specification must not be declared again in the package body.
 The number of cursor and module definitions in the specification must
match the number of cursor and module header in the body.
 Any element declared in the specification and be referenced in the body.

The example for package specification and body is shown below:


SQL> CREATE OR REPLACE PACKAGE BODY COURSEINFO IS
PROCEDURE FINDTITLE (ID IN [Link]%TYPE, TITLE
OUT [Link]%TYPE)
IS
BEGIN
SELECT TITLE INTO TITLE1 FROM COURSE WHERE COURSEID=ID;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(ID||'NOT FOUND');
END FINDTITLE;
FUNCTION HASPREREG
(ID IN [Link]%TYPE) RETURN BOOLEAN IS
VPREREG VARCHAR2(6);
BEGIN
SELECT PREREG INTO VPREREG FROM COURSE WHERE
COURSEID=ID;
IF VPREREG='NONE' THEN
DBMS_OUTPUT.PUT_LINE('NO PREREQUISITE');
RETURN FALSE;
ELSE
RETURN TRUE;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(ID||'DOES NOT
EXISTS');
RETURN FALSE;
END HASPREREG;

Package body
A call is made to the procedure findtitle of the courseinfo package
DECLARE
VCOURSEID [Link]%TYPE:=’&PCOURSEID';
VTITLE [Link]%TYPE;
BEGIN
[Link](VCOURSEID,VTITLE);
IF VTITLE IS NOT NULL THEN
DBMS_OUTPUT.PUT_LINE(VCOURSEID||’ ‘||VTITLE);
END IF;
END;
To use the EXECUTE command to run a package's procedure:
EXECUTE [Link]

TRIGGERS

1. Explain about Triggers with Example.(Part-C)


What is a Trigger? Explain the Working of BEFORE and AFTER Trigger.(Part-B)
How are INSTEAD of triggers different from BEFORE and AFTER Triggers?(Part-B)
A database trigger, known simply as a trigger, is a PL/SQL block. It is stored in the database
and is called automatically when a triggering event occurs. A user cannot call a trigger.
The triggering event is based on a Data Manipulation Language (DML) statement, such
as INSERT, UPDATE, or DELETE. It can be created to fire before or after the triggering
event. The execution of a trigger is also known as firing the trigger.
General Syntax:
Create [or replace] trigger triggername
Before|After|instead of triggeringevent ON table|view
[For each row]
[When condition]
DECLARE
Declaration statements
BEGIN
Executable statements
EXCEPTION
Exception-handling statements
END;
 The above syntax the CREATE is used for creating a new trigger and REPLACE
helps to replace an existing trigger. The keyword REPLACE is optional, and
you should only use it to modify a trigger. If a trigger already exists in one table,
you cannot replace it and associate it with another table.
 A trigger is very useful in generating values for derived columns, keeping track of
table access, preventing invalid entries, performing validity checks, or
maintaining security.

Restrictions on Triggers:
A trigger cannot use a Transaction Control Language (TCL) statement, such as
COMMIT,
ROLLBACK, or SAVEPOINT.
A procedure or function called by a trigger cannot perform Transaction Control
Language statements.
A variable in a trigger cannot be declared with LONG or LONG RAW data type.

BEFORE Triggers:
It is fired before execution of a DML statement. The BEFORE trigger is useful when
you want to plug into some values in a new row, insert a calculated column into a new
row, or validate a value in the INSERT query with a lookup in another table.
Example:
SQL> CREATE OR REPLACE TRIGGER
BEFORETRIGGER
BEFORE INSERT ON EMPLOYEE5
FOR EACH ROW
DECLARE
VEMPID [Link]%TYPE;
BEGIN
SELECT EMPLOYEE5.EMPLOYEEID_SEQ.NEXTVAL INTO VEMPID FROM
DUAL;
:[Link]:=VEMPID;
END;

 It fires before a new row is inserted into a table. The 'for each row' is used such
trigger is known as a row trigger. A trigger uses a pseudorecord called :NEW,
which allows you to access the currently processed row. The type of
record :NEW is tablename%TYPE. The columns in this :NEW record are
referenced with dot notation. (:[Link]).
 The trigger beforetrigger provides values of employeeid so you need not include
those values in your INSERT statement.

Example:
SQL> insert into employee5(lname,fname,salary,deptid) values('xxx’,’yyy’,2000,2);
SQL>select * from employee5 where lname='xxx';

After Trigger:
An AFTER trigger fires after a DML statement is executed. It uses the built-in Boolean
functions INSERTING, UPDATING and DELETING.
Example:
SQL> CREATE OR REPLACE TRIGGER EMPLOYEEATRIGGER
AFTER DELETE OR UPDATE ON EMPLOYEE5
DECLARE
VTYPE VARCHAR2(6);
BEGIN
IF DELETING THEN
VTYPE:='DELETE';
ELSIF UPDATING THEN
VTYPE:='UPDATE';
END IF;
INSERT INTO XXX VALUES('EMPLOYEE’, VTYPE);
END;
In this example, we did not use a FOR EACH ROW clause. Such a trigger is known
as a statement trigger.

The trigger uses the transaction type based on the last DML statement. It also plugs in
the user name and today's date. The information is then inserted in the xxx table.

Examplel:
SQL> delete from employees where lname='yyy';
SQL> select * form xxx;
SQL> update employees set commission= salary* 0.10 where employeeid=547;
SQL> select * from xxx;
The above shows rows inserted in the xxx table on use of DELETE and UPDATE
statement by trigger.

INSTEAD of Trigger:

 The BEFORE and AFTER triggers are based on database tables. From version 8i
onward, oracle provides another type of trigger called INSTEAD OF Trigger, which is
not based on a table but is based on a view.
 The INSTEAD OF trigger is a row trigger. If a view is based on a SELECT query that
contains set operators, group functions, GROUP BY and HAVING clauses, DISTINCT
function, join, and/or a ROWNUM pesudocolumn, data manipulation is not possible
through it.
 It is used to modify a table that cannot be modified through a view. This trigger fires
"instead of” triggering DML statements, such as DELETE, UPDATE, or INSERT.
Example1:
SQL> CREATE OR REPLACE VIEW STUDFACULTY
AS
SELECT [Link], [Link], [Link],[Link],
[Link] FROM STUDENT S, FACULTY F
WHERE [Link](+) =[Link];
View created
The above example creates a view with select queries and an outer join.
Example2:
Delete from studfaculty where facultyid=235;
ERROR: cannot delete from view without exactly one key-preserved table.
The delete statement to delete facultyid 235 is shown above return an error message. We
will accomplish deletion of row by creating an INSTEAD OF trigger.

SQL> CREATE OR REPLACE TRIGGER FACULTYDELETE


INSTEAD OF DELETE ON STUDFACULTY
FOR EACH ROW
BEGIN
DELETE FROM FACULTY WHERE FACULTYID =: OLD. FACULTY ID;
END;
SQL> delete from studfaculty where facultyid=235;

Data Manipulation and the INSTEAD OF Trigger

In the above example INSTEAD OF DELETE trigger is created on the studfaculty view. Now,
when the DELETE statement is issued to delete a faculty member with the complex view, the
trigger is fired, and the faculty member is deleted without any error messages.
The use of pseudo row called :OLD in this trigger, which gets the value of Facultyid 235 from the
DELETE statement that the user had issued.

DATA DICTIONARY VIEWS

1. Explain about Data Dictionary Views. (Part-B)


Oracle maintains a very informative Data Dictionary. A few Data Dictionary Views are
useful for
getting information about stored PL/SQL blocks.
The following are example of queries to USER PROCEDURES (for named blocks), USER
TRIGGERS (for trigger only),USER_SOURCE (for all source codes), USER OBJECTS
(for any object), and USER_ERRORS(for current errors) views:
Select ObjectName, Procedure_name FROM USER_PROCEDURES;
Select Name, Type,Line, Text FROM USER_SOURCE;
SELECT object_name, object_type FROM USER_OBJECTS;

Use the DESCRIBE command to find out the names of columns in each Data
Dictionary view, and issue SELECT queries according to the information desired.
UNIT-V COMPLETED

You might also like