Professional Documents
Culture Documents
UNIT 2 DBMS
UNIT 2 DBMS
UNIT 2 DBMS
RDBMS are powerful because they require few assumptions about how data is
related or how it will be extracted from the database. As, a result the same
database can be viewed in many different ways.
Main feature of relational systems is that single database can be spread across
several tables.
Constraints
• Constraints are the rules enforced on the data columns of a 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 either on a column level or a table level. The column
level constraints are applied only to one column, whereas the table level
constraints are applied to the whole table.
Following are some of the most commonly used constraints
available in SQL are -
• NOT NULL Constraint − Ensures that a column cannot have NULL
value.
• DEFAULT Constraint − Provides a default value for a column when
none is specified.
• UNIQUE Constraint − Ensures that all values in a column are different.
• PRIMARY Key − Uniquely identifies each row/record in a database
table.
• FOREIGN Key − Uniquely identifies a row/record in any of the given
database table.
CHECK Constraint − The CHECK constraint ensures that all the values
in a column satisfies certain conditions.
CONSTRAINTS
Example:-
Example:-
SQL> create table student1(roll_no number(12) primary key,
,name varchar2(20),class varchar2(2), e_mail varchar2(20)
unique);
Table created.
5) Check Constraints:-
The CHECK constraint is used to limit the value range that can be
placed in a column. If you define a CHECK constraint on a single
column it allows only certain values for this column.
For Example:-
The default value will be added to all new records, if no other value is specified.
Oracle:
Oracle:
Integrity Constraints:
• Integrity constraints are used to ensure accuracy and consistency of data
in a relational database. Data integrity is handled in a relational database
through the concept of referential integrity.
• There are many types of integrity constraints that play a role in referential
integrity (RI). These constraints include Primary Key, Foreign Key,
Unique Constraints and other constraints
Integrity Constraints
• Integrity constraints are a set of rules. It is used to maintain the quality of
information.
• Integrity constraints ensure that the data insertion, updating, and other
processes have to be performed in such a way that data integrity is not
affected.
• Key constraints
• Domain constraints
• Referential integrity constraints
• Entity Integrity Constraints
Key Constraints
• There must be at least one minimal subset of attributes in the relation,
which can identify a tuple uniquely. This minimal subset of attributes is
called key for that relation. If there are more than one such minimal
subsets, these are called candidate keys.
• Key constraints force that −
• in a relation with a key attribute, no two tuples can have identical values
for key attributes.
• a key attribute can not have NULL values.
• Key constraints are also referred to as Entity Constraints.
Domain Constraints
• Attributes have specific values in real-world scenario. For example, age
can only be a positive integer. The same constraints have been tried to
employ on the attributes of a relation. Every attribute is bound to have a
specific range of values. For example, age cannot be less than zero and
telephone numbers cannot contain a digit outside 0-9. Domain
constraints can be defined as the definition of a valid set of values for an
attribute.
• The data type of domain includes string, character, integer, time, date,
currency, etc. The value of the attribute must be available in the
corresponding domain.
• Example:
• Example
Relational Algebra:-
1. Select Operation:
o The select operation selects tuples that satisfy a given predicate.
o It is denoted by sigma (σ).
o It yields a horizontal subset of a given relation.
1. Notation: σ p(r)
Where:
σ is used for selection prediction
r is used for relation
p is used as a propositional logic formula which may use connectors like: AND
OR and NOT. These relational can use as relational operators like =, ≠, ≥, <, >,
≤. Furthermore, we can combine several predicates into a larger predicate by
using the connectives and (∧), or (∨), and not (¬).
For example: LOAN Relation
BRANCH_NAME LOAN_NO AMOUNT
Find those tuples whose loans of more than Rs 1200 and branch is perryride.
2. σ BRANCH_NAME="perryride" ∧ amount>1200(LOAN)
find tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" ∧ price = "450"(Books)
Selects tuples from books where subject is 'database' and 'price' is 450 or
those books published after 2010.
σsubject = "database" ∧ price = "450" ∨ year > "2010"(Books)
2. Project Operation:
o This operation shows the list of those attributes that we wish to appear in
the result. Rest of the attributes are eliminated from the table.
o It is denoted by ∏.
o It yields a vertical subset of a given relation.
1. Notation: ∏ A1, A2, An (r)
Where
A1, A2, A3 is used as an attribute name of relation r.
Example: CUSTOMER RELATION
NAME STREET CITY
Jones Harrison
Smith Rye
Hays Harrison
Curry Rye
Johnson Brooklyn
Brooks Brooklyn
Find those customers who live in Rye.
∏ name (σ city=”Rye”) (Customer)
Selects and projects columns named as subject and author from the
relation Books.
∏subject, author (Books)
Johnson A-101
Smith A-121
Mayes A-321
Turner A-176
Johnson A-273
Jones A-472
Lindsay A-284
BORROW RELATION
CUSTOMER_NAME LOAN_NO
Jones L-17
Smith L-23
Hayes L-15
Jackson L-14
Curry L-93
Smith L-11
Williams L-17
Mayes
CUSTOMER_N
AME
Smith
Jones
5. Set Difference:
The set-difference operation, denoted by −, allows us to find tuples
that are in one relation but are not in another. The expression r − s
produces a relation containing those tuples in r but not in s.
Suppose there are two tuples R and S. The set intersection operation
contains all tuples that are in R but not in S.
It is denoted by intersection minus (-).
1. Notation: R - S
Example: Using the above DEPOSITOR table and BORROW table
Find the name of customer who has account number in BORROW table but not
in DEPOSITOR
Input:
1. ∏ CUSTOMER_NAME (BORROW) - ∏ CUSTOMER_NAME (DEPOSITOR
)
Output:
CUSTOMER_NAME
Jackson
Hayes
Willians
Curry
Question Provides the name of authors who have written books but not
articles.
∏ author (Books) - ∏ author (Articles)
6. Cartesian product
The Cartesian product is used to combine each row in one table with each
row in the other table. It is also known as a cross product.
It is denoted by X.
The Cartesian-product operation, denoted by a cross (×), allows us to
combine information from any two relations. We write the Cartesian
product of relations r1 and r2 as r1 × r2.
1. Notation: E X D
Example:
EMPLOYEE
EMP_ID EMP_NAME EMP_DEPT
1 Smith A
2 Harry C
3 John B
DEPARTMENT
DEPT_NO DEPT_NAME
A Marketing
B Sales
C Legal
Input:
1. EMPLOYEE X DEPARTMENT
Output:
EMP_I EMP_NA EMP_DE DEPT_ DEPT_NA
D ME PT NO ME
1 Smith A A Marketing
1 Smith A B Sales
1 Smith A C Legal
2 Harry C A Marketing
2 Harry C B Sales
2 Harry C C Legal
3 John B A Marketing
3 John B B Sales
3 John B C Legal
Question Find relation, which shows all the books and articles written by
test.
Division Operation(/)
Division Operator (÷): Division operator A÷B can be applied if and only if:
Attributes of B is proper subset of Attributes of A.
The relation returned by division operator will have attributes = (All
attributes of A – All Attributes of B)
The relation returned by division operator will return those tuples from
relation A which are associated to every B’s tuple.
7. Rename Operation:
The rename operation is used to rename the output relation. It is denoted
by rho (ρ).
Unlike relations in the database, the results of relational-algebra
expressions do not have a name that we can use to refer to them.
It is useful to be able to give them names; the rename operator, denoted
by the lowercase Greek letter rho (ρ), lets us do this. Given a relational-
algebra expression E, the expression ρ x (E) returns the result of
expression E under the name x.
Example: We can use the rename operator to rename STUDENT relation to
STUDENT1.
1. ρ(STUDENT1, STUDENT)
2. Query to rename the table name Project to Pro and its attributes to P, Q, R.
ρ Pro(P, Q, R) (Project)
3. Query to rename the first attribute of the table Student with attributes A, B, C
to P.
ρ (P, B, C) (Student)
Join Operations:
A Join operation combines related tuples from different relations, if and
only if a given join condition is satisfied. It is denoted by ⋈.
The general form of a join operation on two relations R(A1,A2,A3…An)
and S(B1,B2….Bn) is R ⋈ <join condition> S.
(Emp⋈dept ⋈cmp)
The result of the join is a relation Q with (n+m) attributes in that order,
one from R relation and other from S relation.
TYPES OF JOINS
1. INNER join:- In SQL, INNER JOIN selects records that have matching
values in both tables as long as the condition is satisfied. It returns the
combination of all rows from both the tables where the condition satisfies.
Syntax:-
SELECT table1.column1, table1.column2, table2.column1,....
FROM table1 INNER JOIN table2 ON table1.matching_column = table2.
matching_column;
Example:-
emp
Eid ename deptid
101 Aman 201
102 Rajesh 202
103 Suresh 204
dept
deptid Dname
201 B.Tech
202 MCA
203 MBA
SELECT emp. ENAME, dept. dname FROM emp INNER JOIN dept
ON emp.deptid=dept.deptid;
Ename Dname
Aman Btech
Rajesh MCA
For example:- SELECT emp. ename, dept.dname from emp LEFT OUTER
JOIN dept on emp.deptid=dept.depid;
Ename Dname
Aman Btech
Rajesh Mca
Suresh
Relational algebra
∏ ENAME, DNAME (Emp Dept)
B) RIGHT OUTER JOIN:- It returns a result table with matched data of two
tables then remaining rows of the RIGHT table and NULL for the LEFT table
column.
For example:- SELECT emp. ename, dept.dname from emp RIGHT OUTER
JOIN dept on emp.deptid=dept.depid;
Ename Dname
Aman Btech
Rajesh Mca
Mba
Relational algebra
∏ ENAME, DNAME (Emp Dept)
C) FULL OUTER JOIN:-It returns a result table with matched data of two
tables then remaining rows of both left and right table is NULL.
Ename Dname
Aman Btech
Rajesh Mca
Suresh
Mba
Relational algebra
∏ ENAME, DNAME (Emp Dept)
3. Natural Join:- Natural Join joins two tables based on same attribute
name and datatypes. The resulting table will contain all the attributes of
both the table but keep only one copy of each common column.
- The columns must be the same data type.
- Don’t use ON clause in a natural join.
Natural join does not use any comparison operator
Syntax:
4. CROSS JOIN: This join produces a result where the number of rows in the
first table gets multiplied with the rows in the second table.
5. SELF JOIN: Self-join is a regular join and here the table joins with itself
only.
Tuple Calculus provides only the description of the query but it does not
provide the methods to solve it. Thus, it explains what to do but not how to do.
{t| P(t)}
P(t) = known as Predicate and these are the conditions that are used to
fetch tuple t
| -- filter side
Result of query
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.
Notations used
t is a tuple variable
t[A] denotes the value of tuple on attribute A
t∈r denote the tuple in relation r
P is formula similar to that of predicate calculus
the variable t that appears to the left of | must be only the free variable in the
formula p(t)
in other words all other tuple variable must be bound using quantifiers.
Queries-1: Find the loan number, branch name , amount of loans of over
$1200
Queries-2: Find the loan number for each loan of an amount greater than
1200.
{t| ∃ s ∈ loan(t[loan number] = s[loan number] ∧
s[amount]>1200)}
it selects the set of tuples t such that there exixts a tuple s in relation loan for
which the value of t & s for the loan number are equal and the value of s for
the amount attribute is greater than $1200.
Queries-3: Find the names of all customers having a loan at the “ABC”
branch.
{t | ∃ s ∈ borrower(t[customer-name] = s[customer-name] ∧ ∃ u ∈
loan(u[branch-name] = “ABC” ∧ u[loan-number] = s[loan-number]))
(Join)
Queries-4: Find the names of all customers who have a loan and an account
or both at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∨ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
(union)
Queries-5: Find the names of all customers who have a loan and an account
at the bank.
{t | ∃ s ∈ borrower( t[customer-name] = s[customer-name])
∧ ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
(intersection)
Query-2: Find the loan number for each loan of an amount greater or equal to
150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan ∧ (a ≥ 150)}
Query-3: Find the names of all customers having a loan at the “Main” branch
and find the loan amount .
{∃c, a∈| ∧ l (∃c, l∈∧ borrower ∧ ∃ b (≺l, b, a≻∈ loan ∧ (b = “Main”)))}
Introduction to SQL(Structured Query Language)
SQL Literals
• Character string :
Character strings are written as a sequence of characters enveloped in
single quotes. the only quote character is delineate at intervals a
personality string by 2 single quotes. Some example of character strings
are :
• ‘My String’
• ‘I love GeeksForGeeks’
• Bit string :
A bit string is written either as a sequence of 0s and 1s enveloped in
single quotes and preceded by the letter ‘B’ or as a sequence of
positional representation system digits enveloped in single quotes and
preceded by the letter X’ some examples are given below :
• B ’10001011′
• B ’1′
• Exact numeric :
These literals ar written as a signed or unsigned decimal variety
probably with mathematical notation. Samples of actual numeric literals
are given below :
• 8
• +88.88
• Approximate numeric :
Approximate numeric literals are written as actual numeric literals
followed by the letter ‘E’, followed by a signed or unsigned number.
Some example are :
• 6E6
• 66.6E6
• +66E-6
SQL Commands
o SQL commands are instructions. It is used to communicate with the
database. It is also used to perform specific tasks, functions, and queries
of data.
o SQL can perform various tasks like create a table, add data to tables, drop
the table, modify the table, set permission for users.
o There are five types of SQL commands: DDL, DML, DCL, TCL, and
DQL.
o CREATE
o ALTER
o DROP
o TRUNCATE
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(
100), DOB DATE);
b. DROP: It is used to delete both the structure and record stored in the table.
c. ALTER: It is used to alter the structure of the database. This change could be
either to modify the characteristics of an existing attribute or probably to add a
new attribute.
d. TRUNCATE: It is used to delete all the rows from the table and free the
space containing the table.
Syntax: TRUNCATE TABLE table_name;
o INSERT
o UPDATE
o DELETE
Or
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = value
N] [WHERE CONDITION]
For example:
For example:
DCL commands are used to grant and take back authority from any database
user.
o Grant
o Revoke
Syntax:
REVOKE <privilege list>
ON <relation name or view name>
FROM <user name>;
TCL commands can only use with DML commands like INSERT, DELETE
and UPDATE only.
These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
Syntax:
COMMIT;
Example:
Syntax:
ROLLBACK;
Example:
o SELECT
Syntax:
For example:
SQL statements generally contain some reserved words or characters that are
used to perform operations such as comparison and arithmetical operations etc.
These reserved words or characters are known as operators.
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Assume 'variable a' holds 10 and 'variable b' holds 20, then −
Checks if the value of left operand is less than the value of (a < b) is
<
right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than or equal to the (a <= b)
<=
value of right operand, if yes then condition becomes true. is true.
NOT The NOT operator reverses the meaning of the logical operator with
2 which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN, etc. This
is a negate operator.
SELECT code, area FROM agent WHERE code = 1 AND area = ‘knp’;
SELECT code, area FROM agent WHERE code = 1 OR area = ‘knp’;
SELECT * FROM agent WHERE NOT code>1;
Set Operators
Set operators combine the results of two separate queries into single result.
following table shows different set operators
Operator Returns
MINUS All distinct rows selected by the first query but not the second
UNION ALL All rows selected by either query, including all duplicates
Operator Precedence
Precedence is the order in which Oracle evaluates different operators in the
same expression. When evaluating an expression containing multiple operators,
Oracle evaluates operators with higher precedence before evaluating those with
lower precedence. Oracle evaluates operators with equal precedence from left to
right within an expression. Operators listed on the same line have the same
precedence.
Aggregate Functions:-
Aggregate functions in DBMS take multiple rows from the table and return a
value according to the query.
All the aggregate functions are used in Select statement.
SQL aggregate function is used to perform the calculations on multiple rows of
a single column of a table. It returns a single value.
It is also used to summarize the data.
Various Aggregate Functions
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
COUNT() Function
The count function returns the number of rows in the result. It does not count
the null values.
Example: Write a query to return number of rows where salary > 20000.
MAX() Function
The MAX function is used to find maximum value in the column that is
supplied as a parameter. It can be used on any type of data.
Example − Write a query to find the maximum salary in employee table.
Select MAX(salary) from Employee
SUM() Function
This function sums up the values in the column supplied as a parameter.
Example: Write a query to get the total salary of employees.
AVG() Function
This function returns the average value of the numeric column that is supplied
as a parameter.
Example: Write a query to select average salary from employee table.
MIN() Function
The aggregate function SQL MIN() is used to find the minimum value or
lowest value of a column or expression. This function is useful to determine the
smallest of all selected values of a column
Example: Write a query to select minimum salary from employee table.
Syntax:
SELECT column1, function_name(column2)
FROM table_name
WHERE condition
GROUP BY column1, column2
Having Clause condition
ORDER BY column1, column2;
Emp table:-
c)Find the empname and total salary increment by 1000 of all employees;
Having Clause:
The having clause tells SQL to include only certain groups produced by the
group by clause in the query result set. Having is used to specify the search
criteria when group by is used.
For Example
a) Find the empname and total salary of all employees except employee
'Ajay'
Select empname ,sum(salary) from emp group by empname having
empname<>'ajay';
Select salary, empname from emp group by empname, salary having empname
like '_m%';
Where Clause
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
a) Display all the empname with salary in ascending order
Storename Sales
Los angeles 1500
San diego 250
San franciso 300
Boston 700
Storename Sales
Los Angeles 1500
San diego 250
Los Angeles 300
Sub Queries:-
A subquery is a query within another query. The outer query is called
as main query and inner query is called as subquery.
A Subquery or Inner query or a Nested query is a query within another SQL
query and embedded within the WHERE clause.
A subquery is used to return data that will be used in the main query as a
condition to further restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE
statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
You can place the Subquery in a number of SQL
clauses: WHERE clause, HAVING clause, FROM clause.
There are a few rules that subqueries must follow −
Subqueries must be enclosed within parentheses.
A subquery can have only one column in the SELECT clause, unless
multiple columns are in the main query for the subquery to compare its
selected columns.
ORDER BY command cannot be used in a
Subquery. GROUPBY command can be used to perform same function
as ORDER BY command.
Subqueries that return more than one row can only be used with multiple
value operators such as the IN operator.
Subqueries are most frequently used with the SELECT statement. The basic
syntax is as follows −
SELECT column_name
FROM table_name
WHERE column_name expression operator
( SELECT column_name from table_name WHERE ... );
Author Table:
Authorname Pubadd
Aroa Us
Kapoor Canada
Basu India
Sinha India
Ques : -Display the title ,author and publisher name of all books published
in 2000, 2002 and 2004.
SQL> select title ,author and publisher name, PUB_YEAR from book where
pub_year in('2000', '2002', '2004');
TITLE AUTHOR PUBLISHER PUB_YEAR
NAME NAME
ORACLE AROA PHI 2004
DBMS BASU TECHNICAL 2004
ADBMS BASU TECHNICAL 2004
UNIX KAPOOR SCITECH 2000
Ques: Get details of author who have published book in the year 2004
NOT IN
Display the title, author and publisher name of all books except those which are
published in the year 2002, 2004 ,2005.
SQL>select title, author , publisher name from book where pub_year not in
('2002','2004','2005');
SQL> Select title from book where author not in (select authorname from
author where pubadd='India');
Set Comparison
Nested subqueries are used to compare sets.SQL use various operators such as
<,<=,>,>=,<>,any ,all etc to compare sets.
Ques: Display the titles of books have price greater than at least one book
published in year 2004
SQL> select distinct title from book where unitprice > some (select unitprice
from book where pub_year=2004;
>some means outer query is true if the unit price of the row is greater than at
least one values of all unit prices published in year 2004
Ques Display the titles of books that have price greater than that all books
publiser in year 2004.
SQL> select distinct title from book where unitprice > all (select unitprice from
book where pub_year=2004;
>all means outer query is true if the unitprice of all row is greater than all values
of unitprice published in year 2004.
Subqueries also can be used with INSERT statements. The INSERT statement
uses the data returned from the subquery to insert into another table . The
structure of both tables must be same.
The subquery can be used in conjunction with the UPDATE statement. Either
single or multiple columns in a table can be updated when using a subquery
with the UPDATE statement.
The basic syntax is as follows.
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
SQL> UPDATE employee
SET SALARY = SALARY * 0.25
WHERE empid IN (SELECT empid FROM emp);
Subqueries with the DELETE Statement
The subquery can be used in conjunction with the DELETE statement like with
any other statements mentioned above.
The basic syntax is as follows.
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[ WHERE) ]
SQL> DELETE FROM employee
WHERE empid IN (SELECT empid FROM emp);
Ques:- get the title names of all book for which authorname exist in author
table.
Ques:- get the title names of all book for which no authorname exist in
author table.
select title from book where not exists(select * from author where
book.authorname=author.authorname);
Views in SQL
Views in SQL are considered as a virtual table. A view also contains rows
and columns.
To create the view, we can select the fields from one or more tables
present in the database.
A view can either have specific rows based on certain condition or all the
rows of a table.
A View in SQL as a logical subset of data from one or more tables.
Views are used to restrict data access. A View contains no data of its
own but it's like window through which data from tables can be viewed
or changed. The table on which a View is based are called BASE
Tables.
BOOK TABLE
Author Table:
Authorname Pubadd
Aroa Us
Kapoor Canada
Basu India
Sinha India
1. Creating view A view can be created using the CREATE VIEW statement.
We can create a view from a single table or multiple tables.
CREATE VIEW view_name AS SELECT column1, column2.....
FROM table_name WHERE condition;
Query:
CREATE VIEW DetailsView AS SELECT title, author_name
FROM book ;
4. Deleting View:-
A view can be deleted using the Drop View statement.
Simple View and Complex View. Simple views can only contain a single base
table. Complex views can be constructed on more than one base table. In
particular, complex views can contain: join conditions, a group by clause, a
order by clause.
Does not contain groups of data It can contain groups of data using group
using group by clause. by clause
DML operations could be
performed through a simple DML operations could not always be
view. performed through a complex view.
Syntax
CREATE INDEX index_name ON table_name (column1, column2, ...);
Example
2. Composite Indexes
3. Unique Index
It is used to create a unique index on a table. It does not allow duplicate value.
Syntax
Example
Syntax
Example
DROP INDEX websites_idx;
What is PL/SQL
PL/SQL is a block structured language that can have multiple blocks in it.
SQL stands for Structured Query Language i.e. used to perform operations on
the records stored in database such as inserting records, updating records,
deleting records, creating, modifying and dropping tables, views etc.
PL/SQL is a highly structured and readable language. Its constructs express the
intent of the code clearly. Also, PL/SQL is a straightforward language to learn.
PL/SQL architecture
Triggers in PL/SQL
Triggers are stored programs, which are automatically executed or fired when
some events occur. Triggers are, in fact, written to be executed in response to
any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or
UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the
event is associated.
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
+----+----------+-----+-----------+----------+
| 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 > 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;
/
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 you can use them for record-level triggers.
If you want 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 you
can write your trigger on a single or multiple operations, for example
BEFORE DELETE, which will fire whenever a record will be deleted
using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one
INSERT statement, which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 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. Let us now perform one more DML operation on the
CUSTOMERS table. The UPDATE statement will update an existing record in
the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
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
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which
performs one or more specific tasks. It is just like procedures in other
programming languages.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.
When you want to create a procedure or function, you have to define parameters
.There is three ways to pass parameters in procedure:
Creating a Procedure
A procedure is created with the CREATE OR REPLACE
PROCEDURE statement. The simplified syntax for the CREATE OR
REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and
OUT represents the parameter that will be used to return a value outside
of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a
standalone procedure.
The following table lists out the parameter modes in PL/SQL subprograms −
IN
An IN parameter lets you pass a value to the subprogram. It is a read-
only parameter. Inside the subprogram, an IN parameter acts like a
1 constant. It cannot be assigned a value. You can pass a constant,
literal, initialized variable, or expression as an IN parameter. You can
also initialize it to a default value; however, in that case, it is omitted
from the subprogram call. It is the default mode of parameter
passing. Parameters are passed by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the
2
subprogram, an OUT parameter acts like a variable. You can change
its value and reference the value after assigning it. The actual
parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and
returns an updated value to the caller. It can be assigned a value and
3 the value can be read.
The actual parameter corresponding to an IN OUT formal parameter
must be a variable, not a constant or an expression. Formal parameter
must be assigned a value. Actual parameter is passed by value.
In this example, we are going to insert record in user table. So you need to
create user table first.
Table creation:
Procedure Code:
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully');
END;
/
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
Cursors In PL/SQL
A cursor is a pointer that points to a result of a query. PL/SQL has two
types of cursors: implicit cursors and explicit cursors.
Oracle creates a memory area, known as the context area, for processing an
SQL statement, which contains all the information needed for processing the
statement; for example, the 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.
Declare a cursor
Before using an explicit cursor, you must declare it in the declaration section of
a block or package as follows:
In this syntax:
First, specify the name of the cursor after the CURSOR keyword.
Second, define a query to fetch data after the IS keyword.
Open a cursor
Before start fetching rows from the cursor, you must open it. To open a cursor,
you use the following syntax:
OPEN cursor_name;
Fetch from a cursor
The FETCH statement places the contents of the current row into variables. The
syntax of FETCH statement is as follows:
To retrieve all rows in a result set, you need to fetch each row till the last one.
Closing a cursor
After fetching all rows, you need to close the cursor with the CLOSE statement:
CLOSE cursor_name;
cursor_name%attribute
Code language: SQL (Structured Query Language) (sql)
1) %ISOPEN
2) %FOUND
3) %ROWCOUNT
The %ROWCOUNT attribute returns the number of rows fetched from the
cursor. If the cursor is not opened, this attribute returns INVALID_CURSOR.
Types of Cursors
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
Explicit cursors
Implicit Cursors
%NOTFOUND
2 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
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
+----+----------+-----+-----------+----------+
| 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 will update the table and increase the salary of each
customer by 500 and use the SQL%ROWCOUNT attribute to determine the
number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
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.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
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 allocates the memory for the cursor and makes it ready for
fetching the rows returned by the SQL statement into it. For example, we will
open the above defined cursor as follows −
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example, we will
fetch rows from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the cursor means releasing the allocated memory. For example, we
will close the above-opened cursor as follows −
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following
result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.