Understanding Functional Dependencies and Normalization
Understanding Functional Dependencies and Normalization
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.
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.
employee
emp_no department
l_name dept_code
f_name
description
dept_code
❖ 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
Name Project
Name Hobby
Alexis Microsoft
Alexis Reading
Alexis Oracle
Alexis Music
Mathews Intel
Mathews Movies
Mathews Sybase
Mathews Riding
p F
F
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]
❖ 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.
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
❖ 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
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;
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
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];
Example:
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.
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
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.
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.
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