You are on page 1of 64

CU / UIE / COMPUTER SCIENCE AND ENGINEERING / 2 1CSH-214

UNIVERSITY INSTITUTE OF ENGINEERING (UIE)

Department of Computer Science and Engineering

B.E. – Computer Science and Engineering

SEMESTER : Third

SUBJECT NAME : Database Management Systems Lab Manual

SUBJECT CODE : 21CSH-214

FACULTY : Gursimran Kaur


Contents of Course File

Sr. Particular
No.
1 University-Vision and Mission
2 Department-Vision and Mission
3 PEO
4 PO
5 PSO
6 Course Objectives
7 Course Outcomes
8 Mapping of COs/POs/PSOs
9 Syllabus (As approved in BOS)---(If Any
Changes required, Approval Copy from DAA)
10 List of Experiments (Mapped with Cos)
11 Experiment 1…10
Aim
Objective
Input/Apparatus Used
Procedure/Algorithm/Code
Observations/Outcome
Discussion
Question: Viva Voce
Vision of the University

“To be globally recognized as a Centre of Excellence for Research, Innovation, Entrepreneurship and
disseminating knowledge by providing inspirational learning to produce professional leaders for serving
the society.”

Mission of the University

M1: Providing world class infrastructure, renowned academicians and ideal environment for
Research, Innovation, Consultancy and Entrepreneurship relevant to the society.

M2: Offering programs & courses in consonance with National policies for nation building and
meeting global challenges.

M3: Designing Curriculum to match international standards, needs of Industry, civil society and for
inculcation of traits of Creative Thinking and Critical Analysis as well as Human and Ethical values.

M4: Ensuring students delight by meeting their aspirations through blended learning, corporate
mentoring, professional grooming, flexible curriculum and healthy atmosphere based on co-curricular
and extra-curricular activities.

M5: Creating a scientific, transparent and objective examination/evaluation system to ensure an ideal
certification.

M6: Establishing strategic relationships with leading National and International corporates and
universities for academic as well as research collaborations.

M7: Contributing for creation of healthy, vibrant and sustainable society by involving in Institutional
Social Responsibility (ISR) activities like rural development, welfare of senior citizens, women
empowerment, community service, health and hygiene awareness and environmental protection.
Vision of the Department

To be recognized as a leading Computer Science and Engineering department through effective teaching
practices and excellence in research and innovation for creating competent professionals with ethics,
values and entrepreneurial attitude to deliver service to society and to meet the current industry
standards at the global level.

Mission of the Department

M1: To provide practical knowledge using state-of-the-art technological support for the experiential
learning of our students.

M2: To provide industry recommended curriculum and transparent assessment for quality learning
experiences.

M3: To create global linkages for interdisciplinary collaborative learning and research.

M4: To nurture advanced learning platform for research and innovation for students‟ profound future
growth.

M5: To inculcate leadership qualities and strong ethical values through value based education.

Program Educational Objectives (PEOs)

PEO 1: To produce computer science graduate engineers with an ability to comprehend, understand and
analyze real life problems for providing sustainable solutions in the light of disruptive technologies.

PEO 2: To inculcate life-long learning skills in graduates preparing them for work in changing
environments and multidisciplinary teams in order to enhance their capability being globally
employable.

PEO 3: To instill leadership qualities in graduates with a sense of confidence, professionalism and
ethical attitude to produce professional leaders for serving the society.

PEO 4: To make the graduates adaptable to changing career opportunities who have the potential to
excel in industry/ public sector/ higher studies or entrepreneurship exhibiting global competitiveness.

Program Outcomes (POs)

PO1: Engineering knowledge: Apply the knowledge of Mathematics, Science, Engineering


fundamentals and computer science fundamental and strategies which have the solution of complex
computer science engineering problems.

PO2: Problem analysis: Identify, formulate, research literature, and analyze complex computer science
engineering problems reaching substantiated conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
PO3: Design/development of solutions: Design solutions for complex database and software
engineering problems and design system components or processes that meet the specified needs with
appropriate considerations for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of software engineering &networking based experiments, analysis and
Interpretation of data, and synthesis of the information to provide valid conclusions.

PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
Computer science engineering and IT tools including prediction and modelling to complex database or
software engineering activities with an understanding of the limitations.

PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
social, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
Professional Computer Science & Engineering practice.

PO7: Environment and sustainability: Understand the impact of the professional computer science
and engineering solutions in social and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development goals.

PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of computer science engineering practice

PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

PO10: Communication: Communicate effectively on complex computer science engineering activities


with the engineering community like CSI society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO11: Project management and finance: Demonstrate knowledge and understanding of the computer
science engineering and management principles and apply these to one‟s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life- long learning in the broadest context of computer science engineering changes

Program Specific Outcomes (PSOs)

A Graduate of Computer Science and Engineering Program will be able:

PSO1. To acquire proficiency in developing and implementing efficient solutions using emerging
technologies, platforms and Free and Open-Source Software (FOSS).

PSO2. To gain critical understanding of hardware and software tools catering to the contemporary needs
of IT industry.
Student Outcomes (SOs)

CAC- SOs

SO1 Analyze a complex computing problem and to apply principles of computing and other relevant
disciplines to identify solutions.

SO2 Design, implement and evaluate a computing-based solution to meet a given set of computing
requirements in the context of the program‟s discipline.

SO3 Communicate effectively in a variety of professional contexts.

SO4 Recognize professional responsibilities and make informed judgments in computing practice
based on legal and ethical principles.

SO5 Function effectively as a member or leader of a team engaged in activities appropriate to the
program‟s discipline.

SO6 Apply computer science theory and software development fundamentals to produce computing-
based solutions.

EAC- SOs

SO1 An ability to identify, formulate, and solve complex engineering problems by applying principles
of engineering, science, and mathematics

SO2 An ability to apply engineering design to produce solutions that meet specified needs with
consideration of public health, safety, and welfare, as well as global, cultural, social, environmental,
and economic factor

SO3 An ability to communicate effectively with a range of audiences

SO4 An ability to recognize ethical and professional responsibilities in engineering situations and make
informed judgments, which must consider the impact of engineering solutions in global, economic,
environmental, and societal context

SO5 An ability to function effectively on a team whose members together provide leadership, create a
collaborative and inclusive environment, establish goals, plan tasks, and meet objectives

SO6 An ability to develop and conduct appropriate experimentation, analyze and interpret data, and
use engineering judgment to draw conclusions

SO7 An ability to acquire and apply new knowledge as needed, using appropriate learning strategies.
Academic calendar
Syllabus

SN Program Code Course Title L T P C CH Course

- CS201 Database Management System Type

2 CourseCode- 3 0 2 4 5 CR

21CSH-214

Pre-requisite 21CSH-101, 21CSH-103

Co-requisite 21CSH-211, 21CSH-218

Anti-requisite 21CST-251,21CST-252,21CSR-264

a. Course Description

The main DBMS course, we learn about the structural formation of data, maintain data integrity,
multitasking with concurrent access and recovery without occurring crashes, data structures, data models
etc. and their working in which every organization is based. At the end of the course, the students may
understand the concepts of data structures, data models and design, construction of queries by using
SQL, uses and applications of database design etc.

b. Course Objectives
1. To have good understanding of database system concepts and design databases for different
applications.

2. To learn how to use a DBMS and RDBMS.

3. To implement and understand different types of DDL, DML and DCL statements.

4. To understand transaction concepts related to databases and recovery/backup techniques required


for the proper storage of data.

c. Course Outcomes

CO1 Understand the database system concepts and design databases for different

applications.

CO2 Identify different types of DDL, DML, DCL and TCL commands and their usage.

CO3 Classifying Normalization, Dependencies and Denormalization along with their


requirements.

CO4 Analyze and Compare Transaction Processing techniques and Recovery

techniques.
CO5 Evaluate database performance after implementing Triggers, procedures,

packages, cursors and views.

d. Syllabus

Unit I 15 Hours

Chapter 1.1 Overview of Databases: Database concepts, DBMS, Data Base System
Architecture (Three Level ANSI-SPARC Architecture), Advantages and
Disadvantages of DBMS, Data Independence, DBA and Responsibilities of
DBA, Relational Data Structure, Keys, Relations, Attributes, Schema and

Instances, Referential integrity, Entity integrity.

Chapter 1.2 Data Models: Relational Model, Network Model, Hierarchical Model, ER
Model: Design, issues, Mapping constraints, ER diagram, Comparison of

Models.

Chapter 1.3 Relational Algebra & Relational Calculus: Introduction, Syntax,


Semantics, Additional operators, Grouping and Ungrouping, Relational
comparisons, Tuple Calculus, Domain Calculus, Calculus Vs Algebra,
Computational

capabilities.

Experiment 1.1 To implement different types of DDL, DML, DCL queries.

Experiment 1.2 To explore “SELECT” clause using where, order by, between, like, group by,
having etc.

Experiment 1.3 Introduction and implementation of programs using Block Structure and

Variables.

Unit 2 15 Hours

Chapter 2.1 Functional dependencies and Normalization: Functional dependencies,


Decomposition, Full Functional Dependency (FFD), Transitive Dependency

(TD), Join Dependency (JD), Multi-valued Dependency (MVD), Normal


Forms (1NF, 2NF, 3NF, BCNF), De-normalization.

Chapter 2.2 Database Security: Introduction, Threats, Counter Measures.

Chapter 2.3 Control Structures: Introduction to conditional control, Iterative control

and sequential control statements, Cursors, Views.

Experiment 2.1 Introduction and implementation of programs using control structures If-
else statements and case statement.

Experiment 2.2 Introduction and implementation of programs using loops like: For, while,

Do-while.

Experiment 2.3 Introduction and implementation of programs using Cursors.

Experiment 2.4 Introduction and implementation of programs using Views.

Unit 3 15 Hours

Chapter 3.1 Package, Procedures and Triggers: Parts of procedures, Parameter modes,
Advantages of procedures, Syntax for creating triggers, Types of triggers,
package specification and package body, developing a package, Bodiless

package, Advantages of packages.

Chapter 3.2 Transaction Management and Concurrency Control: Introduction to


Transaction Processing, Properties of Transactions, Serializability and
Recoverability, Need for Concurrency Control, Locking Techniques, Time
Stamping Methods, Optimistic Techniques and Granularity of Data items.

Chapter 3.3 Database Recovery of database: Introduction, Need for Recovery, Types

of errors, Recovery Techniques.

Experiment 3.1 Introduction and implementation of programs of Procedures.

Experiment 3.2 Introduction and implementation of programs of Packages.

Experiment 3.3 Introduction and implementation of programs of Triggers.

e. Textbooks

1. RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The

Benjamin / Cummings Publishing Co.

2. Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.

3. Pratt,” DBMS”, Cengage Learning.


f. Reference books

1. C.J.Date, “An Introduction to Database Systems”, Addison Wesley.

2. Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to Design,
Implementation and Management”, 5/E, University of Paisley, Addison-Wesley.

3. Rob,” Database Principal Fundamental Design, Cengage Learning.

g. Assessment Pattern -Internal and External

The performance of student is evaluated as follows:

Theory Practical

Components Internal Mid Term End Term Continuous Mid Term End Term
Assessment Assessment Assessment Assessment Assessment Assessment

Marks 20 40 60 40 20 40

Total Marks 100 100

Internal Evaluation Component

Sr. Type of Weightage of Frequency Final Weightage in Remarks


Assessment Task actual conduct of Task Internal Assessment
No.
(Prorated Marks)

1. Assignment* 10 marks of each One Per 10 marks


Unit
assignment

2. Time Bound 12 marks of One Per 4 marks

Surprise Test each test Unit

3. Quiz 4 marks of each 2 Per Unit 4 marks

quiz

4. Mid-Semester 20 marks for 2 per 20 marks

Test** one MST. semester


5. Presentation*** Non Graded: Only for Self
Engagement Task Study MNG

Courses

6. Homework NA One per Non Graded:


lecture(of 2 Engagement Task

questions)

7. Discussion NA One per Non Graded:

Forum Chapter Engagement Task

8. Attendance and NA NA 2 marks


Engagement

Score on BB

h. CO-PO Mapping

Course PO 1 PO 2 PO 3 PO 4 PO 5 PO 6 PO 7 PO 8 PO 9 PO1 PO1 PO1 PSO PSO


0 1 2 1 2
Outcome

CO1 3 - 2 3 - - - - - 3 - 3 3 -

CO2 3 - 2 3 - - - - - 3 - 3 3 -

CO3 3 3 2 2 - - - - - 2 - 2 2 -

CO4 3 3 2 2 - - - - - 3 - 1 2 -

CO5 3 3 3 2 - - - - - 3 - 3 3 2
S. No List of Experiments Mapped CO

UNIT-I

CO2
To implement different types of DDL, DML, DCL queries.
I.

II. To explore “SELECT” clause using where, order by, between, like, CO2
group by, having etc.

Introduction and implementation of programs using Block Structure CO2


III. and Variables.

UNIT-II

Introduction and implementation of programs using control CO2


structures If-else statements and case statement.
IV.

V. Introduction and implementation of programs using loops like: For, CO2


while, Do-while.

CO5
Introduction and implementation of programs using Cursors.
VI.

Introduction and implementation of programs using Views. CO5

VII.

UNIT-III

VIII. CO5
Introduction and implementation of programs of Procedures.

Introduction and implementation of programs of Packages. CO5

IX.

X. Introduction and implementation of programs of Triggers. CO5


Experiment–I: To implement different types of DDL, DML, DCL queries.

AIM: Implement various commands of DDL, DML and DCL

S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL

1. CREATE Command:

This command is used to create relations or tables. The column name must be specified along the data types.
Each table must have at least one column.

Syntax: Create table <tablename>(col1,datatype, col2,datatype…… coln, datatype);

2. DESCRIBE Command:

It is use to describe the table. It includes information like table name, column name, data type etc.

Syntax: Describe <tablename>;

3.INSERT Command:

Records can be added to table using this command. Only one row can be inserted at a time.

Syntax: Insert into<tablename>(col1,col2…coln)values(List of values)


4. SELECT Command:

This command is used to show table data.

Syntax: Select * from <tablename>;

This command is used to select specific columns.

Syntax: Select distinct col1,col2 from <table name>;


5.DELETE Command:

It is used to remove rows from a table. The entire row can be deleted using this command.

Syntax: Delete from<table name> where condition;

As shown here the row is deleted and table is shown in next figure.

6.ALTER Command

It is use to make changes in table. It can be used to add a new column or modify an existing one. It is also used
to delete a column.
Modification using alter command:

Delete a specific column using alter command.

7.RENAME Command:

It is used to rename table.


Syntax: Rename old name to new name;

After rename the table is shown below.

8.TRUNCATE Command

This command is used to remove all rows from the table and to release the storage space used by that table.

Syntax: Truncate table <tablename>;

9.DROP Command

This command is used to remove the definition of a table. When you drop a table database loses all the data in
the table and all indexes associated with it.
10.UNION Command

It is used to combine the data of one or more columns of two tables with same data type.

Syntax: Select <column name> from<tablename1> union all Select <column name>
from<tablename2>;

11.MERGE Command

It is used to merge data of two distinct tables.

Syntax: Insert into <tablename1>(col1,col2) select col1,col2 from <tablename2>where condition;


Discussion

Q1. Create a table called Employee with the following structure.

Name Type

Empno Number

Ename Varchar2(10)

Job Varchar2(10)

Mgr Number

Sal Number

a. Add a column commission with domain to the Employee table.

b. Insert any five records into the table.

c. Update the column details of job

d. Rename the column of Employ table using alter command.

e. Delete the employee whose Empno is 105.

Q2. Create department table with the following structure.

Name Type

Deptno Number

Deptname Varchar2(10)

location Varchar2(10)
a. Add column designation to the department table.

b. Insert values into the table.

c. List the records of dept table grouped by deptno.

d. Update the record where deptno is 9.

e. Delete any column data from the table.

Q3. Create table EMP with the following description :

Name Type

EMPNO NOT NULL NUMBER(4)

ENAME VARCHAR2(10)

JOB VARCHAR2(9)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

COMM NUMBER(7,2)

DEPTNO NUMBER(3)

AGE NUMBER(3)

ESAL NUMBER

a. Get the description EMP table.

b. List all employees details.

c. List all employee names and their salaries, whose salary lies between 1500/- and 3500/- both inclusive.

d. List all employee names and their and their manager whose manager is 7902 or 7566 0r 7789.

e. List all employees who belongs to the department 10 or 20.

Viva-Voce Questions

Ques 1 How many types of database languages are?

Ques 2 What is DML (Data Manipulation Language)?

Ques 3 Explain the functionality of DML Compiler.


Experiment – II: To explore “SELECT” clause using where, order by, between, like, group by, having
etc.

AIM: Implementation of select command with its variants like where, order by, between, like, group by
and having.

S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL

1. Where clause:

Where clause is used along with SELECT command to specify the condition based on which rows will be
extracted from table

Syntax:Select * from tablename where condition;

2.Like Clause:

This operator is used for matching character patterns. The character pattern matching is called a wild card
search.

Syntax: select * from tablename where columnname like ’condition’;

3.InClause:

It is used to test for a values in the list.


Syntax: Select * from tablename where column name in(values);

4.BetweenClause:

It is used to specify a range of values. The range you specify contain lower and upper range.

Syntax:Select * from tablename where column name between value1 and value 2

5.Orderby clause:

It can be used to sort the rows. The clause sorts the query output according to the values in one or more
selected column.

Syntax: Select * from tablename order by column name;


6.And Clause:

It is used to check multiple condition if all conditions are true than output will be shown.

Syntax:Select * from tablename where col1 condition and col2 condition;

7.Or Clause:

It is used to check multiple condition if any one condition is true than output will be shown.

8.Groupby Clause:

It is used to collect data across multiple record and group the result by one or more columns.
Syntax:

Select column name,Function from tablename group by column name;

Discussion

Q1. Consider a relation Employee with following attributes:

Name Null Type

-------------------------------- ----------------------- -------------------------

EMPNO NOT NULL NUMBER(4)

ENAME VARCHAR2(10)

JOB VARCHAR2(9)

MGR NUMBER(4)

HIREDATE DATE

SAL NUMBER(7,2)

COMM NUMBER(7,2)

DEPTNO NUMBER(3)

AGE NUMBER(3)
ESAL NUMBER(10)

a. List minimum , maximum , average salaries of employee.

b. What is the difference between maximum and minimum salaries of employees in the organization?

c. Display all employee names and salary whose salary is greater than minimum salary of the company and job
title starts with „M‟.

d. Display total salary spent for each job category.

e. Display lowest paid employee details under each manager.

Q2. create table emp with attributes (eid number,ename varchar2(10),age number,salary number);

a. Count number of employee names from employee table.

b. Display the Sum of age employee table.

c. Find grouped salaries of employees (group by clause).

d. Find salaries of employee in Ascending Order (order by clause).

e. Find salaries of employee in Descending Order.

Q3. Consider the database for a college. Write the query for the following.

Insert at least 5 tuples into each table.

a. List the details of students in the ascending order of date of birth

b. Display the details of students from computer department

c. List the faculties in the descending order of salary

d. Display the total number of students in each department


e. Display the total number of faculties in each department with salary greater than 25000

Viva Voce Questions

Ques 1 Mention the issues with traditional file-based systems that make DBMS a better choice

Ques 2 Explain a few advantages of a DBMS

Ques 3 Are NULL values in a database the same as that of blank space or zero?

Ques 4 What is the difference between having and where clause?


Experiment–III: Introduction and implementation of programs using Block Structure and Variables.

AIM: Implementation of variables and block structure in PL/SQL

S/W Requirement: Oracle Database 11g Express Edition or oracle live SQL

Practical: Introduction to PL/SQL

 PL/SQL stands for Procedural Language extension of SQL.

 PL/SQL is a combination of SQL along with the procedural features of programming languages.

 It was developed by Oracle Corporation in the early 90‟s to enhance the capabilities of SQL.

The PL/SQL Engine:

Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored in the client
system (client-side) or in the database (server-side).

A Simple PL/SQL Block:

DECLARE

Variable declaration

BEGIN

Program Execution

EXCEPTION

Exception handling

END;

Declaration Section:

The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE. This section is
optional and is used to declare any placeholders like variables, constants, records and cursors, which are used
to manipulate data in the execution section.

Execution Section:

The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and ends with END. This
is a mandatory section and is the section where the program logic is written to perform any task. The
programmatic constructs like loops, conditional statement and SQL statements form the part of execution
section.

Exception Section:

The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This section is
optional. Any errors in the program can be handled in this section, so that the PL/SQL Blocks terminates
gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly
with errors.

Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks can be nested within
other PL/SQL blocks. Comments can be used to document code.

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

--I am a comment, so i will be ignored.

var varchar2(40) := 'Chandigarh University' ;

BEGIN

dbms_output.put_line(var);

END; /

Output:

Chandigarh University

PL/SQL procedure successfully completed.

Discussion

Ques1. Write a PL/SQL block to find Sum of Digits of a given Number.

Ques2. Write a PL/SQL program to SWAP two numbers with and without using temporary variables.

Ques3. Write a PL/SQL program to print reverse of a number. For example: 1234 print as 4321.

Viva Voce Questions

Ques 1 What are the features of PL/SQL?

Ques 2 What do you understand by PL/SQL table?

Ques 3 Explain the basic structure followed in PL/SQL?


UNIT-II

Experiment-IV: Introduction and implementation of programs using control structures If-else


statements and case statement.

AIM: To implement programs of control statements using PL/SQL

S/W Requirement: Oracle Database 11g Express Edition or Oracle live SQL.

Introduction:

The IF statement executes a sequence of statements depending on the value of a condition. There are three
forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.

IF-THEN Statement

The simplest form of IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF (not ENDIF), as follows:

IF condition THEN

sequence_of_statements

END IF;

IF-THEN-ELSE Statement

The second form of IF statement adds the keyword ELSE followed by an alternative sequence of
statements, as follows:

IF condition THEN

sequence_of_statements1

ELSE

sequence_of_statements2

END IF;

IF-THEN-ELSIF Statement

Sometimes you want to select an action from several mutually exclusive alternatives. The third form
of IF statement uses the keyword ELSIF (not ELSEIF) to introduce additional conditions, as follows:

IF condition1 THEN

sequence_of_statements1

ELSIF condition2 THEN


sequence_of_statements2

ELSE

sequence_of_statements3

END IF;

For example:

DECLARE

sales NUMBER(8,2) := 12100;

quota NUMBER(8,2) := 10000;

bonus NUMBER(6,2);

emp_idNUMBER(6) := 120;

BEGIN

IF sales > (quota + 200) THEN

bonus := (sales - quota)/4;

ELSE

IF sales > quota THEN

bonus := 50;

ELSE

bonus := 0;

END IF;

END IF;

UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;

END;

Case Statement in PL/SQL

The CASE statement in PL/SQL is similar to the IF-ELSEIF condition where different conditions are listed
within a block and only that statements get executed for which it satisfies the condition. CASE statement
matches the expression value instead of a Boolean expression. The expression could be of any data type
and the same data type has to be used in the statements. Each statement has a predefined value and if that
value matches up with the values passed in the selector expression then that particular statement gets
executed. In this topic, we are going to learn about the CASE statement in PL/SQL.
Syntax

Now that you have got a gist of what a CASE statement in PL/SQL is let‟s have a look at the syntax of the
CASE statement.

CASE (expression)

WHEN <value_l> THEN statement_l;

WHEN <value_2> THEN statement_2;

WHEN <value_3> THEN statement_3;

ELSE default_statement;

END CASE;

Code Explanation

In the syntax above, the expression will return a value of any data type, all the statements will have a
predefined unique value, the CASE expression will go through all the statements until it gets the exact
match defined in the value expression, in this case, Value_1, Value_2, and Value_3. If the Case expression
didn‟t find the match in the statement, then the default statement will get executed.

Note that the ELSE block is optional and if you do not want any default statement to get executed you can
skip this statement. The END Case is a mandatory part of the case.

Example

The CASE statement can be used in Oracle/PLSQL.

You could use the CASE statement in a SQL statement as follows: (includes the expression clause)

SELECT table_name,

CASE owner

WHEN 'SYS' THEN 'The owner is SYS'

WHEN 'SYSTEM' THEN 'The owner is SYSTEM'

ELSE 'The owner is another value'

END

FROM all_tables;

Or you could write the SQL statement using the CASE statement like this: (omits the expression clause)

SELECT table_name,
CASE

WHEN owner='SYS' THEN 'The owner is SYS'

WHEN owner='SYSTEM' THEN 'The owner is SYSTEM'

ELSE 'The owner is another value'

END

FROM all_tables;

The above two CASE statements are equivalent to the following IF-THEN-ELSE statement:

IF owner = 'SYS' THEN

result := 'The owner is SYS';

ELSIF owner = 'SYSTEM' THEN

result := 'The owner is SYSTEM'';

ELSE

result := 'The owner is another value';

END IF;

The CASE statement will compare each owner value, one by one.

One thing to note is that the ELSE clause within the CASE statement is optional. You could have omitted
it. Let's look at the SQL statement above with the ELSE clause omitted.

Your SQL statement would look as follows:

SELECT table_name,

CASE owner

WHEN 'SYS' THEN 'The owner is SYS'

WHEN 'SYSTEM' THEN 'The owner is SYSTEM'

END

FROM all_tables;

With the ELSE clause omitted, if no condition was found to be true, the CASE statement would return
NULL.
Discussion

Ques 1 Write a PL/SQL program to check whether a date falls on weekend i.e. SATURDAY or SUNDAY.

Ques 2 Write a PL/SQL program to display the description against a grade according to the marks achieved
by students in their final exams.

Ques 3 Write a PL/SQL program to identify whether a character entered by user is letter or digit.

Viva voce questions:

Ques 1 How can a name be assigned to an unnamed PL/SQL Exception Block?

Ques 2 When does a DECLARE block become mandatory?

Ques 3 How do you write comments in a PL/SQL code?


Experiment-V:Introduction and implementation of programs using loops like: For, while, Do-while.

AIM: To implement loops in PL/SQL

S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL

A loop marks a sequence of statements that has to be repeated. The keyword loop has to be placed before the
first statement in the sequence of statements to be repeated, while the keyword end loop is placed immediately
after the last statement in the sequence.

Once a loop begins to execute, it will go on forever. Hence a conditional statement that controls the number of
times a loop is executed always accompanies loops.

PL/SQL supports the following structures for iterative control:

Simple loop :

In simple loop, the key word loop should be placed before the first statement in the sequence and the keyword
end loop should be written at the end of the sequence to end the loop.

Syntax:

Loop

< Sequence of statements >

End loop;

Example:

create file named it.sql

DECLARE

inumber := 0;

BEGIN

LOOP

dbms_output.put_line ('i = '||i);

i:=i+1;

EXIT WHEN i>=11;

END LOOP;

END;
Output:

Run SQL Command Line

SQL>set serveroutput on

SQL>start d://it.sql

i=0

i=1

i=2

i=3

i=4

i=5

i=6

i=7

i=8

i=9

i = 10

PL/SQL successfully completed.

WHILE loop

The while loop executes commands in its body as long as the condition remains true

Syntax :

WHILE < condition >

LOOP

< Action >

END LOOP

Example 1 :

find reverse of given number using while loop

DECLARE
numNumber(3) :=123;

ansNumber(3) :=0;

iNumber(3) :=0;

BEGIN

WHILE num != 0

LOOP

i:=mod(num,10);

ans:=(ans * 10 ) + i;

num:=floor(num/10);

END LOOP;

dbms_output.put_line('reverse of given number is: ' || ans);

END;

Output :

Run SQL Command Line

SQL>set serveroutput on

SQL>start d://rev.sql

reverse of given number is: 321

PL/SQL successfully completed.

Example 2 :

DECLARE n_counter NUMBER := 1;

BEGIN

WHILE n_counter<= 5
LOOP

DBMS_OUTPUT.PUT_LINE( 'Counter : ' || n_counter );

n_counter := n_counter + 1

END LOOP;

END;

OUTPUT:

Counter : 1

Counter : 2

Counter : 3

Counter : 4

Counter : 5

PL/SQL procedure successfully completed.

The FOR Loop

The FOR loop can be used when the number of iterations to be executed are known.

Syntax :

FOR variable IN [REVERSE] start..end

LOOP

< Action >

END LOOP;

The variable in the For Loop need not be declared. Also the increment value cannot be specified. The For
Loop variable is always incremented by 1.

Example 1 :

DECLARE

inumber ;

BEGIN

FOR i IN 1 .. 10

LOOP
dbms_output.put_line ('i = '||i);

END LOOP;

END;

Output :

Run SQL Command Line

SQL>set serveroutput on

SQL>start d://it.sql

i=1

i=2

i=3

i=4

i=5

i=6

i=7

i=8

i=9

i = 10

PL/SQL successfully completed.

Example 2 :

DECLARE

a number(2);

BEGIN

For a in 10 ….20 LOOP

Dbms_output.put_line(„value of a:‟ || a);

END loop;

END;
OUTPUT:

value of a: 10

value of a: 11

value of a: 12

value of a: 13

value of a: 14

value of a: 15

value of a: 16

value of a: 17

value of a: 18

value of a: 19

value of a: 20

PL/SQL procedure successfully completed.

Discussion

Ques 1Write a program in PL/SQL to print the value of a variable inside and outside a loop using LOOP EXIT
statement.

Ques 2Write a program in PL/SQL to print 1st n numbers with a difference of 3 and starting from 1.

Ques 3Write a program in PL/SQL to insert records from one table to another.

Viva Voce Questions

Ques 1 How do you write comments in a PL/SQL code?

Ques 2 Can you explain the PL/SQL execution architecture?

Ques 3 What is the importance of %TYPE and %ROWTYPE data types in PL/SQL?
Experiment-VI:Introduction and implementation of programs of Cursors

AIM: To implement various programs using triggers

S/W Requirement: Oracle Database 11g Express Edition or Oracle Live SQL

Cursors

Oracle creates a memory area, known as context area, for processing an SQL statement, which
contains all information needed for processing the statement, for example, number of rows
processed etc.

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.

You can name a cursor so that it could be referred to in a program to fetch and process the rows
returned by the SQL statement, one at a time. There are two types of cursors:

Implicit Cursors

Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement.

Attribute Description

%FOUND

Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND

The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE


statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

%ISOPEN

Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically
after executing its associated SQL statement.

%ROWCOUNT
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.

Explicit Cursors

Explicit cursors are programmer defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.

Syntax

Working with an explicit cursor involves four steps:

 Declaring the cursor for initializing in the memory

 Opening the cursor for allocating memory

 Fetching the cursor for retrieving data

 Closing the cursor to release allocated memory

Declaring the Cursor

Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example:

CURSOR c_customers IS SELECT id, name, address FROM customers;

Opening the Cursor

Opening the cursor allocates memory for the cursor, and makes it ready for fetching the rows
returned by the SQL statement into it. For example :

OPEN c_customers;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example:

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor

Closing the cursor means releasing the allocated memory. For example, we will close above
opened cursor as follows:

CLOSE c_customers;

EXAMPLE
Discussion

Ques 1Write a program in PL/SQL to find the number of rows effected by the use of
SQL%ROWCOUNT attributes of an implicit cursor.

Ques 2Write a program in PL/SQL to show the uses of SQL%FOUND to determine if a


DELETE statement affected any rows.

Ques 3Write a program in PL/SQL to FETCH multiple records and more than one columns from
the same table.

Viva Voce Questions

Ques 1 What is a PL/SQL cursor?

Ques 2 What is the use of WHERE CURRENT OF in cursors?

Ques 3 Differentiate between implicit cursor and explicit cursor.


Experiment-VII: Introduction and implementation of programs using Views.

AIM: Implementation of Views

S/W Requirement: Oracle Database 11g Express Edition

VIEW

 A view is a virtual table.

 In SQL, a view is a virtual table based on the result-set of an SQL statement.

 A view contains rows and columns, just like a real table. The fields in a view are fields
from one or more real tables in the database.

 You can add SQL functions, WHERE, and JOIN statements to a view and present the
data as if the data were coming from one single table.

Syntax

CREATE VIEW view_name AS

SELECT column_name(s)

FROM table_name

WHERE condition

Employee table
View emp1

Discussion:

Q1. Consider the following table:

1. Write a query to create a view for those salesmen belonging to the city New York.
2. Write a query to create a view for all salesmen with columns salesman_id, name, and
city.

Q2. Consider the following relation Customer:

Write a query to create a view to getting a count of how many customers we have at each level
of a grade.

Q3. Consider the following relations:

Salesman

salesman_id | name | city | commission

-------------+------------+----------+------------

5001 | James Hoog | New York | 0.15

5002 | Nail Knite | Paris | 0.13

5005 | Pit Alex | London | 0.11

5006 | Mc Lyon | Paris | 0.14

5007 | Paul Adam | Rome | 0.13

5003 | Lauson Hen | San Jose | 0.12

Customer
customer_id | cust_name | city | grade | salesman_id

-------------+----------------+------------+-------+-------------

3002 | Nick Rimando | New York | 100 | 5001

3007 | Brad Davis | New York | 200 | 5001

3005 | Graham Zusi | California | 200 | 5002

3008 | Julian Green | London | 300 | 5002

3004 | Fabian Johnson | Paris | 300 | 5006

3009 | Geoff Cameron | Berlin | 100 | 5003

3003 | Jozy Altidor | Moscow | 200 | 5007

3001 | Brad Guzan | London | | 5005

Orders

ord_no purch_amt ord_date customer_id salesman_id

---------- ---------- ---------- ----------- -----------

70001 150.5 2012-10-05 3005 5002

70009 270.65 2012-09-10 3001 5005

70002 65.26 2012-10-05 3002 5001

70004 110.5 2012-08-17 3009 5003

70007 948.5 2012-09-10 3005 5002

70005 2400.6 2012-07-27 3007 5001

70008 5760 2012-09-10 3002 5001

70010 1983.43 2012-10-10 3004 5006

70003 2480.4 2012-10-10 3009 5003

70012 250.45 2012-06-27 3008 5002

70011 75.29 2012-08-17 3003 5007


70013 3045.6 2012-04-25 3002 5001

Write a query to create a view that shows for each order the salesman and customer by
name.

Viva Voce Questions

Ques 1 Differentiate between SQL and PL/SQL.

Ques 2 What is the difference between a mutating table and a constraining table?

Ques 3 What are COMMIT, ROLLBACK and SAVEPOINT statements in PL/SQL?


Experiment VIII Introduction and implementation of programs of Procedures.

AIM: To implement procedure‟s programs

S/W Requirement: Oracle Database 11g Express Edition

Procedure

A procedure or in simple a proc is a named PL/SQL block which performs one or more specific
task. This is similar to a procedure in other programming languages.

A procedure has a header and a body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block.

There are three types of parameters that can be declared:

IN - The parameter can be referenced by the procedure or function. The value of the parameter
cannot be overwritten by the procedure or function.

OUT - The parameter can not be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.

IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.

Syntax

CREATE [OR REPLACE] PROCEDURE procedure_name

[ (parameter [,parameter]) ]

IS

[declaration_section]

BEGIN

executable_section

[EXCEPTION

exception_section]

END [procedure_name];
How to execute a Procedure?

There are two ways to execute a procedure.

1) From the SQL prompt.

EXECUTE [or EXEC] procedure_name;

2) Within another procedure – simply use the procedure name.

procedure_name;

Example:

Before executing Procedure

After executing Procedure


Discussion

Ques 1 Write a procedure and call it into main pl/sql program to find a factorial of a number.
Ques 2 Create a procedure or function to calculate electricity bill as per the following criteria:
For first 100 units: Rs. 5 per unit
For 101-150 units: Rs. 7 per unit
For 151-300 units: Rs. 7.50 per unit
For 301 onward units: Rs. 8 per unit
Ques 3 Create Local procedure to calculate the simple interest by passing the values of principal,
rate and time.

Viva Voce Questions

Ques 1 What is the use of SYS.ALL_DEPENDENCIES?

Ques 2 Differentiate between the cursors declared in procedures and the cursors declared in the
package specifications.

Ques 3 How can you debug your PL/SQL code?


Experiment IX Introduction and implementation of programs of Packages.

AIM: To implement packages

S/W Requirement: Oracle Database 11g Express Edition

Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.

A package will have two mandatory parts −

 Package specification

 Package body or definition

Package Specification

The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the package.
In other words, it contains all information about the content of the package, but excludes the
code for the subprograms.

All objects placed in the specification are called public objects. Any subprogram not in the
package specification but coded in the package body is called a private object.You can have
many global variables defined and multiple procedures or functions inside a package.

CREATE PACKAGE cust_sal AS

PROCEDURE find_sal(c_idcustomers.id%type);

END cust_sal;

When the above code is executed at the SQL prompt, it produces the following result −

Package created.

Package Body

The package body has the codes for various methods declared in the package specification and
other private declarations, which are hidden from the code outside the package.

The CREATE PACKAGE BODY Statement is used for creating the package body. The
following code snippet shows the package body declaration for the cust_sal package created
above. I assumed that we already have CUSTOMERS table created in our database as mentioned
in the PL/SQL - Variables chapter.

CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_idcustomers.id%TYPE) IS

c_salcustomers.salary%TYPE;

BEGIN

SELECT salary INTO c_sal

FROM customers

WHERE id = c_id;

dbms_output.put_line('Salary: '|| c_sal);

END find_sal;

END cust_sal;

When the above code is executed at the SQL prompt, it produces the following result −

Package body created.

Packages

CREATE OR REPLACE PACKAGE BODY c_package AS

PROCEDURE addCustomer(c_idcustomers.id%type,

c_namecustomers.name%type,

c_agecustomers.age%type,

c_addrcustomers.address%type,

c_salcustomers.salary%type)

IS

BEGIN

INSERT INTO customers (id,name,age,address,salary)


VALUES(c_id,c_name,c_age,c_addr,c_sal);

ENDaddCustomer;

PROCEDURE delCustomer(c_idcustomers.id%type) IS

BEGIN

DELETE FROM customers

WHERE id =c_id;

ENDdelCustomer;

PROCEDURE listCustomer IS

CURSOR c_customersis

SELECT name FROM customers;

TYPE c_listis TABLE OF customers.name%type;

name_listc_list:=c_list();

counter integer :=0;

BEGIN

FOR n IN c_customers LOOP

counter := counter +1;

name_list.extend;

name_list(counter):= n.name;

dbms_output.put_line('Customer('||counter||')'||name_list(counter));

END LOOP;

ENDlistCustomer;

ENDc_package;
Discussion

Ques 1 Implement a package for a shopping store?

Ques 2 Implement a package for insertion in university database?

Viva Voce Questions

Ques 1 when do SQL packages get created?

Ques 2 How are SQL packages named?

Ques 3 What are the advantages of using SQL packages?


Experiment X: Introduction and implementation of programs of Triggers.

AIM: To implement triggers

S/W Requirement: Oracle Database 11g Express Edition

Triggers are simply stored procedures that are ran automatically by the database whenever some
event (usually a table update) happens. The trigger is mostly used for keeping the integrity of the
information on the database. For example, when a new record (representing a new worker) is
added to the employees table, new records should be created also in the tables of the taxes,
vacations, and salaries.

Uses:-Triggers are commonly used to:

 audit changes (e.g. keep a log of the users and roles involved in changes)

 enhance changes (e.g. ensure that every change to a record is time-stamped by the
server's clock)

 enforce business rules (e.g. require that every invoice have at least one line item)

 execute business rules (e.g. notify a manager every time an employee's bank account
number changes)

 replicate data (e.g. store a record of every change, to be shipped to another database later)

 enhance performance (e.g. update the account balance after every detail transaction, for
faster queries)

The examples above are called Data Manipulation Language (DML) triggers because the triggers
are defined as part of the Data Manipulation Language and are executed at the time the data is
manipulated. Some systems also support non-data triggers, which fire in response to Data
Definition Language (DDL) events such as creating tables, or runtime or and events such as
logon, commit, and rollback. Such DDL triggers can be used for auditing purposes.

PL/SQL Triggers:-Triggers are basically PL/SQL procedures that are associated with tables,
and are calledwhenever a certain modification (event) occurs. The modification statements may
include INSERT, UPDATE, and DELETE.

The general structure of triggers is:

CREATE [OR REPLACE]

TRIGGER trigger_name
BEFORE (or AFTER)

INSERT OR UPDATE [OF COLUMNS] OR DELETE

ON tablename

[FOR EACH ROW [WHEN (condition)]]

BEGIN

...

END;

TRIGGER specifies just what type of object we are creating. The BEFORE (or AFTER) in the
trigger definition refers to when you want to run the trigger, either before the actual database
modification (update, delete, insert) or after.

Permissions:-Just like with procedures and functions, creating triggers requires certain
privileges which are not part of the default privilege set. If you cannot create triggers from these
notes because of permissions, you (or the admin) has to GRANT CREATE TRIGGER privilege
on your username. For example, to allow user „alex‟ to create triggers, I may do something like
this:

GRANT CREATE TRIGGER TO alex;

Sample Table to be Triggered:-Before we begin playing with triggers, let‟s create a simple
table with which we can experiment:

CREATE TABLE PERSON ( ID INT, NAME VARCHAR(30), DOB DATE, PRIMARY


KEY(ID) );

Before Insert Trigger:-We write a trigger to fire before theinsert takes place.

CREATE OR REPLACE

TRIGGER PERSON_INSERT_BEFORE

BEFORE

INSERT

ON PERSON

FOR EACH ROW

BEGIN
DBMS_OUTPUT.PUT_LINE(‟BEFORE INSERT OF ‟ || :NEW.NAME);

END;

Now let us test it out:

INSERT INTO PERSON(ID,NAME,DOB) VALUES (1,‟JOHN DOE‟,SYSDATE);

The single INSERT statement fires the trigger. When we run it, we get the print out of ‟BEFORE
INSERT OF JOHN DOE‟.

SQL> INSERT INTO PERSON(ID,NAME,DOB) VALUES (1,‟JOHN DOE‟,SYSDATE);

BEFORE INSERT OF JOHN DOE

After Insert Trigger:-

CREATE OR REPLACE

TRIGGER PERSON_INSERT_AFTER

AFTER

INSERT

ON PERSON

FOR EACH ROW

BEGIN

DBMS_OUTPUT.PUT_LINE(‟AFTER INSERT OF ‟ || :NEW.NAME);

END;

And with our 2nd test INSERT:

INSERT INTO PERSON(ID,NAME,DOB) VALUES (2,‟JANE DOE‟,SYSDATE);

For a total result of:

SQL> INSERT INTO PERSON(ID,NAME,DOB) VALUES (2,‟JANE DOE‟,SYSDATE);


BEFORE INSERT OF JANE DOE

AFTER INSERT OF JANE DOE

Before Update Statement Trigger:-Now that we have some data in the table, we can create an
update trigger, that would firewhenever someone tries to update any person (or persons).

CREATE OR REPLACE

TRIGGER PERSON_UPDATE_S_BEFORE

BEFORE UPDATE

ON PERSON

BEGIN

DBMS_OUTPUT.PUT_LINE(‟BEFORE UPDATING SOME PERSON(S)‟);

END;

Now, let‟s run an update...

UPDATE PERSON SET DOB = SYSDATE;

Which produces the result:

SQL> UPDATE PERSON SET DOB = SYSDATE;

BEFORE UPDATING SOME PERSON(S)

Trigger Exceptions:- Triggers become part of the transaction of a statement, which implies that
it causes (or raises) any exceptions (which we‟ll talk about later), the whole statement is rolled
back. Think of an exception as a flag that is raised when an error occurs. Sometimes, an error (or
exception) is raised for a good reason.

For example, to prevent some action that improperly modifies the database. Let‟s say that our
database should not allow anyone to modify their DOB (after the person is in the database, their
DOB is assumed to be static). Anyway, we can create a trigger that would prevent us from
updating the DOB:

CREATE OR REPLACE

TRIGGER PERSON_DOB

BEFORE UPDATE OF DOB ON PERSON


FOR EACH ROW

BEGIN

RAISE_APPLICATION_ERROR(-20000,‟CANNOT CHANGE DATE OF BIRTH‟);

END;

When we do the actual update for example:

UPDATE PERSON SET DOB = SYSDATE;

We end up with an error, that says we CANNOT CHANGE DATE OF BIRTH.

SQL> UPDATE PERSON SET DOB = SYSDATE;

UPDATE PERSON SET DOB = SYSDATE

ERROR at line 1:

ORA-20000: CANNOT CHANGE DATE OF BIRTH

ORA-06512: at "PARTICLE.PERSON_DOB", line 2

ORA-04088: error during execution of trigger ‟PARTICLE.PERSON_DOB‟

You should also notice the error code of ORA-20000. This is our -20000 parameter.

Viewing Triggers:- You can see all your user defined triggers by doing a select statement on
USER_TRIGGERS.

For example:

SELECT TRIGGER_NAME FROM USER_TRIGGERS;

Which produces the names of all triggers. You can also select more columns to get more detailed
trigger information.

Dropping Triggers:-You can DROP triggers just like anything. The general format would be
something like:

DROP TRIGGER trigger_name;


Altering Triggers:-If a trigger seems to be getting in the way, and you don‟t want to drop it, just
disable it fora little while, you can alter it to disable it. Note that this is not the same as dropping
atrigger; after you drop a trigger, it is gone.

The general format of an alter would be something like this:

ALTER TRIGGER trigger_name [ENABLE|DISABLE];

For example:-

ALTER TRIGGER PERSON_DOB DISABLE;

Triggers

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers

FOR EACH ROW

WHEN (NEW.ID >0)

DECLARE

sal_diff number;

BEGIN

sal_diff:=:NEW.salary-:OLD.salary;

dbms_output.put_line('Old salary: '||:OLD.salary);

dbms_output.put_line('New salary: '||:NEW.salary);

dbms_output.put_line('Salary difference: '||sal_diff);

END;

Discussion

Ques 1 Implement trigger to update the increment on salary of employees.

Ques 2 Implement trigger to delete student details from result table when he leaves the course.
Viva voce Questions

Ques 1 What is meant by trigger?

Ques 2 Maximum of how many triggers is possible to apply on one table?

Ques 3 What are the virtual tables available during the execution of the database trigger?

You might also like