Database Systems Lab Manual (1)
Database Systems Lab Manual (1)
CERTIFICATE
satisfactorily completed the lab exercises prescribed for Database Systems Lab [CSE
Date: ……...................................
Signature
Faculty in Charge
i
ii
CONTENTS
iii
Course Objectives
• To understand and use different constructs in SQL.
• Learn to develop stored procedures, functions and packages.
• To develop a database application.
Course Outcomes
At the end of this course, students will have the
• Ability to write SQL queries for database manipulation.
• Ability to understand the effective use of stored procedures, functions and packages.
• Design and develop applications using ORACLE.
Evaluation plan
• Internal assessment: 60 marks
ü Continuous evaluation component (for each week): some marks have been assigned.
ü The assessment will depend on punctuality, program execution, maintaining the
observation note and answering the questions in viva voce.
1
INSTRUCTIONS TO THE STUDENTS
Pre-Lab Session Instructions
• Students should carry the Lab Manual Book and the required stationery to every lab
session.
• Be on time and follow the institution’s dress code.
• Must Sign in to the log register provided.
• Make sure to occupy the allotted seat and answer the attendance.
• Adhere to the rules and maintain decorum.
2
o Additional Exercises - to be completed outside the lab or in the lab to enhance
the skill.
• In case a student misses a lab session, he/she may ensure that the experiment is
completed during the extra lab session (of other batch) with the permission of the
HOD.
• Questions for lab tests and examination are not necessarily limited to the questions
in the manual but may involve some variations and/or combinations of the questions.
• A sample note preparation is given as a model for observation.
3
Sample Lab Observation Note Preparation .MNB/HG
• Creating Tables
1. list the information of all account holders (name and account number).
Select * from depositor.
2. List all branch names and their assets
SELECT BRANCH_NAME, ASSETS FROM BRANCH;
5
LAB NO.: 1 Date:
INTRODUCTION TO SQL
Objectives:
In this lab, student will be able to:
• Understand the working of DDL/DML commands.
SQL Statements can be categorized as -
DDL (Data definition language): Are used to define database structure or schema.
DML (Data manipulation language): Are used to change or alter data with the database
or schema.
DCL (Data Control Language): Are used to control access or privileges.
TCL (Transaction Control Language): Are used to manage transactions in the database.
DDL COMMANDS:
1. CREATION OF TABLE:
SYNTAX:
create table<tablename>(column_name1 datatype(<size>),column_name2
datatype(<size>) ...);
EXAMPLE:
SQL>
create table STUDENT (
reg_no number (5),
stu_name varchar(20),
stu_age number(5),
stu_ dob date,
subject1_marks number (4,2),
subject2_marks number(4,2),
subject3_marks number(4,1));
SQL>insert into STUDENT values (101, ‘AAA’,16, ‘03-jul-88’,80,90,98);
8
2. Inserting Data into Tables:
Syntax:Insert into <tablename> (<col1>,<col2>) values (<exp>,<exp>);
Ex: insert into STUDENT(reg_no, stu_name) values (102, ‘KRISH’);
3. Delete operations
a) Removal of specified row/s
Syntax:Delete from <tablename> where <condition>;
Ex: Delete from STUDENT where reg_no=102;
b) Remove all rows
Syntax: Delete from <tablename>;
Ex: Delete from STUDENT;
LAB EXERCISES:
1. Create a table employee with ( emp_no, emp_name, emp_address)
2. Insert five employees information.
3. Display names of all employees.
4. Display all the employees from ‘MANIPAL’.
5. Add a column named salary to employee table.
6. Assign the salary for all employees.
7. View the structure of the table employee using describe.
8. Delete all the employees from ‘MANGALORE’
9. Rename employee as employee1.
10. Drop the table employee1.
9
LAB NO.: 2 Date:
INTEGRITY CONSTRAINTS IN SQL
Objectives:
In this lab, student will be able to:
• Understand the use of integrity constraints.
Integrity Constraints:
Constraints are the rules enforced on data columns on 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 column level or table level. Column level
constraints are applied only to one column, whereas table level constraints are applied to
the whole table.
Dropping Constraints:
Any constraint that you have defined can be dropped using the ALTER TABLE
command with the DROP CONSTRAINT option.
10
For example, to drop the primary key constraint in the EMPLOYEES table, you can use
the following command:
11
ALTER TABLE <table_name>
ADD / MODIFY/DROP/DISABLE/ENABLE/VALIDATE/NOVALIDATE
CONSTRAINT <constraint_name>
Built-in Functions:
• LENGTH (string): The Oracle/PLSQL LENGTH function returns the length of the
specified string.
Syntax: LENGTH( string1 )
• LOWER (string): The Oracle/PLSQL LOWER function converts all letters in the
specified string to lowercase. If there are characters in the string that are not letters,
they are unaffected by this function.
Syntax: LOWER(string)
12
Syntax: TO_CHAR( value [, format mask] [, nls_language] )
LAB EXERCISES:
Consider the following schema:
Employee (EmpNo, EmpName, Gender, Salary, Address, DNo)
Department (DeptNo, DeptName, Location)
1. Create Employee table with following constraints:
• Make EmpNo as Primary key.
• Do not allow EmpName, Gender, Salary and Address to have null values.
• Allow Gender to have one of the two values: ‘M’, ‘F’.
2. Create Department table with following:
• Make DeptNo as Primary key
• Make DeptName as candidate key
3. Make DNo of Employee as foreign key which refers to DeptNo of Department.
4. Insert few tuples into Employee and Department which satisfies the above constraints.
13
5. Try to insert few tuples into Employee and Department which violates some of the
above constraints.
6. Try to modify/delete a tuple which violates a constraint.
(Ex: Drop a department tuple which has one or more employees)
7. Modify the foreign key constraint of Employee table such that whenever a department
tuple is deleted, the employees belonging to that department will also be deleted.
Naming Constraints:
8. Create a named constraint to set the default salary to 10000 and test the constraint by
inserting a new record.
14
13. List all the instructors whose salary is in between 40000 and 90000.
Retrieving records from multiple tables:
14. Display the IDs of all instructors who have never taught a course.
15. Find the student names, course names, and the year, for all students those who have
attended classes in room-number 303.
Rename and Tuple Variables (Use as in select and from):
16. For all students who have opted courses in 2015, find their names and course id’s
with the attribute course title replaced by c-name.
17. Find the names of all instructors whose salary is greater than the salary of at least
one instructor of CSE department and salary replaced by inst-salary.
String Operations (Use %, _, LIKE):
18. Find the names of all instructors whose department name includes the substring
‘ch’.
Built-in Functions:
19. List the student names along with the length of the student names.
20. List the department names and 3 characters from 3rd position of each department name
21. List the instructor names in upper case.
22. Replace NULL with value1(say 0) for a column in any of the table
23. Display the salary and salary/3 rounded to nearest hundred from Instructor.
Add date of birth column (DOB) to Employee Table. Insert appropriate DOB values
for different employees and try the exercise problems given below:
24. Display the birth date of all the employees in the following format:
• ‘DD-MON-YYYY’
• ‘DD-MON-YY’
• ‘DD-MM-YY’
25. List the employee names and the year (fully spelled out) in which they are born
• ‘YEAR’
• ‘Year’
• ‘year’
26. List the employee names and the day of the week (fully spelled out) in which they are
born
• ‘DAY’
15
• ‘Day’
27. List the employee names and the month(fully spelled out) in which they are born
• ‘MONTH’
• ‘Month’
28. Find the last day of the month(and its day of the week) in which employee Mr. X is
born
29. Find the age of all the employees
30. Find the Saturday following the Employee’s 60th birthday
31. List the employees whose birthday falls in the given year X
32. List the employees whose birthday fall between the given years X and Y
33. List the employees who will retire on the given year X.
[Hint: use & with the variable name (e.g. &X) in the SQL query to read the value from the
user]
ADDITIONAL EXERCISE:
1. Modify the employee table to check the salary of every employee to be greater than
5000.
2. Find the quarter of year from the given date.
3. Convert seconds to hours, minutes and seconds format.
4. Find the week of the year from the given date.
5. Find the names of all departments with instructor, and remove duplicates.
6. For all instructors who have taught some course, find their names and the course ID of
the courses they taught.
7. Find all the instructors with the courses they taught.
8. List all the students with student name, department name, advisor name and the
number of courses registered.
16
LAB NO.: 3 Date:
INTERMEDIATE SQL
Objectives:
The corresponding expressions in the select lists of the component queries of a compound
query must match in number and must be in the same data type group (such as numeric
or character).
The UNION operator returns only distinct rows that appear in either result.
SELECT product_id FROM order_items
UNION
SELECT product_id FROM inventories;
The following statement combines the results with the INTERSECT operator, which
returns only those rows returned by both queries:
SELECT product_id FROM inventories
INTERSECT
SELECT product_id FROM order_items;
The following statement combines results with the MINUS operator, which returns only
unique rows returned by the first query but not by the second:
17
SELECT product_id FROM inventories
MINUS
SELECT product_id FROM order_items;
LAB EXERCISE:
Implement the following Queries on UNIVERSITY Database:
Set Operations
UNION (Use union all to retain duplicates):
1. Find courses that ran in Fall 2009 or in Spring 2010
INTERSECT (Use intersect all to retain duplicates):
2. Find courses that ran in Fall 2009 and in spring 2010
MINUS:
3. Find courses that ran in Fall 2009 but not in Spring 2010
Null values
4. Find the name of the course for which none of the students registered.
Nested Subqueries
Set Membership (in / not in):
5. Find courses offered in Fall 2009 and in Spring 2010.
6. Find the total number of students who have taken course taught by the instructor
with ID 10101.
7. Find courses offered in Fall 2009 but not in Spring 2010.
18
8. Find the names of all students whose name is same as the instructor’s name.
Set Comparison (>=some/all)
9. Find names of instructors with salary greater than that of some (at least one) instructor
in the Biology department.
10. Find the names of all instructors whose salary is greater than the salary of all
instructors in the Biology department.
11. Find the departments that have the highest average salary.
12. Find the names of those departments whose budget is lesser than the average salary
of all instructors.
Test for Empty Relations (exists/ not exists)
13. Find all courses taught in both the Fall 2009 semester and in the Spring 2010 semester.
14. Find all students who have taken all courses offered in the Biology department.
Test for Absence of Duplicate Tuples
15. Find all courses that were offered at most once in 2009.
16. Find all the students who have opted at least two courses offered by CSE department.
Subqueries in the From Clause
17. Find the average instructors salary of those departments where the average salary is
greater than 42000
Views
18. Create a view all_courses consisting of course sections offered by Physics
department in the Fall 2009, with the building and room number of each section.
19. Select all the courses from all_courses view.
20. Create a view department_total_salary consisting of department name and total
salary of that department.
ADDITIONAL EXERCISE:
1. Find the names of all departments with instructor and remove duplicates.
2. For all instructors who have taught some course, find their names and the course ID
of the courses they taught.
3. Find all the instructors with the courses they taught.
4. List all the students with student name, department name, advisor name and the number
of courses registered.
19
LAB NO.: 4 Date:
COMPLEX QUERIES ON SQL
Objectives:
There are circumstances where we would like to apply the aggregate function not only to
a single set of tuples, but also to a group of sets of tuples, we specify this in SQL using
the group by clause. The attribute or attributes given in the group by clause are used to
form group. Tuples with the same value on all attributes in the group by clause are placed
in one group.
Syntax:
Example:
SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY EMPNO;
JOIN with GROUP BY: This query is used to display a set of fields from two relations
by matching a common field in them and group the corresponding records for each and
every value of a specified key(s) while displaying.
20
Example:
Example:
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM (Orders INNER JOIN Employees ON
Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT (Orders.OrderID) > 10;
ORDER BY: This query is used to display a selected set of fields from a relation in an
ordered manner base on some field.
Syntax:
SELECT column_name
FROM table_name
ORDER BY column_name;
Example:
SQL> SELECT empno, ename, job
FROM emp
ORDER BY job;
JOIN with ORDER BY: This query is used to display a set of fields from two relations
by matching a common field in them in an ordered manner based on some fields.
21
Syntax:
Syntax:
WITH <temporary table name> AS (
SELECT <attributes>
FROM <table name>
GROUP BY <attribute>)
SELECT <attribute/s> from <tablename/s>
Example:
WITH temporaryTable(averageValue) as
(SELECT avg(Salary) from Employee),
SELECT EmployeeID,Name, Salary from Employee
WHERE Employee.Salary > temporaryTable.averageValue;
22
Example:
• You can use the SQL ROLLBACK statement to rollback (undo) any changes
you made to the database before a COMMIT was issued.
• The SQL COMMIT statement saves any changes made to the database. When a
COMMIT has been issued, all the changes since the last COMMIT, or since you
logged on as the current user, are saved.
Example:
23
Implementing the rollback
SQL> rollback;
SQL> select * from employee;
SQL> COMMIT;
Commit complete.
LAB EXERCISE:
Implement the following Queries on UNIVERSITY Database.
Group By:
1. Find the number of students in each course.
2. Find those departments where the average number of students are greater than 10.
3. Find the total number of courses in each department.
4. Find the names and average salaries of all departments whose average salary is
greater than 42000.
5. Find the enrolment of each section that was offered in Spring 2009.
24
12. Find the average salary of those department where the average salary is greater
than 50000 and total number of instructors in the department are more than 5.
With Clause:
13. Find all departments with the maximum budget.
14. Find all departments where the total salary is greater than the average of the total
salary at all departments.
15. Find the sections that had the maximum enrolment in Fall 2009
16. Select the names of those departments where the total credits earned by all the
students is greater than the total credits earned by all the students in the Finance
Department
ADDITIONAL EXERCISE:
25
LAB NO.: 5 Date:
ER MODEL AND SQL
Objectives:
Multi-Valued Attributes
A multi-valued attribute is usually represented with a double-line oval
If you have a multi-valued attribute, take the attribute and turn it into a new entity or
table of its own. Then make a 1:N relationship between the new entity and the existing
one. In simple words. 1. Create a table for the attribute. 2. Add the primary (id) column
of the parent entity as a foreign key within the new table as shown below:
26
1:1 Relationships
Or
1:N Relationships
27
N:N Relationships
LAB EXERCISES:
28
Implement the following queries:
1. Retrieve the birth date and address of the employee(s) whose name is ‘John B.
Smith’. Retrieve the name and address of all employees who work for the
‘Research’ department.
2. For every project located in ‘Stanford’, list the project number, the controlling
department number, and the department manager’s last name, address, and birth
date.
3. Find all distinct salaries of employees.
4. For each employee, retrieve the employee’s first and last name and the first and
last name of his or her immediate supervisor.
5. Make a list of all project numbers for projects that involve an employee whose
last name is ‘Smith’, either as a worker or as a manager of the department that
controls the project.
6. Retrieve all employees who reside is in Houston, Texas.
7. Show the resulting salaries if every employee working on the ‘ProductX’ project
is given a 10 percent raise.
8. Retrieve all employees in department 5 whose salary is between 30,000 and
40,000.
9. Retrieve a list of employees and the projects they are working on, ordered by
department and, within each department, ordered alphabetically by last name, then
first name.
10. Retrieve the names of all employees who do not have supervisors.
11. Retrieve the name of each employee who has a dependent with the same first name
and is the same sex as the employee.
12. Retrieve the names of employees who have no dependents.
13. List the names of managers who have at least one dependent.
14. Retrieve the Social Security numbers of all employees who work on project
numbers 1, 2, or 3.
15. Find the sum of the salaries of all employees, the maximum salary, the minimum
salary, and the average salary.
29
16. Find the sum of the salaries of all employees of the ‘Research’ department, as
well as the maximum salary, the minimum salary, and the average salary in this
department.
17. For each project, retrieve the project number, the project name, and the number
of employees who work on that project.
18. For each project on which more than two employees work, retrieve the project
number, the project name, and the number of employees who work on the
project.
19. For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than 40,000.
ADDITIONAL EXERCISE:
1. Find the names of employees who work on all the projects controlled by
department number 5.
2. Find the names of all employees who have a higher salary than some instructor
in ‘Research’ department.
3. Find the total number of (distinct) employees who have worked on project
‘ProductX’.
30
LAB NO.: 6 Date:
A SIMPLE APPLICATION USING ORACLE DB
Objectives:
Using this architecture, the software is divided into 3 different tiers: Presentation tier,
Logic tier, and Data tier. Each tier is developed and maintained as an independent tier.
JDBC
An API that lets the user access virtually any tabular data source from the Java
programming language”. A tabular data source is virtually any data source, from
relational databases to spreadsheets and flat files.
31
Basic steps to use a database in Java:
1. Establish a connection
2. Create JDBC Statements
3. Execute SQL Statements
4. GET ResultSet
5. Close connections
Example :
1. Establish a connection
• import java.sql.*;
• Load the vendor specific driver
Class.forName("oracle.jdbc.driver.OracleDriver");Dynamically loads a driver class,
for Oracle database
• Make the connection
Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@oracle-
prod:1521:OPROD", username, passwd);
• Establishes connection to database by obtaining a Connection object
con.setAutoCommit(false);
con.setAutoCommit(true);
Once auto-commit is off, no SQL statement will be committed until an explicit is invoked
con.commit(); At this point all changes done by the SQL statements will be made
permanent in the database.
Programs should recover and leave the database in a consistent state. If a statement in the
try block throws an exception or warning, it can be caught in one of the correspondingcatch
statements. E.g., the user could rollback the transaction in a catch { …} block or close
database connection and free database related resources in finally {…} block.
LAB EXERCISES:
1. Consider the following tables of University database:
33
Build the application containing the following screens which should cover the
functionalities of Insert, Update, Delete, etc. Handle “No Database Connectivity”
exception.
34
LAB NO.: 7 Date:
Mini Project (Phase I)
Objectives:
In this lab, student will be able to:
• Identify a domain that uses database to manage data.
• Formulate the synopsis for mini project.
• Perform the requirement gathering and design phases of the project.
Guidelines:
All the students are instructed to form a team of two members. Students need to submit
synopsis by the end of sixth week.
Synopsis Format:
• Title, Team Members
• Abstract (with modifications, if any)
• Problem Statement (covering both data and functional requirements)
(Refer ‘Project Suggestions’ in Chapter 9, Database System Concepts, Korth, Sixth
Edition)
LAB EXERCISE:
For the selected problem statement:
1. Design and implement the database.
2. Implement basic and complex queries.
35
LAB NO: 8 Date:
PL/SQL BASICS
Objectives:
In this lab, student will be able to understand and use:
PL/SQL
Though SQL is the natural language of Oracle DB, it has some disadvantages when used
as a programming language:
1. SQL does not have any procedural capabilities like condition checking, looping
and branching.
2. SQL statements are passed on to the Oracle engine one at a time. This adds to the
network traffic in a multi-user environment and decreases data processing speed.
3. SQL has no facility for programmed error handling.
Main Features of PL/SQL
36
PL/SQL Block Structure: The basic unit of a PL/SQL source program is the block,
which groups related declarations and statements. The syntax for which is shown in
Figure 7.1
37
‘SET SERVEROUTPUT ON’ command should be issued before executing the PL/SQL
block. Alternatively, it can be included in the beginning of every PL/SQL block.
SQL DATA TYPES
The default data types that can be declare in PL/SQL are
1. Number
2. Char
3. Date
4. Boolean
Null values are allowed for Number, Char and Date but not Boolean data type.
E.g.: sname varchar2(30);
%TYPE
PL/SQL can use %Type to declare variables based on column definition in a table. Hence,
if a column’s attribute changes, the variable’s attribute will change as well.
E.g.: sname student.name%TYPE;
%ROWTYPE
The %ROWTYPE attribute lets you declare a record that represents a row in a table or
view. For each column in the referenced table or view, the record has a field with the
same name and data type. To reference field in the record use record_name.field_name.
The record fields do not inherit the constraints or default values of the corresponding
columns. If the referenced item table or view changes, your declaration is automatically
updated. You need not change your code when, for example, columns are added or
dropped from the table or view.
E.g., srecord student%ROWTYPE;
Not Null: ‘Not null’ causes creation of a variable or a constant that cannot be assigned
‘null’ value. Attempt to assign null value to such a variable or constant will return an
internal error.
VARIABLES: In PL/SQL a variable name must begin with a character with maximum
length of 30. Space not allowed in variable names. Reserve words cannot be used as
variable names unless enclosed within double quotes. Case is insignificant when
declaring variables.
Values can be assigned to variables by:
1. Using the assignment operator := (a colon followed by an ‘equal to’ ).
2. Selecting or fetching table data values INTO variables.
38
Constants can be declared with constant keyword.
E.g.: pi constant number := 3.141592654;
DISPLAYING USER MESSAGES ON SCREEN
dbms_output is a package that includes procedures and functions that accumulate
information in a buffer so that it can be retrieved later.
put_line is a procedure in dbms_output package used to display information in the buffer.
SERVEROUTPUT should be set to ON before calling this procedure.
COMMENTS
Comment can be of two forms, as:
1. The comment line begins with a double hypen (--). The entire line is considered
as a comment.
2. The comment line begins with a slash followed by an asterisk (/*) and ends with
asterisk followed by slash (*/). All lines within is considered as comments.
Syntax:
IF < condition> THEN
< action >
ELSE
< action >
END IF;
Example: A PL/SQL block to display the grade for given letter grade.
DECLARE
grade CHAR(1);
BEGIN
grade := '&g';
IF grade = 'A' THEN
DBMS_OUTPUT.PUT_LINE('Excellent');
ELSIF grade = 'B' THEN
DBMS_OUTPUT.PUT_LINE('Very Good');
ELSIF grade = 'C' THEN
39
DBMS_OUTPUT.PUT_LINE('Good');
ELSIF grade = 'D' THEN
DBMS_OUTPUT. PUT_LINE('Fair');
ELSIF grade = 'F' THEN
DBMS_OUTPUT.PUT_LINE('Poor');
ELSE
DBMS_OUTPUT.PUT_LINE('No such grade');
END IF;
END;
/
Syntax:
LOOP
<Sequence of statements>
END LOOP;
Example: The following PL/SQL block traces the control flow in a simple LOOP
construct.
DECLARE
x NUMBER := 0;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' ||
TO_CHAR(x));
x := x + 1;
IF x > 3 THEN EXIT;
END IF;
END LOOP;
-- After EXIT, control resumes here
DBMS_OUTPUT.PUT_LINE(' After loop: x = ' || TO_CHAR(x));
END;
40
Output:
Inside loop: x = 0
Inside loop: x = 1
Inside loop: x = 2
Inside loop: x = 3
After loop: x = 4
Syntax:
WHILE <condition>
LOOP
<Action>
END LOOP;
Example: The following PL/SQL block traces the control flow in a while LOOP.
DECLARE
x NUMBER := 0;
BEGIN
WHILE x < 4
LOOP
DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' ||
TO_CHAR(x));
X := x + 1;
END LOOP
END;
/
Syntax:
FOR index IN [ REVERSE ] lower_bound..upper_bound LOOP
statements
END LOOP ;
With REVERSE, the value of index starts at upper_bound and decreases by one with each
iteration of the loop until it reaches lower_bound.
41
Example: The following PL/SQL block traces the control flow in a FOR LOOP
BEGIN
Output:
lower_bound < upper_bound
1
2
3
lower_bound = upper_bound
2
lower_bound > upper_bound
The GOTO statement transfers control to a label unconditionally. The label must be
unique in its scope and must precede an executable statement or a PL/SQL block. When
run, the GOTO statement transfers control to the labeled statement or block.
42
Syntax:
GOTO Label
The code block is marked using tags
<<Label>>
ERROR HANDLING:
In PL/SQL, a warning or error condition is called an exception. Exceptions can be
internally defined (by the run-time system) or user defined. Examples of internally
defined exceptions include division by zero and out of memory etc.
When an error occurs, an exception is raised. That is, normal execution stops and control
transfers to the exception-handling part of your PL/SQL block or subprogram. Internal
exceptions are raised implicitly (automatically) by the run-time system.
To handle raised exceptions, you write separate routines called exception handlers. After
an exception handler runs, the current block stops executing and the enclosing block
resumes with the next statement. If there is no enclosing block, control returns to the host
environment.
43
Syntax:
EXCEPTION
WHEN ex_name_1 THEN
< Exception handler_1>
WHEN ex_name_2 OR ex_name_3 THEN
< Exception handler_2>
WHEN OTHERS THEN
< Exception handler_3>
END;
DECLARE
BEGIN
update account set balance = 0 where balance<0
EXCEPTION
44
END;
User Defined Exceptions:
User can define exceptions of his own in the declarative part of any PL/SQL block,
subprogram, or package. For example, an exception named insufficient_balance can
be defined to flag overdrawn bank accounts. Unlike internal exceptions, user-defined
exceptions must be given names and they must be raised explicitly by RAISE statements.
Example: Validate the resultant balance before supporting withdrawal of money from the
account table such that a min. of 500 is maintained.
Declare
Insufficient_Balance Exception;
Amount account.balance%Type;
Temp account.balance%Type;
ANumber account.account_number%Type;
BEGIN
ANumber := &Number;
Amount := &Amount;
Select balance into Temp from account where
account_number = ANumber;
Temp := Temp – Amount;
IF (Temp >=500) THEN
update account set balance = Temp where account_number =
ANumber;
ELSE
RAISE Insufficient_Balanae;
EXCEPTION
WHEN Insufficient_Balance THEN
dbms_output.put_line(“Insufficient Balance”);
END;
45
LAB EXERCISE:
NOTE: Use a table StudentTable(RollNo, GPA) and populate the table with {(1, 5.8); (2,
6.5); (3, 3.4); (4,7.8); (5, 9.5)} unless a different DB schema is explicitly specified.
Usage of IF –THEN:
2. Write a PL/SQL block to display the letter grade(0-4: F; 4-5: E; 5-6: D; 6-7: C; 7-
8: B; 8-9: A; 9-10: A+} of given student.
3. Input the date of issue and date of return for a book. Calculate and display the fine
with the appropriate message using a PL/SQL block. The fine is charged as per
the table 8.1:
Table 8.1
Simple LOOP:
4. Write a PL/SQL block to print the letter grade of all the students(RollNo: 1 - 5).
Usage of WHILE:
Usage of FOR:
6. Write a PL/SQL block to find the student with max. GPA without using aggregate
function.
46
Usage of GOTO:
Exception Handling:
8. Based on the University database schema, write a PL/SQL block to display the
details of the Instructor whose name is supplied by the user. Use exceptions to
show appropriate error message for the following cases:
ADDITIONAL EXERCISE
Usage of IF –THEN:
2. You went to a video store and rented DVD that is due in 3 days from the rental
date. Input the rental date, rental month and rental year. Calculate and print the
return date, return month, and return year.
Simple LOOP:
3. Write a simple loop such that message is displayed when a loop exceeds a
particular value.
4. Write a PL/SQL block to print all odd numbers between 1 and 10.
Usage of WHILE:
47
Usage of FOR:
Usage of GOTO:
7. Write a PL/SQL block of code to achieve the following: if the price of Product
‘p00001’ is less than 4000, then change the price to 4000. The Price change has
to be recorded in the old_price_table along with Product_no and the date on which
the price was last changed. Tables involved:
Product_master(product_no, sell_price)
Old_price_table(product_no,date_change, Old_price)
Exception:
8. Write a PL/SQL block that asks the user to input first number, second number and
an arithmetic operator (+, -, *, /). If the operator is invalid, throw and handle a
user-defined exception. If the second number is zero and the operator is /, handle
the ZERO_DIVIDE predefined server exception.
48
LAB NO: 9 Date:
CURSORS
Objectives:
In this lab, student will be able to understand and use:
• Implicit and Explicit Cursors
• Cursor For Loops, Parameterized Cursors
• Transactions
CURSORS: A cursor is a temporary work area created in the system memory when a
SQL statement is executed. A cursor contains information on a select statement and the
rows of data accessed by it. This temporary work area is used to store the data retrieved
from the database, and manipulate this data. A cursor can hold more than one row, but
can process only one row at a time. The set of rows the cursor holds is called the active
set.
Implicit Cursor
Oracle engine implicitly opens a cursor on the server to process each SQL statement and
manages space, populates data and releases memory itself. Implicit cursor can be used to
access information about the status of last insert, update, delete or single row select
statements. SQL is the cursor name of the implicit cursor. The attributes of the implicit
cursor are listed below.
Attribute Description
49
Always returns FALSE for implicit cursors, because Oracle
%ISOPEN
closes the SQL cursor automatically after executing its
associated SQL statement.
BEGIN
END;
/
Output: If there is no row that matches the delete query in student table.
No students of department: History
Explicit Cursor
Steps involved in using an explicit cursor and manipulating data in its active set are:
1. Declare a cursor mapped to a select statement.
2. Open the Cursor.
3. Fetch data from the cursor one row at a time into memory variables
4. Process the data held in the memory variables as required using a loop
50
5. Exit from loop after processing is complete
6. Close the cursor
Syntax:
CURSOR [ parameter_list ] [ RETURN return_type ]
IS select_statement;
OPEN cursor_name;
Loop
FETCH cursor_name into variable_list;
End Loop
CLOSE cursor_name;
No memory is allocated at this point and only intimation is sent to the engine.
Open defines a private area named by the cursor name, executes the query , retrieves the
data and creates the Active Data Set.
Fetch moves the data held in the active data set into the memory variable. It is placed in
a Loop … End Loop which causes data to be fetched and processed until all rows are
processed
Close disables the cursor and the active data set becomes undefined. After the fetch loop
is executed the data needs to be closed. Close will release the memory occupied by the
cursor.
Example: A PL/SQL block to list the student names of ‘Comp. Sci.’ department in
University database.
DECLARE
dname CONSTANT student.dept_name%TYPE := ‘Comp. Sci.’;
CURSOR C1 is select name from Student where dept_name = dname;
sname student.name%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE( ' ');
OPEN c1;
LOOP
-- Fetches student name into variable
FETCH c1 INTO sname;
51
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( RPAD(‘Name: ‘ || sname);
END LOOP;
CLOSE c1;
DBMS_OUTPUT.PUT_LINE( ' ');
END;
The cursor FOR LOOP statement lets the user run a SELECT statement and then
immediately loop through the rows of the result set. This statement can use either an
implicit or explicit cursor (but not a cursor variable).
The cursor FOR LOOP statement implicitly declares its loop index as a %ROWTYPE
record variable of the type that its cursor returns. This record is local to the loop and exists
only during loop execution. Statements inside the loop can reference the record and its
fields.
After declaring the loop index record variable, the FOR LOOP statement opens the
specified cursor. With each iteration of the loop, the FOR LOOP statement fetches a row
from the result set and stores it in the record. When there are no more rows to fetch, the
cursor FOR LOOP statement closes the cursor. The cursor also closes if a statement inside
the loop transfers control outside the loop or if PL/SQL raises an exception.
Example: A PL/SQL block to find the department having maximum Budget in University
database, without using max() aggregate function.
DECLARE
CURSOR C1 is select * from Department;
vBudget Department.Budget%Type :=0;
vdname Department.dept_name%TYPE;
BEGIN
For dept in C1
LOOP
IF dept.Budget > vBudget THEN
vBudget := dept.Budget;
vdname := dept.dept_name;
END IF;
END LOOP;
Dbms_output.put_line('Max. Budget: ' || vBudget || ' Dept: '
|| vdname);
END;
52
WHERE CURRENT OF
It states that the most recent row fetched from the table should be updated or deleted.
Inside a cursor loop, WHERE CURRENT OF allows the current row to be directly
updated. When the sessions open a cursor with the FOR UPDATE clause, all the rows in
the return set will hold row level locks. When SELECT FOR UPDATE is associated with
an explicit cursor, the cursor is called a FOR UPDATE cursor. Only a FOR UPDATE
cursor can appear in the CURRENT OF clause of an UPDATE or DELETE statement.
PARAMATERIZED CURSORS
PL/SQL allows parametrized cursor so that the cursor can be generic and the data that is
retrieved from the table be changed according to need. The user can create an explicit
cursor that has formal parameters, and then pass different actual parameters to the cursor
each time it is opened. In the cursor query, a formal cursor parameter can be used
anywhere that a constant is used. Outside the cursor query, formal cursor parameters
cannot be referenced.
Syntax:
CURSOR cursor_name( variable_name Datatype) is SELECT statement
53
Example: Based on the University database schema, the following example uses a
parametrized cursor on the Instructor table to display the instructors of given department.
DECLARE
cursor c(dname instructor.dept_name%TYPE) is select *
from Instructor where dept_name = dname;
BEGIN
FOR tmp IN c('Comp. Sci.')
LOOP
dbms_output.put_line('EMP_No: '||tmp.ID);
dbms_output.put_line('EMP_Name: '||tmp.name);
dbms_output.put_line('EMP_Dept: '||tmp.dept_name);
dbms_output.put_line('EMP_Salary:'||tmp.salary);
DBMS_OUTPUT.PUT_LINE( ' ');
END Loop;
END;
/
TRANSACTIONS:
A series of one or more statements that are logically related are termed as a Transaction.
A transaction begins with the first executable SQL statement after a commit, rollback or
connection made to the oracle engine. A transaction can be closed by using a commit or
a rollback statement.
COMMIT ends the current transaction and makes permanent changes made during the
transaction
ROLLBACK ends the transaction but undoes any changes made during the transaction
SAVEPOINT marks and saves the current point in the processing of a transaction.
54
ROLLBACK can be fired with or without the SAVEPOINT clause. Rollback operation
performed without the SAVEPOINT clause amounts to the following:
1. Ends the transaction
2. Undoes all the changes in the current transaction
3. Erases all savepoints in that transaction
4. Releases the transactional locks
Example:
Consider account (account_number, balance) table, populated with {(1, 200); (2, 3000);
(3, 500)}. Withdraw an amount 200 and deposit 1000 for all the accounts. If the sum of
all account balance exceeds 5000 then undo the deposit just made.
Declare
Total_bal account.balance%TYPE;
Begin
Update account set balance=balance-200;
Savepoint deposit;
Update account set balance=balance+1000;
Select sum(balance) into total_bal from account;
If total_bal > 5000 then
Rollback to savepoint deposit;
End If;
Commit;
End;
LAB EXERCISE:
Note: Use University DB schema for the following, unless a different DB schema is
explicitly specified
Cursors:
2. Write a PL/SQL block that will display the ID, name, dept_name and tot_cred of
the first 10 students with lowest total credit.
3. Print the Course details and the total number of students registered for each course
along with the course details - (Course-id, title, dept-name, credits,
instructor_name, building, room-number, time-slot-id, tot_student_no )
4. Find all students who take the course with Course-id: CS101 and if he/ she has
less than 30 total credit (tot-cred), deregister the student from that course. (Delete
the entry in Takes table)
Parameterized Cursors:
6. Write a PL/SQL block to print the list of Instructors teaching a specified course.
7. Write a PL/SQL block to list the students who have registered for a course taught
by his/her advisor.
8. Write a PL/SQL block that updates the salary of ‘Biology’ department instructors
by 20%. Subsequently, check the whether the department budget can support the
raise. If not, undo the raise given to the instructors.
ADDITIONAL EXERCISE:
Cursors
56
1. Write a PL/SQL block that will display the name, department and salary of the
top 10 highest paid instructors.
2. Repeat problem 1
i. Using cursor for loops. ii. Using where current of.
Parameterized Cursors:
3. Write a PL/SQL block that would update the Bal_stock in the item_master(ItemId,
Description, Bal_stock) table each time a transaction takes place with an entry in
the item_transaction (TransID, ItemId, Quantity) table. The change in the
item_master table depends on the itemId. If the item is present in the item_master
table then Bal_stock is updated. Otherwise, itemID is inserted into the
item_master table with ZERO as Bal_stock and raises an exception.
4. Write a PL/SQL block to find the number of courses offered and number of
students of each department. Use a parameterized cursor which takes department
name as a parameter and calculates the number of courses offered and number of
students of that department.
5. Write a PL/SQL block that will insert a new record in Takes (ID, course-id, sec-
id, semester, year, grade) table. Check the total number of students registered for
the course and if it exceeds 30, then undo the insert made to the Takes table.
57
LAB NO.: 10 Date:
Uses of Subprograms:
• Modularity
• Easier Application Design
• Maintainability
• Packageability
• Reusability
• Better Performance
Since the stored subprograms run in the database server, a single invocation over the
network can start a large job.
Part of a Subprogram:
• Declarative part(optional)
• Executable part(required)
• Exception handling part(optional)
PROCEDURE
A procedure is a subprogram that performs a specific action. A procedure invocation (or
call) is a statement. In a procedure a return statement returns the control to the invoker
and we cannot specify any expression. The declarative part of a subprogram does not
begin with the keyword DECLARE, as the declarative part of an anonymous block does.
Syntax:
CREATE OR REPLACE PROCEDURE procedure_name(parameters list) is
BEGIN
58
//statements
END;
/
The procedure can be executed by just calling the procedure name with parameters in
other PL/SQL block. e.g.: procedure_name (actual values for the parameters);
Example: Create a procedure to print Hello world and execute the procedure.
FUNCTIONS
A function has a same structure as a procedure except:
• A function must include a RETURN clause, which specifies the data type of the
value that the function returns (A procedure heading cannot have a RETURN
clause)
• In the executable part of a function, every execution path must lead to a
RETURN statement. Otherwise, the PL/SQL compiler issues a compile-time
warning.
Syntax:
CREATE OR REPLACE FUNCTION function_name(variable_name datatype)
RETURN datatype
AS
//declare section
BEGIN
59
…….
RETURN var2 //variable of the return datatype
END;
/
Example 1: Create a function to return the sum of two numbers
create or replace function sum_number(a number, b number)
return number as
tot number;
begin
tot := a + b;
return tot;
end;
/
Example 2: A function that, given the name of a department, returns the count of the
number of instructors in that department. (Using University database schema)
This function can be used in a query that returns names and budgets of all departments
with more than 12 instructors:
60
select dept name, budget
from instructor
where dept count(dept name) > 12;
PACKAGES: A package is a schema object that groups logically related PL/SQL types,
variables, constants, subprograms, cursors, and exceptions. A package is compiled and
stored in the database, where many applications can share its contents. It is a way of
creating generic, encapsulated, re-usable code.
Features of Packages:
Modularity: Packages encapsulates logically related types, variables, constants,
subprograms, cursors, and exceptions in named PL/SQL modules.
Easier Application Design: When designing an application, initially only the interface
information is required in the package specifications. The specifications can be coded and
compiled without their bodies.
Information Hiding: Packages lets the user share your interface information in the
package specification, and hide the implementation details in the package body.
Added Functionality: Package public variables and cursors can persist for the life of a
session. They can be shared by all subprograms that run in the environment. They allow
maintaining data across transactions without storing it in the database.
Better Performance: The first time when a package subprogram is invoked, Oracle
Database loads the whole package into memory. Subsequent invocations of other
subprograms in same the package require no disk I/O. Packages prevent cascading
dependencies and unnecessary recompiling.
Easier to Grant Roles: The user can grant roles on the package, instead of granting roles
on each object in the package.
Example:
CREATE OR REPLACE PACKAGE BODY emp_bonus AS
PROCEDURE calc_bonus(date_hiredemployees.hire_date%TYPE) IS
BEGIN
DBMS_OUTPUT.PUT_LINE
('Employees hired on ' || date_hired || 'get bonus.');
END;
END emp_bonus;
/
Invoking a Package
Example: Invoking the ‘calc_bonus’ procedure in ‘emp_bonus’ package
Execute emp_bonus. calc_bonus(“14-Jan-2012”);
[or]
Call emp_bonus. calc_bonus(“14-Jan-2012”);
Example:
CREATE OR REPLACE PACKAGE emp_mgmt AS
FUNCTION hire (last_name VARCHAR2, job_id VARCHAR2, manager_id
NUMBER,
salary NUMBER, commission_pct NUMBER, department_id
NUMBER)
RETURN NUMBER;
62
FUNCTION create_dept(department_id NUMBER, location_id NUMBER)
RETURN NUMBER;
PROCEDURE remove_emp(employee_id NUMBER);
PROCEDURE remove_dept(department_id NUMBER);
PROCEDURE increase_sal(employee_id NUMBER, salary_incr
NUMBER);
PROCEDURE increase_comm(employee_id NUMBER, comm_incr
NUMBER);
no_comm EXCEPTION;
no_sal EXCEPTION;
END emp_mgmt;
/
The specification for the emp_mgmt package declares these public program objects:
• The functions hire and create_dept
• The procedures remove_emp, remove_dept, increase_sal, and increase_comm
• The exceptions no_comm and no_sal
Package Body:
CREATE OR REPLACE PACKAGE BODY emp_mgmt AS
FUNCTION hire (last_name VARCHAR2, job_id VARCHAR2, manager_id
NUMBER, salary NUMBER, commission_pct NUMBER, department_id
NUMBER)
RETURN NUMBER AS
//declare section
BEGIN
Note: Do not use OUT and IN OUT for function parameters. Ideally, a function takes
zero or more parameters and returns a single value. A function with IN OUT parameters
returns multiple values and has side effects. Regardless of how an OUT or IN OUT
parameter is passed:
• If the subprogram exits successfully, then the value of the actual parameter is the
final value assigned to the formal parameter. (The formal parameter is assigned at
least one value—the initial value.)
64
• If the subprogram ends with an exception, then the value of the actual parameter
is undefined.
• Formal OUT and IN OUT parameters can be returned in any order. In this
example, the final values of x and y are undefined:
Example 1:
A procedure that, given the name of a department, returns the count of the number of
instructors in that department.
Procedures can be invoked either from an SQL procedure or from embedded SQL by the
call statement:
Example 2: The procedure p has two IN parameters, one OUT parameter, and one IN
OUT parameter. The OUT and IN OUT parameters are passed by value (the default). The
anonymous block invokes p twice, with different actual parameters. Before each
invocation, the anonymous block prints the values of the actual parameters. The
procedure p prints the initial values of its formal parameters. After each invocation, the
anonymous block prints the values of the actual parameters again.
EXERCISE:
Procedures:
1. Write a procedure to display a message “Good Day to You”.
2. Based on the University Database Schema in Lab 2, write a procedure which takes
the dept_name as input parameter and lists all the instructors associated with the
department as well as list all the courses offered by the department. Also, write an
anonymous block with the procedure call.
3. Based on the University Database Schema in Lab 2, write a Pl/Sql block of code
that lists the most popular course (highest number of students take it) for each of
the departments. It should make use of a procedure course_popular which finds
the most popular course in the given department.
4. Based on the University Database Schema in Lab 2, write a procedure which takes
the dept-name as input parameter and lists all the students associated with the
department as well as list all the courses offered by the department. Also, write an
anonymous block with the procedure call.
Functions:
5. Write a function to return the Square of a given number and call it from an
anonymous block.
6. Based on the University Database Schema in Lab 2, write a Pl/Sql block of code
that lists the highest paid Instructor in each of the Department. It should make use
68
of a function department_highest which returns the highest paid Instructor for the
given branch.
Packages:
7. Based on the University Database Schema in Lab 2, create a package to include
the following:
a) A named procedure to list the instructor_names of given department
b) A function which returns the max salary for the given department
c) Write a PL/SQL block to demonstrate the usage of above package components
ADDITIONAL EXERCISE:
Procedures:
1. Based on the Banking Schema provided in Appendix, create payment
(loan_number, payment_number, payment_date, amount) table for the Bank
database.
(a) Write a procedure to find out loan amount issued and total payment done by a
customer.
(b) Write a procedure to find out total deposit and loan amount for the given
branch.
2. Based on the Banking Schema provided in Appendix, write a procedure which
takes the branch_name as input parameter and lists the names of all customers
belonging to that branch. Also, write an anonymous block with the procedure call.
69
Functions:
4. Based on the HR database schema in Appendix, write a function to return the net
salary given the employee number in the employees table and call the same from
an anonymous block.
5. Based on the University Database Schema in Lab 2, write a Pl/Sql block of code
that lists the most popular course (highest number of students take it) for each of
the departments. It should make use of a function course_popular which returns
the most popular course in the given department.
7. Based on the University Database Schema in Lab 2, write a Pl/Sql block of code
that lists the highest paid Instructor in each of the Department. It should make use
of a named procedure department_highest which finds the highest paid Instructor
for the given branch.
70
LAB NO.: 11 Date:
TRIGGERS
Objectives:
In this lab, student will be able to:
• Use triggers to enforce business logic in a database.
• Use Row triggers to enforce any constraint on a table.
• Understand the usage of “Instead Of” Triggers.
Triggers
A trigger is a named PL/SQL block that is stored in the database and run in response to
an event that occurs in the database. The user can specify the event (insert, update or
delete)
• whether the trigger fires before or after the event
• whether the trigger runs for each event or for each row affected by the event
Uses of Triggers
1. Enforce referential integrity constraints when child and parent tables are on different
nodes of the distributed database.
2. Prevent DML operations on a table after regular business hours.
3. Modify table data when DML statements are issued against views.
4. Enforce complex business rules that you cannot define with constraints.
Triggers vs Constraints
• A trigger applies on new data only while constraint holds true for the entire data
Eg.: a trigger can prevent a DML statement from inserting a NULL but the column
couldhave null prior.
• Constraints are easier to write and less error prone.
• But triggers can enforce complex business rules that constraints cannot.
Syntax:
CREATE OR REPLACE TRIGGER trigger_name
BEFORE(AFTER) INSERT OR UPDATE OF list of columns
OR DELETE on tablename
FOR EACH ROW
begin
CASE
WHEN INSERTING THEN
//set of actions
WHEN UPDATING(column1) THEN
//set of actions
71
WHEN DELETING THEN
//set of actions
END CASE;
END;
/
Example: A trigger to insert the records into the emp_delete table before deleting the
records from the employee table, based on the HR schema provided in the appendix.
CREATE OR REPLACE trigger emp_trigger
BEFORE DELETE ON employee
FOR EACH ROW
BEGIN
insert into emp_delete values(:OLD.emp_id,
:OLD.emp_name,
:OLD.emp_sal);
END;
/
Output:
delete from employee where emp_id=1101;
When you execute the above statement in the terminal the same
record is inserted in the emp_delete table.
INSTEAD OF TRIGGERS:
• It is created to perform data manipulation of views which cannot be performed
ingeneral.
• We cannot perform deletion or insertion on views if the view contains aggregate
functions or joins.
72
• An INSTEAD OF trigger is the only way to update a view that is not inherently
updatable.
• Consider a view which is joined on tables A and B. A delete operation on the view
is equivalent to deletion on A separately and B separately.
Syntax:
Create or replace trigger trigger_name
INSTEAD OF DELETE on view_name
FOR EACH ROW
BEGIN
//Set of Actions
END;
EXERCISE:
Row Triggers
1. Based on the University database Schema in Lab 2, write a row trigger that records
along with the time any change made in the Takes (ID, course-id, sec-id, semester,
year, grade) table in log_change_Takes (Time_Of_Change, ID, courseid,sec-id,
semester, year, grade).
2. Based on the University database schema in Lab: 2, write a row trigger to insert
the existing values of the Instructor (ID, name, dept-name, salary) table into a new
table Old_ Data_Instructor (ID, name, dept-name, salary) when the salary table is
updated.
Database Triggers
3. Based on the University Schema, write a database trigger on Instructor that checks
the following:
• The name of the instructor is a valid name containing only alphabets.
• The salary of an instructor is not zero and is positive
• The salary does not exceed the budget of the department to which theinstructor
belongs.
4. Create a transparent audit system for a table Client_master (client_no, name,
address, Bal_due). The system must keep track of the records that are being
deleted or updated. The functionality being when a record is deleted or modified
the original record details and the date of operation are stored in the auditclient
(client_no, name, bal_due, operation, userid, opdate) table, then the delete or
update is allowed to go through.
73
Instead of Triggers
5. Based on the University database Schema in Lab 2, create a view Advisor_Student
which is a natural join on Advisor, Student and Instructor tables. Create an
INSTEAD OF trigger on Advisor_Student to enable the user to delete the
corresponding entries in Advisor table.
Additional Exercise:
Row Triggers
1. Write a row trigger to update the Bal_Stock in item_master when a new
transaction is entered in the item_transaction
Database Triggers
2. Based on the Banking Schema provided in Appendix; write a database trigger on
Account that checks the following:
• The account for which transaction is performed is a valid account number
• The transaction amount is not zero and is positive
• In case of withdrawal, the amount does not exceed balance for that account
number
74
LAB NO.: 12 Mini Project (Phase II) Date:
Objectives:
• To develop an application that uses database to manage data.
Guidelines: Students need to submit the final report and demonstrate the application
developed as part of mini project.
Evaluation Guidelines:
75
REFERENCES:
76
APPENDIX:
BANKING SCHEMA
branch = ( branch_name, branch_city , assets )
customer = (customer_id , customer_name , customer_street, customer_city)
loan = (loan_number, amount)
account= (account_number, balance)
employee = ( employee_id,employee_name, telephone_number, start_date)
dependent_name = (employee_id, dname)
account_branch = (account_number, branch_name)
loan_branch = (loan_number, branch_name)
borrower = (customer_id, loan_number)
depositor = ( customer_id, account_number)
cust_banker = (customer_id, employee_id, type)
works_for= (worker_employee_id, manager_employee_id)
payment = (loan_number, payment_number, payment_date, payment_amount)
savings_account= (account_number, interest_rate)
checking_account = (account_number, overdraft_amount)
77
HR SCHEMA
78
ER Diagram
DIA Software: Dia is a diagramming application that can be used to make a large variety
of diagrams. Dia is easy to learn and flexible enough to allow users to create highly
customized diagrams. Below are two simple examples of diagrams that can quickly be
created using Dia.
Starting DIA:
You can start Dia by going into the Applications section on the Main Menu and clicking
on the Dia icon. Or, you can type dia in a console window.
Creating Canvas:
All diagrams are drawn in their own canvas. When you first start Dia, a blank canvas is
created automatically. At any time, you can create a new canvas by selecting File->New
Diagram. The canvas may be customized in various ways, such as changing the
background color or grid lines.
Making a Diagram:
A diagram is made up of objects. Objects are shapes or lines that can be different colors
and sizes. Objects can be simple line drawings, text, or full-color pictures. Some objects
allow text to be entered inside the shape. Using Dia to create a diagram is easy. The
Toolbox contains a palette of predefined objects, including simple shapes, lines, and
specialized objects. To add an object to the canvas, simply click on the desired object’s
icon on the Toolbox and then click on the desired point on the canvas. The object will
appear on the canvas where you clicked.
Dia provides the normal save and print options, located on the File menu. Selecting
the File -> Page Setup allows you to set the paper size, orientation, and print margins.
This also allows you to choose whether to print the diagram to scale (entered in percent)
or to fit the diagram to a specific size (in centimeters).
79
Dia supports exporting to numerous formats for excellent web publishing. Some of them
include:
• Computer Graphics Metafile (.cgm)
• Encapsulated Postscript (.eps)
• Portable Document Format (.pdf)
• Portable Network Graphics (.png)
• Scalable Vector Graphics (.svg)
80