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

SQL_MORE

The document covers advanced SQL topics including complex queries, triggers, views, and schema modifications. It explains concepts such as NULL values, nested queries, joins, aggregate functions, and the creation of views. Additionally, it provides examples and SQL syntax for various operations, demonstrating how to manipulate and retrieve data from databases effectively.

Uploaded by

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

SQL_MORE

The document covers advanced SQL topics including complex queries, triggers, views, and schema modifications. It explains concepts such as NULL values, nested queries, joins, aggregate functions, and the creation of views. Additionally, it provides examples and SQL syntax for various operations, demonstrating how to manipulate and retrieve data from databases effectively.

Uploaded by

msaturn860
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 68

More SQL:Complex Queries,Triggers,Views

and Schema Modification


More Complex SQL Retrieval Queries
• Comparison Involving NULL and Three Valued Logic
NULL is used to represent a missing value
It has Three Interpretation
Unknown Value:
Value exists but is not known or it is not known whether or not the value
exists
Ex: Person date of birth is not known or Person Phone number
Not available or not applicable:
Value exists but is possibly withheld.
Ex: Person has a phone number but don’t want to list
Not applicable attribute:
Ex: Year of graduation
More Complex SQL Retrieval Queries
• Retrieve the names of all employees who do
not have supervisor
SELECT FNAME
FROM EMPLOYEE
WHERE SSSN IS NULL
Nested Queries, Tuples and set/multiset comparison
Some queries requires existing values in the database be
fetched and then used in comparison condition
Nested Queries:
-Are complete select-from-where blocks within another SQL
query, that other query is called outer query
-Nested queries can also appear in the WHERE clause or
FROM clause of SELECT clause or other SQL clauses as
needed.
-Comparison operators
IN-Which compares a value v with a set(or multiset) of values
V and evaluates to TRUE if v is one of the element in V.
NOT IN reverse of IN operator
• Nested Queries, Tuples and set/multiset comparison
Example:
1) Retrieve the name of the employees who have dependent
SELECT FNAME
FROM EMPLOYEE
WHERE SSN IN(SELECT ESSN
FROM DEPENDENT)
2) Retrieve the SSN of the employees who work on the same
project and hours as that of employee Jhon Smith
SELECT ESSN
FROM WORKS_ON
WHERE (PNO,HOURS) IN (SELECT PNO,HOURS
FROM WORKS_ON
WHERE ESSN=‘123456789’)
• Nested Queries, Tuples and set/multiset comparison contd..
3)Retrieve the project numbers of projects that have an employee with
last name Smith involved as manager or an employee with last name
Franklin

SELECT DISTINCT PNO


FROM PROJECT
WHERE PNO IN(SELECT PNO
FROM EMPLOYEE E,PROJECT P,DEPARTMENT D,
WHERE E.SSN=D.MGR_SSN AND E.LNAME=‘Smith’ AND
D.DNO=P.DNO)
OR
(SELECT PNO
FROM EMPLOYEE E,WORKS_ON W
WHERE SSN=ESSN AND LNAME=‘Franklin))

v=[1,2,3,10,20,30]
V=[1,2,3] or V=[2,3,10,20]
V=[1,2,3,10,20,30]
• Nested Queries, Tuples and set/multiset comparison contd…
• =Any or some used to compare a single value v to set or multi
set
v=Any V or some returns TRUE if the value v is equal to some value
in the set V hence equivalent to IN
< ,> ,<=, >= operators can be combined with Any or some
Example:
1)Retrieve the name of the employees whose salary is same as that
of salary of employee working in dno 5
SELECT FNAME
FROM EMPLOYEE
WHERE SALARY=ANY(SELECT SALARY
FROM EMPLOYEE
WHERE DNO=5)
• Nested Queries, Tuples and set/multiset
comparison contd…
• solve
1)Retrieve the name of each employee who has
dependent with same first name and is the same
gender of the employee
2) Retrieve the name of each employee who are
controlling department
3) Retrieve the name of each employee who are
not controlling any department
Correlated Nested Queries
-Whenever a condition in the where clause of a
nested query references some attribute of relation
declared in the outer query then two queries are
said to be correlated
-Better to use correlated queries than nested
query.
1) Retrieve the name of the employees who have dependent
SELECT FNAME
FROM EMPLOYEE,DEPENDENT
WHERE SSN=ESSN
Joined Tables in SQL and Outer Joins
• JOIN
1)Retrieve the name of employees who are working for department
research using join

SELECT FNAME,LNAME
FROM (EMPLOYEE JOIN DEPARTMENT ON DNO=DNUMBER)
WHERE DNAME=‘Research’

• NATURAL JOIN
2)Retrieve the name of employees who are working for department
research using natural join
SELECT FNAME,LNAME
FROM (EMPLOYEE NATURAL JOIN DEPARTMENT
WHERE DNAME=‘Research’
IF EMPLOYEE and DEPARTMENT has same attribute name
Joined Tables in SQL and Outer Joins
• MULTY WAY JOIN
1)Retrieve the pnumber, dnumber last name,
address and date of birth of employee of
employees who are working on the projects
located at Stafford
SELECT PNUMBER,DNUMBER,LNAME,ADDRES,DOB
FROM (PROJECT JOIN DEPARTMENT ON
DNUM=DNUMBER ) JOIN EMPLOYEE ON
MGR_SSN=SSN
WHERE PLOCATION=‘Stafford’
The EXISTS and UNIQUE functions in SQL

• EXISTS,NOTEXISTS and UNIQUE are Boolean


functions that returns TRUE or FALSE hence
they can be used in WHERE clause condition.
EXISTS Clause
• The EXISTS clause is used to check whether the
nested query result is empty or not
• Returns TRUE if nested query has at least one
tuple or FALSE if nested query has no tuples
• Used in conjunction with corelated queries
The EXISTS and UNIQUE functions in SQL
CONTD…
EXISTS Clause
• Retrieve the names of employee who have
dependent
SELECT FNAME,LNAME
FROM EMPLOYEE
WHERE EXISTS(SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
The EXISTS and UNIQUE functions in SQL
CONTD…
EXISTS Clause
• Retrieve the names of managers who at least one dependent
SELECT FNAME,LNAME
FROM EMPLOYEE
WHERE EXISTS(SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
AND
EXISTS(SELECT *
FROM DEPARTMENT
WHERE SSN=MGR_SSN)
The EXISTS and UNIQUE functions in SQL

NOTEXISTS Clause
• The NOTEXISTS clause is used to check
whether the nested query result is empty or
not
• Returns FALSE if nested query has at least one
tuple or TRUE if nested query has no tuples
• Used in conjunction with corelated queries
The EXISTS and UNIQUE functions in SQL
CONTD…
NOT EXISTS Clause
• Retrieve the names of employee who do not
have dependent
SELECT FNAME,LNAME
FROM EMPLOYEE
WHERE NOT EXISTS(SELECT *
FROM DEPENDENT
WHERE SSN=ESSN)
The EXISTS and UNIQUE functions in SQL CONTD…
SOLVE
1)Retrieve the names of employee who are not working on any projects
2)Retrieve the names of employee who have dependent with gender and name of employee and dependent
are same
SELECT E.FNAME,E.LNAME
FROM EMPLOYEE E
WHERE EXISTS(SELECT *
FROM DEPENDENT D
WHERE E.SSN=E.ESSN AND
E.FNAME=D.FNAME AND
E.GENDER=F.GENDER)

3)Retrieve the names of each employee who works on all the projects controlled by department 5
SELECT E.FNAME,E.LNAME
FROM EMPLOYEE E
WHERE NOT EXISTS((SELECT PNUMBER
FROM PROJECT
WHERE DNUM=5)
EXCEPT
(SELECT PNO AS PNUMBER
FROM WORKS_ON
WHERE SSN=ESSN))
Explicit Sets and Renaming in SQL
Explicit set of values in the where clause can be used
• Retrieve the ssn of employees who works on pnumbers 1,2,3

SELECT DISTINCT ESSN


FROM WORKS_ON
WHERE PNO IN(1,2,3)

Renaming of attributes is also possible in SQL


• Retrieve the employee name and his/her immediate supervisor name

SELECT E.FNAME AS ENAME,S.FNAME AS SNAME


FROM EMPLOYEE E ,EMPLOYEE S
WHERE E.SSSN=S.SSN

Where E.FNAME is renamed as ENAME,


S.FNAME is renamed as SNAME are rename
Explicit Sets and Renaming in SQL
• SOLVE
1)Retrieve the names of employees who works in department 1,5
SELECT Fname
FROM EMPLOYEE
WHERE DNO IN(1,5)

2)Retrieve the names of employees who works for department


Research and Administration
SELECT Fname
FROM EMPLOYEE,DEPARTMENT
WHERE DNO=DNUM AND DNAME
IN('RESEARCH','ADMINSTARION')
Aggregate Functions in SQL
-Grouping and aggregate are required in many database
applications.
-Aggregate functions are used to summarize information from
multiple tuples into a single tuple summary.
-Grouping is used to create subgroups of tuples before
summarization .
--Followings are the aggregate functions
1)COUNT
2)SUM
3)MAX
4)MIN
5)AVG
Aggregate Functions in SQL CONTD..
COUNT
-Function returns the number of tuples or values as specified in query
--Used in SELECT or HAVING Clause
1)Retrieve the total number of employees in the company

SELECT COUNT(*)
FROM EMPLOYEE

Renaming attribute name

SELECT COUNT(*) AS NO_EMP


FROM EMPLOYEE
Aggregate Functions in SQL CONTD..
COUNT
2)Retrieve the total number of employees who are working for
Research department in the company

SELECT COUNT(*)
FROM EMPLOYEE JOIN DEPARTMENT ON DNO=DNUM AND
DNAME=‘RESEARCH’

3)Retrieve the number of distinct salaries of employees

SELECT COUNT(DISTINCT SALARY)


FROM EMPLOYEE
Aggregate Functions in SQL CONTD..
SUM,MAX,MIN,AVG
-Function can be applied to a set or multiset of numeric values AND
returns sum, maximum value, minimum value and average of the values
-Used in SELECT or HAVING Clause
1)Retrieve the sum of the salaries of all employees also retrieve
maximum,minimum and average salary
SELECT SUM(SALARY),MAX(SALARY),MIN(SALARY),AVG(SALARY)
FROM EMPLOYEE

The above query returns the single row summary of all the rows in the employee
table.
Aggregate Functions in SQL CONTD..
SUM,MAX,MIN,AVG
-Function can be applied to a set or multiset of numeric values AND
returns sum, maximum value, minimum value and average of the values
-Used in SELECT or HAVING Clause
1)Retrieve the sum of the salaries of all employees also retrieve
maximum,minimum and average salary
SELECT SUM(SALARY),MAX(SALARY),MIN(SALARY),AVG(SALARY)
FROM EMPLOYEE

The above query returns the single row summary of all the rows in the employee
table.
Aggregate Functions in SQL CONTD..
SUM,MAX,MIN,AVG contd..
1)Retrieve the sum of the salaries of all employees also retrieve
maximum,minimum and average salary

Rename the column names in the resulting single row table

SELECT SUM(SALARY) AS TOTSL_SAL,MAX(SALARY), AS


MAX_SAL,MIN(SALARY) AS MIN_SAL,AVG(SALARY) AS AVG_SAL
FROM EMPLOYEE
Aggregate Functions in SQL CONTD..
2)Retrieve the sum of the salaries of all employees,maximum,minimum and average
salary who are working for Research department

SELECT SUM(SALARY) AS TOTSL_SAL,MAX(SALARY), AS MAX_SAL,MIN(SALARY) AS


MIN_SAL,AVG(SALARY) AS AVG_SAL
FROM EMPLOYEE JOIN DEPARTMENT ON DNO=DNUMBER
WHERE DNAME=‘Research’

3)Retrieve the names of all employees who have two or more dependent
SELECT FNAME
FROM EMPLOYEE
WHERE (SELECT COUNT(*)
FROM DEPENDENT WHERE SSN=ESSN)>=2
Aggregate Functions in SQL CONTD..
SOLVE
1)Retrieve the total salaries of all employees ,maximum, minimum and
average salaries of employees who are working on project number 1

2)Retrieve the number of projects handled by the employee Jhon Smith

3)Retrieve the names of all employees who are working on two or more
projects.
Aggregate Functions in SQL CONTD..
Grouping:The GROUP BY and HAVING clauses
-SQL provides a GROUP BY clause to specify grouping
attributes which should also appear in the SELECT
clause
-Aggregate functions can be applied to subgroups of
tuples in a relation, where the subgroups are based on
some attribute values.
-Each group(partition) will consists of the tuples that
have the same value of some attributes called grouping
attributes
Aggregate Functions in SQL CONTD..

Examples
1)For each department retrieve the department number, the number of
employees in the department and their average salary.
SELECT DNO,COUNT(*),AVG(SALARY)
FROM EMPLOYEE
GROUP BY DNOS
Or
SELECT DNO AS DNO,COUNT(*) AS NO_OF_EMP,AVG(SALARY) AS AVG_SAL
FROM EMPLOYEE
GROUP BY DNOS

2)For each employee retrieve the ssn,ESSN, the number of dependent.


SELECT SSN,ESSN,COUNT(*)
FROM EMPLOYEE,DEPENDENT
WHERE SSN=ESSN
GROUP BY SSN, ESSN
Aggregate Functions in SQL CONTD..

Examples
3)For each project retrieve the project
number,project name and number of employees who
work on the project
SELECT PNUMBER,PNAME,COUNT(*)
FROM PROJECT,WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME
Aggregate Functions in SQL CONTD..

HAVING CLAUSE
-Sometimes the aggregate functions can be applied
for groups that satisfy certain conditions then
HAVING clause is used.
- HAVING provides a condition on the summary
information regarding the group of tuples
associated with each value of the grouping
attributes.
- The groups which satisfy the condition are
retrieved in the result of the query.
Aggregate Functions in SQL CONTD..

Examples
1)For each project on which more than two
employees work retrieve the project number,project
name and number of employees who work on the
project
SELECT PNUMBER,PNAME,COUNT(*)
FROM PROJECT,WORKS_ON
WHERE PNUMBER=PNO
GROUP BY PNUMBER,PNAME
HAVING COUNT(*)>2
Aggregate Functions in SQL CONTD..

Examples
1)For each department in which more than two
employees work retrieve the department number,
department name and number of employees who
work in the department
SELECT DNO,DNAME,COUNT(*)
FROM EMPLOYEE,DEPARTMENT
WHERE DNO=DNUM
GROUP BY DNO,DNAME
HAVING COUNT(*)>3
Aggregate Functions in SQL CONTD..

Examples
2)For each department in which more than five
employees work retrieve the department number,
number of employees who work in department

SELECT DNO,COUNT(*)
FROM EMPLOYEE
GROUP BY DNO
HAVING COUNT(*)>5
Aggregate Functions in SQL CONTD..

Examples
3)For each department that has more than five
employees retrieve the department number, number
of employees who are making more than $40000

SELECT DNO,COUNT(*)
FROM EMPLOYEE
WHERE SALRY>40000 AND DNO IN
(SELECT DNO FROM EMPLOYEE GROUP BY DNO
HAVING COUNT(*)>5)
GROUP BY DNO
Views (Virtual Tables) in SQL
Concept of View In SQL
-A view is single table which is derived from other
tables.
-Other tables may be base table or previously defined
view.
-A view is called virtual table because view does not
necessarily exists in physical form that is tuples or not
stored in database which limits the update operation
database but does not limits the on querying a view.
Views (Virtual Tables) in SQL
Specification of view in SQL
-A view can be created using CREATE VIEW
-Syntax is as follows
CREATE VIEW VIEW_NAME
AS SELECT <ATTRIBUTE-LIST>
FROM <TABLE-LIST>
WHERE<CONDITION>
GROUP BY <ATTRIBUTE-LIST>
-Where
ATTRIBUTE-LIST->List of attribute names whose values to be retrived
TABLE-LIST->List of table names
CONDITION->Boolean expression
Note:WHERE and GROUP BY is optional
-View can be deleted by using DROP command
DROP VIEW VIEW_NAME
VIEWS(VIRTLA TABLES) IN SQL
Examples
1)Create view that has employee name, department name and
salary
Without specifying attribute names
for view Specifying attribute names for view

CREATE VIEW EMP_DEPT CREATE VIEW


EMP_DEPT(NAME,DEPT_NAME,SAL)
AS SLECT FNAME,DNAME,SALARY
AS SLECT FNAME,DNAME,SALARY
FROM EMPLOYEE,DEPARTMENT
FROM EMPLOYEE,DEPARTMENT
WHERE DNO=DNUMBER
WHERE DNO=DNUMBER
Views (Virtual Tables) in SQL
Examples
Specifying SQL queries on view EMP_DEPT
1)Retrieve the content of EMP_DEPT
SELECT FROM EMP_DEPT
2)Retrieve the salary of the employee james who works for
department research
SELECT SALARY
FROM EMP_DEPT
WHERE FNAME='JAMES' AND DNAME='RESEARCH‘
3)Delete the view which was created
DROP VIEW EMP_DEPT
Views (Virtual Tables) in SQL
Examples
Specifying SQL queries on view
View is to be up to date that is if modification in base table results in
view automatically
UPDATE EMPLOYEE SET FNAME='ANNIE' WHERE SSN='987654321‘
SELECT *FROM EMP_DEPT
Views (Virtual Tables) in SQL
Examples
2)Create view that has employee name,project name and hours
CREATE VIEW WORKS_ON1
AS SLECT FNAME,PNAME,HOURS
FROM PROJECT,WORKS_ON
WHERE PNUMBER=PNO AND DNUM=DNO
Specify SQL queries on view
1)Retrieve the content of VIEW
SELECT *FROM WORKS_ON1
2)Retrieve the name of employee who works on project name Product X
SELECT FNAME
FROM WORKS_ON1
WHERE PNAME=‘PRODUCT X’
c)Delete the view which was created
DROP VIEW WORKS_ON1
Views (Virtual Tables) in SQL
Examples
3)a)Create view that has department number,number of
employees working in each department,total salary of the
employees for each department
CREATE VIEW DEPT_INFO(DNO,NUM_EMP,TOTAL_SALARY)
AS SLECT DNO,COUNT(*),SUM(SALARY)
FROM EMPLOYEE
GROUP BY DNO
b)Retreive the DEPT_INFO view
SELECT *FROM DEPT_INFO
b)Retreive the dno for which total salary is above 50000
SELECT *FROM DEPT_INFO WHERE TOTAL_SALARY>50000
c)Delete the view which was created
DROP VIEW DEPT_INFO
Views (Virtual Tables) in SQL
View implementation,view update and inline views
-A user can always issue a retrieval query against view.
-However issuing an insert, delete, update command on
view table in many cases not possible. Because
1)A view with a single defining table is updatable if the
view attributes contains primary key of the base relation,
also with not null constraint that do not have default
values.
Ex: DELETE FROM EMP_DEPT WHERE FNAME=‘ANNIE’
Views (Virtual Tables) in SQL
View implementation,view update and inline views
2)Views defined on multiple tables using joins are
generally not updatable.
Ex: UPDATE WORKS_ON1
SET PNAME=‘PRODCUT Z’
WHERE LNAME=‘SMITH’ AND FNAME=‘JHON’ AND
PNAME=‘PRODUCTX’
Here it is not possible for the DBMS to determine possible
updates intended
Views (Virtual Tables) in SQL
View implementation,view update and inline views
3)Views defined using grouping and aggregate functions
are not updatable.
Ex: UPDATE DEPT_INFO
SET TOTAL_SALARY=100000
WHERE DNO=1
The above updation doesn’t make much sense because
TOTAL_SALARY is not individual employee salaries. This is
incorrect
Schema Changes Statements In sql
1)DROP COMMAND
-Used to drop or delete schema elements such as tables, domains or
constraints also to drop a whole schema
-Deletes all records along with schema definition
Examples
a)SYNTAX: DROP TABLE TABLE NAME
EX: DROP TABLE EMPLOYEE
b)SYNTAX:DROP CONSTRAINT CONSTRAINT_NAME
EX:DROP CONSTRAINT EMP_PK_SSN
b)SYNTAX:DROP CONSTRAINT CONSTRAINT_NAME
EX:DROP CONSTRAINT EMP_PK_SSN
c)SYNTAX:DROP SCHEMA SCHEMA_NAME
EX:DROP SCHEMA COMPANY
Schema Change Statements
2)ALTER COMMAND
-Used to alter the definitions of base table or other named schema
elements

• ALTER TABLE statement


 The ALTER TABLE statement allows you to add a column to a table
 add a constraint to a table
 drop a column from a table
 drop an existing constraint from a table
 increase the width of a VARCHAR or VARCHAR FOR BIT DATA column
 change the increment value and start value of the identity column
 change the null ability constraint for a column
 change the default value for a column
Schema Change Statements in SQL

• ALTER TABLE statement


ALTER TABLE table-Name { ADD column-definition |
ADD CONSTRAINT clause | DROP [ COLUMN ] column-
name [ CASCADE | RESTRICT ] DROP { PRIMARY KEY
| FOREIGN KEY constraint-name | UNIQUE constraint-
name | CHECK constraint-name | CONSTRAINT
constraint-name } CASCADE||RESTRICT
Schema Change Statements in SQL
• ALTER TABLE statement
Adding columns
Syntax :ALTER TABLE TABLE-NAME ADD COLUMN -
NAME DATATYPE

Ex: ALTER TABLE STUDENT ADD email varchar(10)


• Dropping columns
ALTER TABLE DROP COLUMN COLUMN-NAME allows
you to drop a column from a table.
EX: ALTER TABLE STUDENT DROP COLUMN email
Schema Change Statements in SQL
ALTER STATEMENT
• Modifying columns
• The column-alteration allows you to alter the named
column by specifying the data type and new size
after the column name.

ALTER TABLE table_name


MODIFY COLUMN datatype;

EX: ALTER TABLE STUDENT MODIFY USN int;


Schema Change Statements in SQL
DROP STATEMENT
• The DROP TABLE statement is used to drop an
existing table in a database.

Syntax: DROP TABLE table_name;


EX:DROP TABLE STUDENT
ALTER STATEMENT
ALTER TABLE statement
• Adding constraints by giving name

ALTER TABLE ADD CONSTRAINT adds a table-level constraint to an existing table.

EXAMPLES
ALTER TABLE STUDENT ADD CONSTRAINT PK_STUD PRIMARY KEY (USN);
Adding constraints without giving name

ALTER TABLE STUDENT ADD PRIMARY KEY (USN);


Or
ALTER TABLE STUDENT MODIFY USN char(8) PRIMARY KEY

• Dropping constraints
ALTER TABLE DROP CONSTRAINT drops a constraint on an existing table.
EX:ALTER TABLE STUDENT DROP PK_STUD;
PL SQL PROGRAMMING
• PL/SQL is a combination of SQL along with the procedural
features of programming languages.
• It was developed by Oracle Corporation in the early 90's to
enhance the capabilities of SQL.
• PL/SQL is one of three key programming languages embedded in
the Oracle Database, along with SQL itself and Java.
• PL/SQL Program Units
A PL/SQL unit is any one of the following −
 PL/SQL block
 Function
 Package
 Procedure
 Trigger
PL SQL PROGRAMMING
• Basic Syntax of PL/SQL which is a block-structured language;
• this means that the PL/SQL programs are divided and written
in logical blocks of code.
• Each block consists of three sub-parts −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
/
PL SQL PROGRAMMING
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
PL SQL PROGRAMMING
• PL SQL PROGRAM TO ADD TWO NUMBERS
1) Initialization of variables
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
PL SQL PROGRAMMING
2) WRITE PL SQL PROGRAM TO ACCEPT TWO NUMBERS AND FIND THERE
SUM

DECLARE
a integer := :a;
b integer := :b;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
PL SQL PROGRAMMING
PL SQL PROGRAM TO FIND LARGEST OF TWO NUMBERS
DECLARE
a integer :=:A;
b integer :=:B;
BEGIN
IF( a >b ) THEN
dbms_output.put_line(a||' '||'Is larger ' );
ELSE
dbms_output.put_line(b||' '||'b is larger ' );
END IF;
END;
PL SQL PROGRAMMING
• PL SQL PROGRAM TO GENERATE
1 TO 10 NUMBERS
1)USING WHILE STATEMENTS or
DECLARE
DECLARE
i NUMBER := 1;
BEGIN
i INTEGER := 1;
LOOP BEGIN
EXIT WHEN i>10; WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i); DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
i := i+1;
END LOOP;
END; END LOOP;
END;
PL SQL PROGRAMMING
• PL SQL PROGRAM TO GENERATE 1 TO 10 NUMBERS
2)USING FOR STATEMENTS
BEGIN
FOR k IN 1..10 LOOP
-- note that k was not declared
DBMS_OUTPUT.PUT_LINE(k);
END LOOP;
END;
PL SQL PROGRAMMING
PL/SQL subprograms are named PL/SQL blocks that can be
invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
Functions − These subprograms return a single value; mainly
used to compute and return a value.
Procedures − These subprograms do not return a value directly;
mainly used to perform an action.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE
PROCEDURE statement.
PL SQL PROGRAMMING
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows :
CREATE[OR REPLACE] PROCEDURE procedure_name[(paramenter[In|Out|Inout])
{IS/AS}
[declaration_section]
BEGIN
Executable_section
END[procedure_name]
Where,
procedure-name : 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
OUT represents the parameter that will be used to return a value outside of the
procedure.
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 the value can be read.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
PL SQL PROGRAMMING
Example:
The following example creates a simple procedure that displays
the string 'Hello World!' on the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
Example:
PL SQL PROGRAMMING
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
1)Using the EXECUTE keyword
2)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; //used in sql propmpt
Or
BEGIN
greetings;
END; /
-Procedure can be droped using
SYNTAX:DROP PROCEDURE PROCEDURE _NAME

EX:DROP PROCEDURE GREETINGS


PL SQL PROGRAMMING
Example:
Create a procedure to to find largest of two numbers pass input
parameter using IN and procedure to return value using out parameter

CREATE OR REPLACE PROCEDURE LARGEST(A IN INTEGER ,B IN


INTEGER,R OUT INTEGER) IS
BEGIN
IF( A >B ) THEN
R:=A;
ELSE
R:=B;
END IF;
END;
/
PL SQL PROGRAMMING
Example: Procedure calling is as follows

DECLARE
A INTEGER:=2;
B INTEGER:=4;
RES INTEGER;
BEGIN
LARGEST(A,B,RES);
DBMS_OUTPUT.PUT_LINE(RES);
END;
/
PL SQL PROGRAMMING
• Write a stored procedure which updates the name of the
employee if ssn value is passed

CREATE OR REPLACE PROCEDURE UPDATE_NAME( SS IN


EMPLOYEE.FNAME%TYPE,NNAME IN EMPLOYEE.FNAME%TYPE)
AS
ENAME EMPLOYEE.FNAME%TYPE;
BEGIN
UPDATE EMPLOYEE SET FNAME=NNAME WHERE SSN=SS;
SELECT FNAME INTO ENAME FROM EMPLOYEE WHERE
SSN=SS;
DBMS_OUTPUT.PUT_LINE('UPDATED NAME IS:'||ENAME);
END;
/
PL SQL PROGRAMMING

DECLARE
SSNE EMPLOYEE.SSN%TYPE:=:SSNE;
NNAME EMPLOYEE.FNAME
%TYPE:=:NNAME;
BEGIN
UPDATE_NAME(SSNE,NNAME);
END;
/
SELECT *FROM EMPLOYEE;

You might also like