0% found this document useful (0 votes)
24 views32 pages

Apznza 1

Uploaded by

reyadblock123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views32 pages

Apznza 1

Uploaded by

reyadblock123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT-IV: SQL & PL/SQL Concepts

PART-I: SQL Concepts

Basics of SQL
 SQL stands for Structured Query Language. It is used for storing and
managing data in relational database management system (RDMS).
 It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
 All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server
use SQL as their standard database language.
 SQL allows users to query the database in a number of ways, using English-
like statements.
 Structure query language is not case sensitive. Generally, keywords of SQL
are written in uppercase.
 When an SQL command is executing for any RDBMS, then the system
figure out the best way to carry out the request and the SQL engine
determines that how to interpret the task.
 In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher etc.
 When an SQL command is executing for any RDBMS, then the system
figure out the best way to carry out the request and the SQL engine
determines that how to interpret the task.
 In the process, various components are included. These components can be
optimization Engine, Query engine, Query dispatcher, classic, etc.
DDL, DQL, DML, DCL, TCL
 SQL uses certain commands like Create, Drop, Insert, etc. to carry out the
required tasks.
 These SQL commands are mainly categorized into four categories as:
1. DDL – Data Definition Language
2. DQL – Data Query Language
3. DML – Data Manipulation Language
4. DCL – Data Control Language
5. TCL – Transaction Control Language

DDL (Data Definition Language):


 DDL or Data Definition Language actually consists of the SQL commands
that can be used to define the database schema.
 It simply deals with descriptions of the database schema and is used to create
and modify the structure of database objects in the database.
 DDL is a set of SQL commands used to create, modify, and delete database
structures but not data.
 List of DDL commands:
CREATE: This command is used to create the database or its objects (like
table, index, function, views, store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all
spaces allocated for the records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.

DQL (Data Query Language):


 The purpose of the DQL Command is to get some schema relation based on
the query passed to it.
 It includes the SELECT statement. This command allows getting the data out
of the database to perform operations with it.
 When a SELECT is fired against a table or tables the result is compiled into a
further temporary table, which is displayed or perhaps received by the
program i.e. a front-end.
 List of DQL:
SELECT: It is used to retrieve data from the database.

DML (Data Manipulation Language):


 The SQL commands that deal with the manipulation of data present in the
database belong to DML or Data Manipulation Language and this includes
most of the SQL statements.
 List of DML commands:
INSERT : It is used to insert data into a table.
UPDATE: It is used to update existing data within a table.
DELETE : It is used to delete records from a database table.

DCL (Data Control Language):


 DCL includes commands such as GRANT and REVOKE which mainly deal
with the rights, permissions, and other controls of the database system.
 List of DCL commands:
GRANT: This command gives users access privileges to the database.
REVOKE: This command withdraws the user’s access privileges given by
using the GRANT command.

TCL (Transaction Control Language):


 Each transaction begins with a specific task and ends when all the tasks in
the group successfully complete.
 If any of the tasks fail, the transaction fails. Therefore, a transaction has only
two results: success or failure.
 Hence, the following TCL commands are used to control the execution of a
transaction:
COMMIT: Commits a Transaction.
ROLLBACK: Rollbacks a transaction in case of any error occurs.

Structure – creation and alterationTable


 SQL Table is a collection of data which is organized in terms of rows and
columns. In DBMS, the table is known as relation and row as a tuple.

Operation on Table [DDL


COMMAND] 1. Create table
 The SQL CREATE TABLE statement is used to create a new table.
 Syntax: The basic syntax of the CREATE TABLE statement is as follows −

CREATE TABLE table_name(


column1 datatype, column2
datatype, column3 datatype,
.....
columnN datatype,
PRIMARY KEY (one or more columns));

Example: The following code block is an example, which creates a


CUSTOMERS table with an ID as a primary key and NOT NULL are the
constraints showing that these fields cannot be NULL while creating records
in this table –

CREATE TABLE CUSTOMERS (ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL, ADDRESS CHAR (25), PRIMARY KEY (ID));
2. Alter table
 The ALTER TABLE statement in Structured Query Language allows you to
add, rename, and delete columns of an existing table.
 This statement also allows database users to add and remove various SQL
constraints on the existing tables.
 Any user can also change the name of the table using this statement.
ALTER TABLE ADD Column
 In many situations, you may require to add the columns in the existing table.
 Instead of creating a whole table or database again you can easily add single
and multiple columns using the ADD keyword.

Syntax: ALTER TABLE table_name ADD column_name column-definition;

 The above syntax only allows you to add a single column to the existing table.
 If you want to add more than one column to the table in a single SQL
statement, then use the following syntax:
Syntax: ALTER TABLE table_name
ADD (column_Name1 column-definition,
column_Name2 column-definition,
.....
column_NameN column-definition);

Example 1: Let's take an example of a table named


Cars: Cars (Car_Name, Car_Color, Car_Cost)
ALTER TABLE Cars ADD Car_Model Varchar (20);

Example 2: Let's take an example of a table named


Employee: Employee (Emp_Id, Emp_Name, Emp_Salary)

Suppose, you want to add two columns, Emp_City and Emp_EmailID, in


the above Employee table. For this, you have to type the following query in
the SQL:

ALTER TABLE Employee ADD (Emp_City Varchar (20), Emp_EmailID


varchar (50));

ALTER TABLE DROP Column


 In many situations, you may require to delete the columns from the existing
table. Instead of deleting the whole table or database you can use DROP
keyword for deleting the columns.

Syntax: ALTER TABLE table_name DROP Column column_name;


Example: ALTER TABLE Cars DROP COLUMN Car_Color;

ALTER TABLE RENAME Column


 ALTER TABLE table_name RENAME COLUMN old_name to new_name;
Syntax: ALTER TABLE table_name RENAME COLUMN old_name to
new_name;
Example: ALTER TABLE Cars RENAME COLUMN Car_Color to Colors;

3. Rename table
 In some situations, database administrators and users want to change the
name of the table in the SQL database because they want to give a more
relevant name to the table.
 Any database user can easily change the name by using the RENAME
TABLE and ALTER TABLE statement in Structured Query Language.

Syntax: RENAME old_table _name To new_table_name;


Example 1: RENAME Cars To Car_2022_Details;
Syntax: ALTER TABLE old_table_name RENAME TO new_table_name;
Example 2: ALTER TABLE Employee RENAME To Coding_Employees;

4. Truncate table
 A truncate SQL statement is used to remove all rows (complete data) from a
table. It is similar to the DELETE statement with no WHERE clause.

Syntax: TRUNCATE TABLE table_name;


Example: TRUNCATE TABLE Employee;

5. Drop table
 A SQL DROP TABLE statement is used to delete a table definition and all
data from a table.
 This is very important to know that once a table is deleted all the information
available in the table is lost forever, so we have to be very careful when using
this command.
Syntax: DROP TABLE table_name;
Example: DROP TABLE STUDENTS;
DML COMMAND
1. INSERT
 SQL INSERT statement is a SQL query. It is used to insert a single or a
multiple records in a table.
There are two ways to insert values in a table.
 In the first method there is no need to specify the column name where the
data will be inserted, you need only their values.

INSERT INTO table_name VALUES (value1, value2, value3....);

 The second method specifies both the column name and values which you
want to insert.

INSERT INTO table_name (column1, column2, column3....) VALUES


(value1, value2, value3.....);

2. UPDATE
 SQL UPDATE statement is used to change the data of the records held by
tables. Which rows is to be update, it is decided by a condition. To specify
condition, we use WHERE clause.

Syntax: UPDATE table_name SET column_name = expression WHERE


conditions
Example: UPDATE students SET User_Name =’’user123’’
WHERE Student_Id = 3;

3. DELETE
 The DELETE statement is used to delete rows from a table. If you want to
remove a specific row from a table, you should use WHERE condition.

DELETE FROM table_name [WHERE condition];

 But if you do not specify the WHERE condition it will remove all the rows
from the table.

DELETE FROM table_name;


SQL SELECT Statement [DQL COMMAND]
 The SELECT statement is the most commonly used command in Structured
Query Language. It is used to access the records from one or more database
tables and views.
 It also retrieves the selected data that follow the conditions we want.
 By using this command, we can also access the particular record from the
particular column of the table.

Syntax: SELECT Column_Name_1, Column_Name_2, .....,


Column_Name_N FROM Table_Name;
EXAMPLE: students (sid, sname, per, city)

Select sid, sname from students;

 In this SELECT syntax, Column_Name_1, Column_Name_2, …..,


Column_Name_N are the name of those columns in the table whose data we
want to read.
 If you want to access all rows from all fields of the table, use the following
SQL SELECT syntax with * asterisk sign:

Syntax: SELECT * FROM table_name;


EXAMPLE: SELECT * FROM students;

SELECT Statement with WHERE clause


 The WHERE clause is used with SELECT statement to return only those
rows from the table, which satisfy the specified condition in the query.

Syntax: SELECT * FROM Name_of_Table WHERE [condition];


EXAMPLE: SELECT * FROM students where per<35;

SQL DISTINCT command


 The SQL DISTINCT command is used with SELECT key word to retrieve
only distinct or unique data.
 In a table, there may be a chance to exist a duplicate value and sometimes we
want to retrieve only unique values. In such scenarios, SQL SELECT
DISTINCT statement is used.
Syntax: SELECT DISTINCT column_name, column_name
FROM table_name;
EXAMPLE: SELECT DISTINCT city FROM students;

Defining constraints –

Primary key constraint


 A column or columns is called primary key (PK) that uniquely identifies each
row in the table.
 If you want to create a primary key, you should define a PRIMARY KEY
constraint when you create or modify a table.
 Primary key enforces the entity integrity of the table.
 Primary key always has unique data.
 A primary key cannot have null value.
 There can be no duplicate value for a primary key.
 A table can contain only one primary key constraint.

Example: The following SQL command creates a PRIMARY KEY on the


"S_Id" column when the "students" table is created.

CREATE TABLE students ( S_Id int NOT NULL, LastName varchar (255)
NOT NULL, FirstName varchar (255), Address varchar (255),
City varchar (255), PRIMARY KEY (S_Id) ) ;

foreign key constraint


 In the relational databases, a foreign key is a field or a column that is used to
establish a link between two tables.
 In simple words you can say that, a foreign key in one table used to point
primary key in another table.
 Let us take an example to explain it: Here are two tables first one is students
table and second is orders table. Here orders are given by students.
First table:
S_Id LastName FirstName CITY

1 MAURYA AJEET ALLAHABAD

2 JAISWAL RATAN GHAZIABAD

3 ARORA SAUMYA MODINAGAR

Second table:
O_Id OrderNo S_Id

1 99586465 2

2 78466588 2

3 22354846 3

4 57698656 1

 The "S_Id" column in the "Students" table is the PRIMARY KEY in the
"Students" table.
 The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
Example: To create a foreign key on the "S_Id" column when the "Orders"
table is created:

CREATE TABLE Orders( O_Id int NOT NULL, Order_No int NOT NULL,
PRIMAY KEY(O_Id), S_Id int REFERENCES Students(S_Id));

On Delete Cascade constraint


 ON DELETE CASCADE constraint is used in MySQL to delete the rows
from the child table (referencing table) automatically, when the rows from
the parent table (referenced table) are deleted.
 It is a kind of referential action related to the foreign key.
[A table in which a referential constraint and a foreign key are defined is
called a referencing table,
while a table that is referenced from a referencing table with a foreign key is
called a referenced table]
 Below are the steps that explain how ON DELETE CASCADE referential
action works.
Step 1: Create the Student table
create table student (sid int primary key, sname varchar(20));

Step 2: Insert rows into the Student table


insert into student values(1, 'jackson');
insert into student values(2, 'harry'); insert
into student values(3, 'allen');

Step 3: Execute the SELECT query to check the data in the Student table.
select * from student;
output:
SID SNAME
1 jackson
2 harry
3 allen

Step 4: Create the Course table


create table course(cid int primary key, cname varchar(20), sid int references
student(sid) on delete cascade);

Step 5: Insert rows into the Course table


insert into course values(101, 'DBMS', 1);
insert into course values(102, 'OS', 2);
insert into course values(103, 'JAVA', 3);

Step 6: Execute the SELECT query to check the data in the Course table.
select * from course;
CID CNAME SID

101 DBMS 1
102 OS 2
103 JAVA 3
Step 7: DELETE FROM Student table
[consider a case – If student left the college his information will be also
deleted from course table.]

delete from student where sid=1;

Step 8: Execute the SELECT query to check the data in the Student table
select * from student;
Output:
SID SNAME
2 harry
3 allen

Step 9: Execute the SELECT query to check the data in the Course table.
select * from course;
output:
CID CNAME SID

102 OS 2
103 JAVA 3

 Here, we have observed that student information is automatically deleted


from course table. This works out because the foreign key constraint ON
DELETE CASCADE is specified.

On Delete Set Null constraint


 Consider All of the above mentioned steps 1 to 9.
 Only make one change in step-4
Step 4: Create the Course table
create table course(cid int primary key, cname varchar(20), sid int references
student(sid) on delete set Null);
unique constraint
 The UNIQUE constraint ensures that all values in a column are different.
 Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.
 A PRIMARY KEY constraint automatically has a UNIQUE constraint.
 However, you can have many UNIQUE constraints per table, but only one
PRIMARY KEY constraint per table.
 The following SQL creates a UNIQUE constraint on the "ID" column when
the "Persons" table is created:

CREATE TABLE Persons ( ID int NOT NULL UNIQUE, LastName


varchar(255) NOT NULL, FirstName varchar(255), Age int );

not null constraint


 The NOT NULL constraint enforces a column to NOT accept NULL values.

Check constraint
 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 column it will allow only
certain values for this column
 The following SQL creates a CHECK constraint on the "Age" column when
the "Persons" table is created. The CHECK constraint ensures that the age of
a person must be 18, or older:

CREATE TABLE Persons (ID int NOT NULL, LastName varchar (255)
NOT NULL, FirstName varchar(255), Age int, CHECK (Age>=18));
insert into Persons Values(1,'DOE', 'JOHN',17);

Output:
ORA-02290: check constraint (SQL_BBLCKZTWJFHBEZNMKTPAIWQWC.SYS_C00106131955)
violated ORA-06512: at "SYS.DBMS_SQL", line 1721
IN, BETWEEN and LIKE operator
IN Operator
 The IN operator allows you to specify multiple values in a WHERE clause.
 The IN operator is a shorthand for multiple OR conditions.

Syntax: SELECT column_name(s) FROM table_name


WHERE column_name IN (value1, value2, ...);

Example: Consider a table


Customers (CustomerID, CustomerName, ContactName, Address, City,
PostalCode, Country)

The following SQL statement selects all customers that are located in
"Germany", "France" or "UK":

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');

BETWEEN Operator
 The BETWEEN operator selects values within a given range. The values can
be numbers, text, or dates.
 The BETWEEN operator is inclusive: begin and end values are included.

Syntax: SELECT column_name(s)FROM table_name


WHERE column_name BETWEEN value1 AND
value2; Example: Consider a table
Products (ProductID, ProductName, SupplierID, CategoryID, Unit, Price)

 The following SQL statement selects all products with a price between 10
and 20:
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

 To display the products outside the range of the previous example, use NOT
BETWEEN:
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
LIKE Operator
 The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.
 There are two wildcards often used in conjunction with the LIKE operator:
 The percent sign (%) represents zero, one, or multiple characters
 The underscore sign (_) represents one, single character

Syntax: SELECT column1, column2, ...


FROM table_name
WHERE columnN LIKE pattern;

Example: Consider a table


Customers (CustomerID, CustomerName, ContactName, Address, City,
PostalCode, Country)

SELECT * FROM Customers WHERE CustomerName LIKE 'a%';

 Here are some examples showing different LIKE operators with '%' and '_'
wildcards:
LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that start with "a"

WHERE CustomerName LIKE '%a' Finds any values that end with "a"
WHERECustomerNameLIKE Finds any values that have "or" in any
'%or%' position
WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the
second position
WHERE CustomerName LIKE 'a_%' Finds any values that start with "a" and are
at least 2 characters in length
WHERE CustomerName LIKE 'a__%' Finds any values that start with "a" and are
at least 3 characters in length
WHERE ContactName LIKE 'a%o' Finds any values that start with "a" and
ends with "o"
Aggregate functions
 SQL aggregation 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.

Types of SQL Aggregation Function:

1. COUNT FUNCTION
 COUNT function is used to Count the number of rows in a database table.
 It can work on both numeric and non-numeric data types.
 COUNT function uses the COUNT(*) that returns the count of all the rows in
a specified table.
 COUNT(*) considers duplicate and Null.

Sample table:
PRODUCT_MAST
PRODUCT COMPANY QTY RATE COST

Item1 Com1 2 10 20

Item2 Com2 3 25 75

Item3 Com1 2 30 60

Item4 Com3 5 10 50

Item5 Com2 2 20 40

Item6 Cpm1 3 25 75

Item7 Com1 5 30 150

Item8 Com1 3 10 30

Item9 Com2 2 25 50

Item10 Com3 4 30 120

Example: SELECT COUNT (*) FROM PRODUCT_MAST;


Output:
10
Example: COUNT with WHERE
SELECT COUNT (*) FROM PRODUCT_MAST WHERE RATE>=20;
Output:
7
Example: COUNT () with DISTINCT
SELECT COUNT (DISTINCT COMPANY) FROM PRODUCT_MAST;

Output:
3
Example: COUNT () with GROUP
BY SELECT COMPANY, COUNT
(*) FROM PRODUCT_MAST GROUP BY COMPANY;

Output:
Com1 5
Com2 3
Com3 2
Example: COUNT() with HAVING
SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST
GROUP BY COMPANY HAVING COUNT(*)>2;

Output:
Com1 5
Com2 3

2. SUM Function
 Sum function is used to calculate the sum of all selected columns.
 It works on numeric fields only.

Example: SUM ()
SELECT SUM(COST) FROM PRODUCT_MAST;
Output:
670
Example: SUM() with WHERE
SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3;

Output:
320

Example: SUM() with GROUP BY


SELECT COMPANY, SUM(COST) FROM
PRODUCT_MAST WHERE QTY>3 GROUP BY COMPANY;

Output:
Com1 150
Com2 170

Example: SUM() with HAVING


SELECT COMPANY, SUM(COST) FROM PRODUCT_MAST
GROUP BY COMPANY HAVING SUM(COST)>=170;

Output:
Com1 335
Com3 170

3. AVG function
 The AVG function is used to calculate the average value of the numeric type.
 AVG function returns the average of all non-Null values.

Example: SELECT AVG(COST) FROM


PRODUCT_MAST; Output:
67.00

4. MAX Function
 MAX function is used to find the maximum value of a certain column.
 This function determines the largest value of all selected values of a column.

Example: SELECT MAX(RATE) FROM


PRODUCT_MAST; 30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This
function determines the smallest value of all selected values of a column.

Example: SELECT MIN(RATE) FROM PRODUCT_MAST;


Output:
10

Built-in functions –numeric, date, string functions


REFER PRACTICAL-10
Set operations
REFER PRACTICAL-5
Sub-queries
 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.

Subqueries with the Select Statement


 SQL subqueries are most frequently used with the Select statement.
Syntax: SELECT column_name FROM table_name WHERE column_name
expression operator (SELECT column_name from table_name WHERE ...);

Consider the Student table have the following records:

ID NAME AGE ADDRESS PER

1 John 20 US 20

2 Stephan 26 Dubai 90

3 David 27 Bangkok 70

4 Alina 29 UK 35

5 Kathrin 34 Bangalore 85
Example: Find Name of student having maximum percentage.
select NAME from Student where PER IN (select MAX(PER) FROM Student);

Subqueries with the UPDATE Statement


 The subquery of SQL can be used in conjunction with the Update statement.
When a subquery is used with the Update statement, then either single or
multiple columns in a table can be updated.

Example: Update per of student to 35 whose percentage is minimum. update


Student set PER=35 where PER IN (select MIN(PER) from Student);

Subqueries with the DELETE Statement


 The subquery of SQL can be used in conjunction with the Delete statement
just like any other statements mentioned above.

Example: Delete record of student whose percentage is minimum.


delete from student where PER IN (select MIN(PER) FROM student)

Join
Refer unit-2 notes for theory and practical-6 for SQL Syntax

View and its Type


 The view is a virtual/logical table formed as a result of a query and used to
view or manipulate parts of the table.
 We can create the columns of the view from one or more tables. Its content is
based on base tables.
 The view is a database object with no values and contains rows and columns
the same as real tables.
 It does not occupy space on our systems.

We can create a view in MySQL using the below syntax:

CREATE VIEW view_name AS


SELECT columns
FROM tables
[WHERE conditions];
The following are the main advantages of the view:
 Views are usually virtual and do not occupy space in systems.
 Views enable us to hide some of the columns from the table.
 It simplifies complex queries because it can draw data from multiple tables
and present it as a single table.
 It helps in data security that shows only authorized information to the users.
 It presents a consistent, unchanged image of the database structure, even if
the source tables are renamed, split, or restructured.

There are 2 types of Views in SQL:


1. Simple views can only contain a single base table.
2. Complex views can be constructed on more than one base table. In
particular, complex views can contain: join conditions, a group by clause,
order by clause.

Transaction control commands

Refer practical-1 solution [TCL COMMAND]

UNIT-IV: SQL & PL/SQL Concepts

PART-II: PL/SQL Concepts

PL/SQL
 PL/SQL is a block structured language. The programs of PL/SQL are logical
blocks that can contain any number of nested sub-blocks.
 Pl/SQL stands for "Procedural Language extension of SQL" that is used in
Oracle. PL/SQL is integrated with Oracle database (since version 7).
 The functionalities of PL/SQL usually extended after each release of Oracle
database. Although PL/SQL is closely integrated with SQL language, yet it
adds some programming constraints that are not available in SQL.
Advantages of PL/SQL
 PL/SQL gives high productivity to programmers as it can query, transform,
and update data in a database.
 PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data types.
 Applications written in PL/SQL are fully portable.
 PL/SQL provides high security level.
 PL/SQL provides access to predefined SQL packages.
 PL/SQL provides support for Object-Oriented Programming.
 PL/SQL provides support for developing Web Applications and Server Pages.

PL/SQL Procedures
 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.
Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
Body: The body contains a declaration section, execution section and
exception section similar to a general PL/SQL block.

How to pass parameters in procedure:


 When you want to create a procedure or function, you have to define
parameters. There is three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or
function. The value of the parameter cannot be overwritten by the
procedure or the function.
2. OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be overwritten
by the procedure or function.
3. INOUT parameters: The INOUT parameter can be referenced by the
procedure or function and the value of the parameter can be overwritten
by the procedure or function.
Syntax for creating procedure:

CREATE PROCEDURE procedure_name [


(parameter [, parameter])]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];

Example-1: The following example creates a simple procedure that displays the
string 'Hello World!' on the screen when executed.

CREATE PROCEDURE greetings


AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
 When the above code is executed using the SQL prompt, it will produce the
following result −
Procedure created.

Executing a Standalone Procedure


A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block

The above procedure named 'greetings' can be called with the EXECUTE
keyword as −
EXECUTE greetings;

The above call will display −


Hello World
PL/SQL procedure successfully completed.
The procedure can also be called from another PL/SQL block −

BEGIN
greetings;
END;
/
The above call will display −

Hello World
PL/SQL procedure successfully completed.

Example-2: In this example, we are going to insert record in user table. So you
need to create user table first.

Table creation:
create table user (id number (10), name varchar (100), primary
key(id)); Now write the procedure code to insert record in user table.

Procedure Code:
create or replace procedure "INSERTUSER"
(id IN NUMBER, name IN VARCHAR)
is
begin
insert into user values (id, name);
end;

Output:
Procedure created.

PL/SQL program to call procedure


Let's see the code to call above created procedure.
BEGIN
insertuser(101,'ABC');
dbms_output.put_line('record inserted successfully');
END;
Now, see the "USER" table, you will see one record is inserted.

ID Name

101 ABC

PL/SQL Cursors
 When an SQL statement is processed, Oracle creates a memory area known
as context area.
 A cursor is a pointer to this context area. It contains all information needed
for processing the statement.
 In PL/SQL, the context area is controlled by Cursor. A cursor contains
information on a select statement and the rows of data accessed by it.
 There are two types of cursors:
o Implicit Cursors
o Explicit Cursors

1) PL/SQL Implicit Cursors


 The implicit cursors are automatically generated by Oracle while an SQL
statement is executed, if you don't use an explicit cursor for the statement.
 These are created by default to process the statements when DML statements
like INSERT, UPDATE, DELETE etc. are executed.
 Orcale provides some attributes known as Implicit cursor's attributes to check
the status of DML operations. Some of them are: %FOUND,
%NOTFOUND, %ROWCOUNT and %ISOPEN.
Attribute Description

%FOUND Its return value is TRUE if DML statements like INSERT,


DELETE and UPDATE affect at least one row or more rows
or a SELECT INTO statement returned one or more rows.
Otherwise it returns FALSE.

%NOTFOUND Its return value is TRUE if DML statements like INSERT,


DELETE and UPDATE affect no row, or a SELECT INTO
statement return no rows. Otherwise it returns FALSE. It is a
just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL
cursor is automatically closed after executing its associated
SQL statements.

%ROWCOUNT It returns the number of rows affected by DML statements like


INSERT, DELETE, and UPDATE or returned by a SELECT
INTO statement.

PL/SQL Implicit Cursor Example

Create customers table and have records:


ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

Let's execute the following program to update the table and increase salary of
each customer by 5000.
Here, SQL%ROWCOUNT attribute is used to determine the number of rows
affected:
Create procedure:

DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers updated ');
END IF;
END;
/
Output:
3 customers updated
PL/SQL procedure successfully completed.

Now, if you check the records in customer table, you will find that the rows are
updated.

select * from customers;


ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 25000

2 Suresh 22 Kanpur 27000

3 Mahesh 24 Ghaziabad 29000

2) PL/SQL Explicit Cursors


 The Explicit cursors are defined by the programmers to gain more control
over the context area.
 These cursors 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.
 Following is the syntax to create an explicit cursor:

Syntax of explicit cursor


CURSOR cursor_name IS select_statement;

Steps:
You must follow these steps while working with an explicit cursor.
1. Declare the cursor to initialize in the memory.
2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

1) Declare the cursor:


 It defines the cursor with a name and the associated SELECT statement.
Syntax for explicit cursor declaration

CURSOR name IS SELECT statement;

2) Open the cursor:


 It is used to allocate memory for the cursor and make it easy to fetch the rows
returned by the SQL statements into it.
Syntax for cursor open: OPEN cursor_name;

3) Fetch the cursor:


 It is used to access one row at a time. You can fetch rows from the above-
opened cursor as follows:
Syntax for cursor fetch: FETCH cursor_name INTO variable_list;

4) Close the cursor:


 It is used to release the allocated memory.
Syntax for cursor close: Close cursor_name;

PL/SQL Explicit Cursor Example


 Let's take an example to demonstrate the use of explicit cursor. In this
example, we are using the already created CUSTOMERS table.

Create customers table and have records:


ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

Create procedure:
Execute the following program to retrieve the customer name and address.
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;
/
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad

PL/SQL procedure successfully completed.

PL/SQL Triggers
 A trigger is a stored procedure in database which automatically invokes
whenever a special event in the database occurs.
 For example, a trigger can be invoked when a row is inserted into a specified
table or when certain table columns are being updated.

Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the
trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the
trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired

BEFORE and AFTER of Trigger:


 BEFORE triggers run the trigger action before the triggering statement is run.
 AFTER triggers run the trigger action after the triggering statement is run.
Example:
 Given Student Report Database, in which student marks assessment is
recorded.
 In such schema, create a trigger so that the total and percentage of specified
marks is automatically inserted whenever a record is insert.
 Here, as trigger will invoke before record is inserted so, BEFORE Tag can be
used.
Suppose the database Schema –
mysql> desc Student;
+------ +------------ +----- +---- +-------- +-------------- +
- - - - - --
| Field Type | Null | Key | Default | Extra |
|
+------ +------------ +----- +---- +-------- +-------------- +
- - - - - --
| sid | int(4) | NO | PRI | NULL | |
| name | varchar(30) | YES | | NULL | |
| subj1 int(2) | YES | | NULL | |
|
| subj2 int(2) | YES | | NULL | |
|
| subj3 int(2) | YES | | NULL | |
|
| total | int(3) | YES | | NULL | |
| per | int(3) | YES | | NULL | |
+------ +------------+----- +---- +-------- +-------------- +
- - - - - --
7 rows set (0.00 sec)
in
SQL Trigger
create trigger stud_marks
before INSERT
on
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3,
Student.per = Student.total * 100 / 300;

 Above SQL statement will create a trigger in the student database in which
whenever subjects marks are entered, before inserting this data into the
database, trigger will compute those two values and insert with the entered
values. i.e.,

mysql> insert into Student values (1, "ABCDE", 20, 50, 50, 0, 0);
Query OK, 1 row affected (0.09 sec)

mysql> select * from Student;


+ ----+------ + ------- ------- ------- ------- ------
-- + + + + +
| tid | name | subj1 | subj2 | subj3 | total | per
|
+ ----+------ + ------- ------- ------- ------- ------
-- + + + + +
| 100 | ABCDE 20 | 20 | 20 | 60 | 36 |
|
+ ----+------ + ------- ------- ------- ------- ------
-- + + + + +
1 row in set (0.00
sec)

In this way trigger can be creates and executed in the databases.

You might also like