0% found this document useful (0 votes)
27 views

DBMS File

Uploaded by

ares4006115
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

DBMS File

Uploaded by

ares4006115
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

PRACTICAL NO.

AIM: Introduction to SQL and installation of SQL server/Oracle.

1. INTRODUCTION TO DBMS:
A Database Management System (DBMS) is a software system that is designed to manage and organize
data in a structured manner. A database management system (or DBMS) is essentially nothing more than
a computerized data-keeping system.
Users of the system are given facilities to perform several kinds of operations on such a system for
either manipulation of the data in the database or the management of the database structure itself.
It can be used for:
 Creation of a database.
 Retrieval of information from the database.
 Updating the database.
 Managing a database.
 Multiple User Interface
 Data scalability, expandability and flexibility
 Security

2. COMPONENTS OF DBMS:

Storage Engine: The storage engine is the core component of the DBMS that interacts with the file
system at an OS level to store data. All SQL queries which interact with the underlying data go through
the storage engine.
Query language: A database access language is required for interacting with a database, from creating
databases to simply inserting or retrieving data. A proper DBMS must support one or multiple query
languages and language dialects. Structured query language (SQL) and MongoDB Query Language
(MQL) are two query languages that are used to interact with the databases.
In many query languages, the query language functionality can be further categorized according to
specific tasks:

 Data Definition Language (DDL). This consists of commands that can be used to define database
schemas or modify the structure of database objects.
 Data Manipulation Language (DML). Commands that directly deal with the data in the database.
All CRUD operations come under DML.
 Data Control Language (DCL). This deals with the permissions and other access controls of the
database.
 Transaction Control Language (TCL). Command which deals with internal database
transactions.

Query Processor: This is the intermediary between the user queries and the database. The query
processor interprets the queries of users and makes them actionable commands that can be understood by
the database to perform the appropriate functionality.

Optimization Engine: The optimization Engine allows the DBMS to provide insights into the
performance of the database in terms of optimizing the database itself and queries. When coupled
with database monitoring tools, it can provide a powerful toolset to gain the best performance out of the
database.

Metadata Catalog: This is the centralized catalog of all the objects within the database. When an object
is created, the DBMS keeps a record of that object with some metadata about it using the metadata
catalog. Then, this record can be used to:

Verify user requests to the appropriate database objects

Provide an overview of the complete database structure

Log Manager: This component will keep all the logs of the DBMS. These logs will consist of user logins
and activity, database functions, backups and restore functions, etc. The log manager ensures all these logs
are properly recorded and easily accessible.

Reporting and Monitoring tools: Reporting and monitoring tools are another standard component that
comes with a DBMS. Reporting tools will enable users to generate reports while monitoring tools enable
monitoring the databases for resource consumption, user activity, etc.

Data Utilities: In addition to all the above, most DBMS software comes with additional inbuilt utilities to
provide functionality such as:

Data integrity checks

Backup and restore

Simple database repair


Data validations

Etc.

3. ORACLE

Oracle database is a relational database management system. It is also called OracleDB, or simply Oracle.
It is produced and marketed by Oracle Corporation. It was created in 1977 by Lawrence Ellison and other
engineers. It is one of the most popular relational database engines in the IT market for storing,
organizing, and retrieving data.

Oracle database was the first DB that designed for enterprise grid computing and data warehousing.
Enterprise grid computing provides the most flexible and cost-effective way to manage information and
applications. It uses SQL queries as a language for interacting with the database.

4. FEATURES OF ORACLE

Oracle database manages data with the help of an open, complete, and integrated approach. The
following are features that complete the demand for powerful database management:

Availability: It is never offline or out of service that means supported 24*7 availability of the
database. It provides high availability of databases because of the Oracle Data Guard functionality.
This functionality allows using of the secondary database as a copy of the primary database during
any failure. As a result, all normal processes such as backups and partial failures do not interrupt
the database from being used.

Security: Oracle has a mechanism for controlling and accessing the database to prevent
unauthorized access. It provides high security because of the Oracle Advanced Security features. It
offers two solutions to protect databases that are TDE (Transparent Data Encryption) and Data
Redaction. TDE supports data encryption both at the source and after export. Redaction is
performed at the application level. Oracle has some other security features like Oracle Database
Vault that regulates user privileges and Oracle Label Security.

Scalability: It provides features like RAC (Real Application Cluster) and Portability, which makes
an Oracle database scalable based on usage. In a clustered environment, it includes capabilities
such as rolling instance migrations, performing upgrades, maintaining application continuity,
quality of service management, etc.

Performance: Oracle provides performance optimization tools such as Oracle Advanced


Compression, Oracle Database In-Memory, Oracle Real Application Testing, and Oracle Times
Ten Application-Tier Database Cache. Their main objective is to improve system performance to
the highest possible level.

Analytics: Oracle has the following solutions in the field of analytics:

OLAP (Oracle Analytic Processing): It is an implementation of Oracle for doing complicated


analytical calculations on business data.

Oracle Advanced Analytics: It is a technical combination of Oracle R Enterprise and Oracle Data
Mining that assists customers in determining predictive business models through data and text
mining, as well as statistical data computation.

Management: Oracle Multitenant is a database management tool that combines a single container
database with many pluggable databases in a consolidated design.

5. INSTALLATION OF ORACLE DATABASE 10G ON WINDOWS

1. Insert Oracle CD , the autorun window opens automatically. If you are installing from network
or hard disk, click setup.exe in the installation folder.
2. The Oracle Universal Installer (OUI) will run and display the Select Installation
Method Window.
3. Choose Basic Installation:
Select this option to quickly install Oracle Database 10g. This method requires minimal user
input. It installs the software and optionally creates a general-purpose database based on the
information you provide.
For basic installation, you specify the following:
Oracle Home Location — Enter the directory in which to install the Oracle Database 10g
software. You must specify a new Oracle home directory for each new installation of Oracle
Database 10g. Use the default value, which is : c:\oracle\product\10.2.0\db_1

Installation Type — Select Enterprise Edition :


If you have limited space, select standard edition. Personal edition installs the same software as the
Enterprise Edition, but supports only a single-user development and deployment environment.
Create Starter Database — Check this box to create a database during installation. Oracle
recommends that you create a starter database for first Create Starter Database — time
installations. Choose a Global Database Name, like cs157b, or just use the default value.
Type a password. Don’t lose this password, since you will need it to connect to the database server.
Click next

4. The Product-Specific Prerequisite Checks window appears: Click next

5. A summary screen appears showing information such as your global settings, space
requirements and the new products to be installed. Click Install to start the installation
6. The Install window appears showing installation progress.

7. At the end of the installation phase, the Configuration Assistants window appears. This
window lists the configuration assistants that are started automatically.
If you are creating a database, then the Database Configuration Assistant starts automatically in
a separate window.
At the end of database creation, you are prompted to unlock user accounts to make the
accounts accessible. The SYS and SYSTEM accounts are already unlocked. Click OK to
bypass password management.

8. Your installation and database creation is now complete. The End of Installation window
displays several important URLs, one of which is for Enterprise Manager.
You can navigate to this URL in your browser and log in as the SYS user with the associated
password, and connect as SYSDBA. You use Enterprise Manager to perform common database
administration tasks

PRACTICAL NO.2

AIM: Data Types , Creating Tables, Retrieval of Rows using Select Statement ,
Conditional Retrieval of rows , Alter and Drop Statements.

DATATYPES:
Data Types are means to identify the type of data and associated operations for handling it. A value’s
datatype associates a fixed set of properties of with value. Some commonly used data types supported by
SQL are:

 Char: A fixed length character string.


 Varchar: A variable length character string.
 Int: A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from
0 to 4294967295.
 Double: A normal-size floating point number.
 Date: A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'.

CREATE TABLE
Tables are defined with CREATE TABLE command. When a table is created, its columns are named, data
types and sizes are supplied for each column.

Syntax for create table command:


create table <table-name>
(<column-name> <data-type> [(<size>)],
<column-name> <data-type> [(<size>)…]);

RETRIEVAL OF ROWS
The SELECT statement is used to pull information from a table. To retrieve all the rows of any table, we
just need to specify asterisk in select-list

Syntax for selecting all rows:


select * from <table-name>

CONDITIONAL RETRIEVAL OF ROWS


We can select particular rows from a table by specifying filtering condition through WHERE clause of the
SELECT statement

Syntax for where clause:


select <column(s)>
from <table-name>
where<condition to specify>

ALTER TABLE
The ALTER TABLE command is used to change definitions of existing tables. Usually , it is used to add
columns to an existing , but sometimes it is used to delete or modify columns as well.

Syntax for Alter Table statement:


ALTER TABLE <table-name> ADD COLUMN<column-name><data-type> <size> [<constraint-
name>];
DROP TABLE
The DROP TBALE statement of SQL lets you drop a table from the database

Syntax for Drop Table statement:


drop table <table name>
PRACTICAL NO.3

AIM: Working with Null Values, matching a Pattern from a Table, Ordering the Result of a
Query, Aggregate Functions, Grouping the Result of a Query, Update and Delete
Statements.

1. NOT NULL
By default, a column can take NULL value if no value is provided. To avoid this, we can make use
of NOT NULL constraint specifying that NULL is now not an allowable value

Syntax for NOT NULL constraint:


create table <table-name>
(<column-name> <data-type> [(<size>)] NOT NULL,
<column-name> <data-type> [(<size>) …]);

2. PATTERN MATCHING
SQL also includes a string-matching operator, LIKE, for comparisons on character strings using
patterns. Patterns are described using two special wildcard characters:

a. percent(%): The % character matches any substring


Syntax:
select <column(s)>
from <table-name>
where <column> LIKE ‘x%’

b. underscore(_): The _ character matches any character


Syntax:
select <column(s)>
from <table-name>
where <column> LIKE ‘__’

3. ORDER BY
The ORDER BY clause is used to sort selected results in ascending or descending order.

Syntax for order by clause:


select*from<table-name>
where<conditoin>
order by<column>

4. BETWEEN
The BETWEEN operator defines a range of values that the column values must fall in to make the
condition true.

Syntax for Between clause:


select*from <table-name>
where <column> between x and y

5. GROUP BY
The GROUP BY statement groups rows that have the same values into summary rows

Syntax for Group by:


select <column-name> from <table-name>
where <condition>
group by <column_name(s)>;

6. AGGREGATE FUNCTIONS:
SQL also supports group functions which operate upon a group of rows.
Some of those functions are:

a. Avg: The function computes the average of given data

Syntax for Avg:


select avg([distinct\all])
from <table-name>

b. Count: The function counts the number of rows in a given column

Syntax for count:


select count<[distinct\all]>
from <table-name>
where<condition>
c. Max: This function returns the minimum value from a column

Syntax for max:


select max([distinct\all])
from <table-name>
where<condition>

d. Min: This function returns the minimum value from a column

Syntax for min:


select min([distinct\all])
from <table-name>
where<condition>;

e. Sum: This function returns the sum of all values from a column

Syntax for sum


select min([distinct\all])
from <table-name>
where<condition>;

7. UPDATE ROWS
The UPDATE statement is used to modify the existing records in a table.

Syntax for update rows:


UPDATE <table-name>
SET <column1> =< value1>, <column2> = <value2>, ...
WHERE <condition>;

8. DELETE ROWS
The DELETE statement is used to delete existing records in a table

Syntax for delete row:


DELETE from <table-name>
WHERE <condition>
PRACTICAL NO.4
l Aim: Set Operators, Nested Queries, Joins, Sequences.
l Introduction:
1. The union clause: merges the outputs of multiple queries into a single set of rows and
columns. It combines rows returned by two select statements by eliminating duplicate
rows. SYNTAX :SQL>SELECT UNION SELECT ;
2. UNION ALL:UNION and UNION ALL are similar in their functioning with a slight
difference. But UNION ALL gives the result set without removing duplication and
sorting the data.

3. INTERSECT:The intersect operator combines two select statements and return only
those rows that are returned by both queries.
SYNTAX:SQL>SELECT INTERSECT SELECT ;

4. MINUS:It combines the result of two queries and returns only those values that are
selected by first query but not in second query.
SYNTAX :SQL>SELECT MINUS SELECT ;

l Nested Queries: A sub query is a form of an SQL statement that appears inside another
SQL statement. It is also termed as nested query. The statement containing a sub query is
called a parent statement. The parent statement uses the rows returned by the sub query. It
can be used by the following commands:
1. To insert records in a target table.
2. To create tables and insert records in the table created.
3. To update records in a target table.
4. To create views.
5. To provide values for conditions in WHERE, HAVING, IN etc. used with SELECT,
UPDATE, and DELETE statements.
TYPES OF SUB QUERIES
l SINGLE ROW
It returns one row from inner nested query.
EXAMPLE IS: SQL>SELECT deptno FROM emp WHERE ename =’MILLER’;
l MULTIPLE ROW
Subqueries that return more than one row called multiple row queries. Operators like
IN,ALL,ANY are used.
EXAMPLESQL>SELECT ename,sal,deptno FROM emp WHERE sal IN (SELECT
min(sal) FROM emp GROUP BY deptno);
l JOINS:A JOIN can be recognized in sql select statement if its has more than one table
after from keyword. This join condition is based on primary keys and foreign keys. There
must be n-1 join conditions for n joins to tables. If join condition is omitted then the result
is Cartesian product.
SYNTAX
SQL>SELECT “list of columns” FROM table1, table2 WHERE “condition”;
TYPES OF JOINS
1. EQUI JOIN : It returns all rows from tables where there is a match. Tables are joined on
columns that have the same datatype & size in table. It is also known as equality join or
simple join or inner join.
SYNTAX:
SELECTfield1,field2 FROM table1,table2 WHERE table1.field=table2.field;
2. CARTESION JOIN : When the join condition is omitted the result is Cartesian join of
two or more tables in which all the combinations of rows will be displayed. All the rows
are joined to all rows of the second table.
SYNTAX
SQL>SELECT field1, field2 FROM table1, table2;
EXAMPLE
SQL>SELECT ename, dname FROM emp, dept;
3. OUTER JOIN : While using equi join we see that if there exists certain rows in one table
which don’t have corresponding values in the second table thn those rows will not be
selected. We can forcefully select those rows by outer join. The rows for those columns
will have NULL values.
SYNTAX
SELECT table1.col, table2.col FROM table1, table2 WHERE table1.col (+) = table2.col;
EXAMPLE
SQL>SELECT empno, ename, emp.deptno, dname FROM emp, dept WHERE emp.deptno (+)
= dept.deptno;
4. SELF JOIN : The self join can be seen as join of two copies of the same table. The table
is not actually copied but sql performs the command as though it were.
EXAMPLE
SQL>SELECT e.ename, m.ename FROM emp e, emp m WHERE e.mgr=e.empno;
l Sequence :is a set of integers 1, 2, 3, … that are generated and supported by some
database systems to produce unique values on demand.
A sequence is a user defined schema bound object that generates a sequence of numeric
values.Sequences are frequently used in many databases because many applications
require each row in a table to contain a unique value and sequences provides an easy way
to generate them.
PRACTICAL NO.5

AIM: Views, Indexes, Database Security and Privileges: Grant and Revoke
Commands, Commit and Rollback Commands.
l VIEWS :A view is very commonly used database object that is derived at runtime. A
view contains data of its own. Its contents are derived from another table. The command
for creating view is CREATE VIEW command. Editing in the tables are automatically
reflected in the views. It is virtual table & does not have any data of its own.
SYNTAX TO CREATE A VIEW IS:
SQL>CREATE [OR REPLACE] VIEW view name AS sub query
EXAMPLE IS: SQL>CREATE VIEW monika AS SELECT empno, ename, sal, comm
FROM emp;
l TYPES OF VIEWS
1. JOIN VIEW :It is defined as view that has more than one table specified in from clause
and does not contain following clauses i.e. distinct, aggregation, group by. This type of
view allows update, insert and delete command to change data in table.
SYNTAX SQL>CREATE OR REPLACE VIEW monika AS SELECT ename, empno, sal
FROM emp, dept WHERE emp.deptno = dept.deptno;
2. INLINE VIEW:Oracle also offers an inline view that is very handy and inline view is
part of SQL statements. It allows you in body of SQL statement to define SQL for view
that SQL statement will use to resolve its query.
3. MATERIALIZED VIEW:Snapshot also called materialized view. It is defined as copy
of part of table or entire table. It reflects the current status of table that is being copied.
The original status table is also called master table. Two types are Read only and update.
Read- only does not allow changes to be made in view
l Indexes:An index can be created in a table to find data more quickly and efficiently the
users cannot see the indexes, they are just used to speed up searches/queries.
Syntax
Creates an index on a table. Duplicate values are allowed:
CREATE INDEX index_name ON table_name (column_name)
SQL CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:
CREATE UNIQUE INDEX index_name ON table_name (column_name)

l Grant: It is used to give user access privileges to a database.


Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

l Revoke: It is used to take back permissions from the user.


Example
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
Commit Command : Commit in SQL is a transaction control language which is used to
permanently save the changes done in the transaction in tables/databases.
SYNTAX :
COMMIT;
Rollback Command : Rollback in SQL is a transactional control language which is used
to undo the transactions that have not been saved in database.
SYNTAX :
ROLLBACK;
PRACTICAL NO. 6
AIM : PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL
Code, Referencing Non-SQL parameters.
PL/SQL Architecture : PL/SQL stands for Procedural Language/Structured Query
Language. The PL/SQL is a case insensitive, a robust procedural extension of the SQL.
PL/SQL was developed by Oracle Corporation within the early ’90s to reinforce the
capabilities of SQL. PL/SQL architecture defines how the PL/SQL blocks are executed in
Oracle. Oracle provides PL/SQL engine that executes the Procedural Language part of a
block. When an application program or a user invokes a PL/SQL block, it is submitted to the
PL/SQL engine available locally. PL/SQL engine extracts the Procedural Language
statements of the block. These statements are then executed separately by the PL/SQL
processor. The SQL statements in the block are passed to the SQL processor of Oracle server.
These are separately executed.

Assignments and Expressions : The assignment statement sets a previously-declared


variable or formal OUT or IN OUT parameter to the value of an expression.
SYNTAX :
Variable := Expression

Variable specifies an identifier for a previously-declared variable, OUT formal parameter, or


IN OUT formal parameter.
Expression specifies an expression that evaluates to a single value. The data type of this value
must be compatible with the data type of variable.
Writing PL/SQL Code : PL/SQL is a block structured language with procedural
techniques with features like logic building, looping, error-handling mechanisms, data-types,
variables, subroutines, procedural constructs. PL/SQL block consists of:
DECLARE
- used to declare variables and constants
- is an optional section
- is also used to declare type declarations, PL/SQL procedures and functions, which are local
to module
BEGIN
- is the executable section containing the code, which is executed when block is run
- is compulsory
EXCEPTION
- handles exceptions occurring during processing
- used to place predefined error-handlers or user-defined exceptions
- code contained in this section is executed only when an error occurs
- is an optional section
End;
STRUCTURE OF PL/SQL : PL SQL is structured in logical blocks of code. Each block has
multiple subsections.
[DECLARE]
<declaration statements>;
[BEGIN]
<Execution statements>;
[EXCEPTION]
<Exception statements>;
END;
CEC- CSE 5-C2

PRACTICAL 7

AIM: Stored Procedures and Exception Handling.


Procedures: Procedures are named PL/SQL blocks that can take parameters,
perform an action and can be invoked. A procedure is generally used to perform an
action and to pass values. Procedures are made up of:
1. A declarative part
2. An executable part
3. An optional exception handling part
Declarative Part: The declarative part may contain declaration of cursors,
constants, variables, exceptions and subprograms. These objects are local to the
procedure. The objects become invalid once you exit from it.
Executable Part: This part contains PL/SQL block consisting of statements that
assign values, control execution and manipulate ORACLE data.
Exception Handling Part: This part contains code that performs action to deal
with exceptions raised during the execution of the program.
Syntax

CREATE OR REPLACE
PROCEDURE [schema] procedure_name (argument {IN, OUT, IN OUT}
datatype){IS, AS} Variable declarations;
Constant declarations; BEGIN
PL/SQL subprogram body; EXCEPTION
Exception PL/SQL
block; END;

Types of Procedures:
1. Local Procedure
2. Stored Procedure
Local Procedure: These procedures are declared within the PL/SQL block and
called from the begin section of the PL/SQL block.
The following is a simple example of a procedure:

Janvi Bansal 25 2101643


CEC- CSE 5-C2

Program:
declare
a number; b number; c number; d number; e number; f number;
procedure process ( a in number, b in number, c out number, d out number,
e out number, f out number) is
begin c:=a+b; d:=a-b; e:=a*b; f:=a/b; end; begin
a:=&firstnumber; b:=&secondnumber;
process(a, b, c, d, e, f); DBMS_output.put_line(‘addition is’ || c);
DBMS_output.put_line(‘subtraction is’ || d);
DBMS_output.put_line(‘multiplication is’ || e);
DBMS_output.put_line(‘division is’ || f);
end;

OUTPUT

Exception Handling: An exception is an error condition during a program execution.


PL/SQL supports programmers to catch such conditions using EXCEPTION block
in the program and an appropriate action is taken against the error condition. There
are two types of exceptions − System-defined exceptions, User-defined exceptions

Syntax:
WHEN exception THEN statement;

Janvi Bansal 26 2101643


CEC- CSE 5-C2

Program:

Janvi Bansal 27 2101643


CEC- CSE 5-C2

PRACTICAL NO. 8

AIM: Triggers and Cursor Management in PL/SQL

Triggers: A trigger is a special kind of stored procedure that is invoked whenever


an attempt is made to modify the data in the table it protects. Triggers are
automatically executed or fired when some events occur. Modifications to the table
are made using INSERT, UPDATE, ORDELETE statements. Triggers are used to
enforce data integrity and business rules such as automatically updating summary
data. It allows performing cascading delete or updating operations. If constraints
exist on the trigger table, they are checked prior to the trigger execution. If
constraints are violated statement will not be executed and trigger will not run.
Triggers are associated with tables and they are automatic. Triggers are
automatically invoked by SQL SERVER. Triggers prevent incorrect, unauthorized,
or inconsistent changes to data.
Uses of Triggers:
1. A trigger can permit DML statements against a table only if they are issued, during
regular business hours or on predetermined weekdays.
2. A trigger can also be used to keep an audit trail of a table.
3. It can be used to prevent invalid transactions.
4. Enforce complex security authorizations.
5. Exception handling.
6. Generation of primary key and foreign key.
How to apply Triggers:
A trigger has three basic parts:
1. Triggering Event or Statement: It is a SQL statement that causes a trigger to be
fired. It can be an INSERT, UPDATE or DELETE statement for a specific table.
2. Trigger Restriction: A trigger restriction specifies a Boolean expression that must
be TRUE for the trigger to fire. It is an option available for triggers that are fired
for each row. A trigger restriction is specified using a WHEN clause.
3. Trigger Action: A trigger action is the PL/SQL code to be executed when a
triggering statement is encountered and any trigger restriction evaluates to TRUE.

Types of Triggers
• Row Triggers: A row trigger is fired each time the table is affected by the triggering

Janvi Bansal 28 2101643


CEC- CSE 5-C2

statement, for example, if an UPDATE statement update multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE statement.
• Statement Triggers: A row trigger is fired once on behalf of the triggering statement,
independent of the number of rows the triggering statement affects.
• Before Triggers: Before triggers execute the trigger action before the triggering
statement. These types of triggers are commonly used in the following situations:
1. BEFORE triggers are used when the trigger action should determine whether or
not the triggering statement should be allowed to complete. By using BEFORE
trigger, user can eliminate unnecessary processing of the triggering statement.
2. BEFORE triggers are used to derive specific column values before completing
a triggering INSERT or UPDATE statement.
• After Triggers: After triggers execute the trigger after the triggering statement is
executed. These types of triggers are commonly used in the following situations:
1. AFTER triggers are used when the triggering statement should complete before
executing the trigger action.
2. If a BEFORE trigger is already present, an AFTER trigger can perform
different actions on the same triggering statement.
Combinations Triggers: Using the above triggers, four types of triggers could be
created. There are twelve combinations of triggers.
Before Statement Trigger: Before executing the triggering statement, the trigger action is
executed.
Before Row Trigger: Before modifying each row affected by the triggering
statement and BEFORE applying appropriate integrity constraints, the trigger is
executed.
After Statement Trigger: After executing the triggering statement and applying
and deferred integrity constraints, the trigger action is executed.
After Row Trigger: After modifying each row affected by the triggering statement
and applying appropriate integrity constraints, the trigger action is executed for the
current row. Unlike BEFORE row triggers, AFTER row triggers have rows locked.

Creation of Triggers: Triggers are created with the CREATE TRIGGER


statement. This statement specifies that the on which table trigger is defined and on
which events trigger will be invoked.

Janvi Bansal 29 2101643


CEC- CSE 5-C2

Syntax:

Deleting a Trigger: To drop Trigger one can use DROP TRIGGER statement.
Syntax:

DROP TRIGGER &lt;TriggerName&gt;

Example

To start with, using the CUSTOMERS table Select * from customers;

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
The following program creates a row-level trigger for the customers table that

would fire for INSERT or UPDATE or DELETE operations performed on the

CUSTOMERS table.

This trigger will display the salary difference between the old values and new

values − CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACH ROW

WHEN (NEW.ID &gt; 0) DECLARE

Janvi Bansal 30 2101643


CEC- CSE 5-C2

sal_diff number; BEGIN

sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line(&#39;Old salary: &#39;


||

:OLD.salary); dbms_output.put_line(&#39;New salary: &#39; || :NEW.salary);

dbms_output.put_line(&#39;Salary difference: &#39; || sal_diff); END;

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

result − Trigger created.

The following points need to be considered here −


 OLD and NEW references are not available for table-level triggers, rather use
them for record-level triggers.
 To query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial
changes are applied and the table is back in a consistent state.
 The above trigger has been written in such a way that it will fire before any
DELETE or INSERT or UPDATE operation on the table, but a trigger can be
written on a single or multiple operations, for example BEFORE DELETE, which
will fire whenever a record will be deleted using the DELETE operation on
thetable.

Triggering a Trigger:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, &#39;,Kriti&#39;, 22, &#39;HP&#39;, 7500.00 ); When a record is
created in the CUSTOMERS table, the above create trigger,
display_salary_changes will be fired and it will display the following result – Old
salary:
New salary: 7500 Salary difference:
Because this is a new record, old salary is not available and the above result
comes as null.
The UPDATE statement will update an existing record in the table –
UPDATE customers
SET salary = salary

+ 500 WHERE id

= 2;

Janvi Bansal 31 2101643


CEC- CSE 5-C2

When a record is updated in the CUSTOMERS table, the above create trigger,

display_salary_changes will be fired and it will display the following

result − Old salary: 1500


New salary: 2000
Salary difference: 500

CURSORS:
Oracle DBA uses a work area for its internal processing. This work area is private
to SQL’s operations and is called Cursor. The data that is stored in the cursor is
called the Active Data Set. The size of the cursor in memory is the size required to
hold the number of rows in the active data set.
A PL/SQL block of code includes the Procedural code for looping and branching
along with the SQL statement. If records from a record set created using a select
statement are to be evaluated and processed one at a time, then the only method
available is by using Explicit Cursors.

TYPES OF CURSORS:
 Implicitcursors.
 Explicitcursors.

ATTRIBUTES OF CURSORS: Oracle provides certain attributes/cursor


variables to control the exception of a cursor. Whenever any cursor is opened and
used, Oracle creates a set of four system variables via which Oracle keeps track of
the ‘Current’ status of the cursor. We can access these variables. The implicit and
explicit cursors have four attributes as described below:
1. %NOTFOUND: It evaluates to TRUE, if an insert, delete ,or updateaffected no rows
or a single row
select returns no rows. Otherwise, it evaluates to FALSE.
Syntax:
cursor_name%NOTFOUND;
2. %FOUND: It is the logical opposite of %notfound. It evaluates to TRUE, if an insert,
delete, orupdateaffected one or more rows, or a single row select returns one or more
rows. Otherwise, it evaluates to FALSE.
Syntax:

Janvi Bansal 32 2101643


CEC- CSE 5-C2

cursor_name%FOUND;

3. %ISOPEN: Oracle automatically closes the SQL cursor after executing its associated
SQL statement. As a result, sql%isopenalways evaluates to FALSE. If the explicit
cursor is open then it returns true otherwise false.

Syntax:
cursor_name%ISOPEN;

4. %ROWCOUNT: Returns the number of rows affected by an insert, delete


,or updateor selectinto statement.

Syntax:
cursor_name%ROWCOUNT;
IMPLICIT CURSORS:

Oracle implicitly opens a cursor to process each SQL statement not associated
with an explicitly declared cursor. PL/SQL lets us refer to the most recent implicit
cursor as the SQL cursor. So, although we cannot use the open, fetch, and
closestatements to control an implicit cursor, we can still use cursor attributes to
access information about the most recently executed SQL statement.
Use cursor to select the five highest paid employees from the emp table showing
tables also.

Input Table:

Declare
cursor c1 isselectename, empno, sal from emp order by saldesc; -- start with highest
paid employee my_enamevarchar2(10);
my_empno
number(4);
my_sal
number(7,2);

Janvi Bansal 33 2101643


CEC- CSE 5-C2

Begin open c1;


fori in 1..5 loop
fetch c1 into my_ename, my_empno, my_sal; exit when
c1%notfound; insert into temp values (my_sal, my_empno,
my_ename);
commit; end loop; close c1; end;
Output Table:

Janvi Bansal 34 2101643

You might also like