Вы находитесь на странице: 1из 16

Different PL/SQL Examples :

Example 1 : Write a program to print reverse of number.


User can use the in built function of Oracle to reverse number directly. But here we will try
to resolve this using anonymous block.

Program :
Declare num1 number:=&num1; ---Declaring the input number
rev_num number:=0; ---Declaring Reverse number as 0
Begin ---Start of PL/SQL block
while(num1>0) ---Check condition that number is
greater than 0
Loop
rev_num=rev_num*10+mod(num1,10); ---Reverse condition
num1=num1/10; ---Reverse condition
End loop;
Dbms_Output.Put_Line('Reverse of Number'||num1||'is'|| rev_num);
End;
Output :
IF user gives number as 786 as input

Output will be

Reverse of Number 786 is 687.

Example 2 : Write a program to calculate factorial of given


number.
Lets try to solve this using the anonymous block of PL/SQL.This is most common PL/SQL
Example in all the different kind of PL/SQL Examples.Let me first explain the logic of
factorial number.

4! is 4*3*2*1 = 24
Program:
Declare num1 number:= &num1; ---Declaring the input of
number
fact_num number:= 1; ---Initialise fact_num as 1
temp_num number; ---This is for doing factorial
number logic
begin temp_num := num1; ---assign num1 to
temp_num
while (num1 > 0) ---check condition whether it is
greather than 0
loop
fact_num := fact_num * num1; ---factorial number logic
num1 := num1 - 1; ---factorial number logic
end loop;
Dbms_Output.Put_line('factorial is ' || fact_num);
end;
Output:
If user gives input as 3 then output is
Factorial is 6.

Example 3 : Write a program to check that number is


Armstrong number or not.
Before starting the program let me first explain you about the Armstrong number.

An Armstrong number of three digits is an integer such that the sum of the cubes of its
digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3
+ 7**3 + 1**3 = 371.
Program:
declare
num number;
tot number:=0;
var1 number;
var2 number;
begin num:=#
tmp:=num;
while tmp>0
loop
var1:=tmp mod 10;
tot:= tot + (var1*var1*var1);
tmp:=tmp/10;
end loop;
if(tot==num)
then
dbms_output.put_line(num||' is armstrong no');
else
dbms_output.put_line(num||' is not a armstrong no');
end if
end;
Output:
If user gives the input as 371 then output will be,

371 is armstrong no.


Example 4 : Write a program to print the Fibonacci series.
This is most common program may ask in interview.

Program:
DECLARE
num number := &n;
n1 number := 0;
n2 number := 1;
n3 number; BEGIN
dbms_output.put_line(n1);
dbms_output.put_line(n2);
for i in 3..num
loop
n3 := n1 + n2;
dbms_output.put_line(n3);
n1 := n2;
n2 := n3;
end loop;
END;
Example 5 : Write a program to print prime numbers
between 1 to 100.
This is also a most common example asked in interviews.

Program:

begin
for i in 1..100 loop
if i in (1,5,7) then
dbms_output.put_line(' These are known prime numbers '||i);
end if; if i not in (1,5,7) then
if mod(i,3)=0 or mod(i,6)=0 or mod(i,9)=0
then null;
elsif mod(i,2)=0 or mod(i,4)=0 or mod(i,8)=0 then
null; elsif mod(i,5)=0 or mod(i,10)=0 then null;
elsif mod(i,7)=0 then null; else
dbms_output.put_line(' Is this a prime number?? '||i);
end if;
end if;
end loop;
end;
1.What is Stored Procedure? ( 100% asked Stored Procedure Interview Questions )
Answer:
Stored procedures are nothing but named blocks which contains the group of SQL
statements to achieve specific functionality.A stored procedure or in simple a proc is a
named PL/SQL block which performs one or more specific task. This is similar to a
procedure in other programming languages.Stored Procedures accepts the different input
parameters and gives the result as per requirement of user. PL/SQL is executed in the
database, you can include SQL statements in your code without having to establish a
separate connection.Stored Procedure reduces the network traffic and improves the system
performance.Stored procedures are used to ensure the data integrity of database.

2.What is basic Syntax of Stored Procedure in PL SQL?( 100% asked Stored Procedure
Interview Questions )
Answer:
The PL SQL procedure have following syntax :

CREATE OR REPLACE procedure_name(arg1 data_type, …)


AS

BEGIN ….

SQL_Statements……

END procedure_name;
CREATE OR REPLACE : This keyword is used to create or replace the database object.

IS/AS : These are keywords which indicates the start of procedure.

SQL Statements: These are nothing but set of SQL statements where actual business logic
is written.

3.What is the basic difference between IS/AS in SQL Stored Procedure?


Answer:
Both ‘IS’ and ‘AS’ are equivalent to each other. There is no difference between IS and AS
in SQL Stored procedure.

4.What is difference between anonymous block and Stored Procedure?


Answer:
Anonymous blocks are nothing but the PL SQL statements which are written in between
begin and end which is not stored in to Database Memory. Stored Procedures are named
block which are stored in to Database memory as database objects.

5.Where the stored procedures are stored in database?


Answer:
Stored Procedure is a subroutine available to applications accessing a relational database
system. Stored Procedures (sometimes called a proc, sproc, StoPro, or SP) are actually
stored in the database data dictionary.

6.What are different types of Stored Procedures?


Answer:
There are two types of Stored Procedures:

1.User Defined Procedures : This category includes the code written by developers.

2.System Stored Procedures: These are stored procedures which are already written
scripts in Oracle. User just needs to run that procedure.

3.Extended Procedure

4.CLR Stored Procedure.

7.What are different usages of Stored Procedure? ( 100% asked Stored Procedure
Interview Questions )
Answer:
Stored Procedures are named blocks which are used to add the business logic to different
programs.Procedures are used in data validation most of the times. If there is a functional
requirement where user needs to validate the data according to the customer requirement
then this logic is been added in Stored Procedure.Complex Functionalities needs huge
amount of data to be processed.Stored Procedures are used to process huge amount of
data at a same time.Following are bullet points of usages of Stored Procedure:

1.Data Validation Purpose

2.Huge Data Processsing

3.Improve System Performance

4.Adding complex logic centralized

5.Access Control Mechanism

8.What is difference between Stored Procedure and Function?


Answer:
Following is difference between Stored Procedure and functions.

Stored Procedure Functions

Stored in database in compiled format.


Compilation Will compiled at run time
Note: Compiled indicates, Execution plan
will be made by sql at the time it created and
stored in DB.

It can directly return only integers It can return any scalar or table

Return type Return type is not must Return type is must

It can also return more than one values (of


Multiple return any data type) indirectly with the help of out
values parameters It won’t support out parameters

Cannot have DML statements.

Note: In case of multi-table valued func


DML Statements Can have DML statements. contain DML statements affecting Table

Stored procedure can execute function.

Cannot be the part of Select query as a Function cannot execute stored proced
column.
Can be the part of select query as a colu
Stored Procedures cannot be used in the SQL
statements anywhere in the Functions be used in the SQL statement
Execution WHERE/HAVING/SELECT in the WHERE/HAVING/SELECT

Exception
handling Can have Try….Catch Cannot have Try….Catch

9.Can Procedures called inside functions? Yes or No Why?


Answer:
1. Stored Procedure may contain DML statements.

2. Function can’t contain DML statements.


So executing Function inside stored procedure will never break rule 1.
But executing stored procedure inside function may break rule no 2.

10.Can We call Stored Procedure inside Stored Procedure?


Answer:
Yes we can call Stored Procedure inside Stored Procedure.
11.What is recursive Stored Procedure?
Answer:
The Stored Procedures which are used to perform repetitive tasks are called as recursive
stored procedures.Recursive feature is disabled by default but can be activated by using the
following command on the server max_sp_recursion_depth, also don?t forget to rename the
system variable to a non zero variable.

12.What are different extensions for Stored Procedures?( 100% asked Stored Procedure
Interview Questions )
Answer:
Most of the database systems have proprietary and vendor based extensions. Microsoft
allows procedures to be written using Transact-SQL. Oracle calls its extension as PL/SQL.
DB2 has its extension as PL/SQL. PL/pgSQL is the extension used by PostgreSQL SQL
and this allows users to have their own functional language such as pl/PHP and pl/Perl.

13.Does the data stored in stored procedure increase access time or execution time?
Explain.
Answer:
Data stored in stored procedures can be retrieved much faster than the data stored in SQL
database. Data can be precompiledand stored in Stored procedures. This reduces the
time gap between query and compiling as the data has been precompiled and stored in the
procedure. To avoid repetitive nature of the data base statement caches are used.
14.Can someone able to call DDL in Stored Procedure?( 100% asked Stored Procedure
Interview Questions )
Answer:
Yes we can call the DDL statement in Stored Procedure. Using Execute Immediate we can
call the DDL statements in Stored Procedures.

15.What are external procedures and when they are used?


Answer:
External procedures are Extended stored procedures only. They let you create your own
external routines in a programming language such as C. Extended stored procedures are
DLLs that an instance of Microsoft SQL Server can dynamically load and run.Extended
stored procedures run directly in the address space of an instance of SQL Server and are
programmed by using the SQL Server Extended Stored Procedure API.
16.What are advantages of Stored Procedure?
Answer:
There are following advantages of Stored Procedures:

1.Reduce Network usage between Client and Server.

2.Improved Security

3.Fast Data Processing

4.Performance Tuning of Application

5.Reduced Development cost and increase relibility

6.Encapsulating the different complex logic

7.Security

17.What is mean by implementing the Business Logic in stored procedure?( 100%


asked Stored Procedure Interview Questions )
Answer:
Stored procedures implement business logic into the database. It is embedded as API and
this reduces the implementation of Logic code again explicitly. Implementation of business
logic internally reduces the chances of data becoming corrupt.

18.What are different parameters of Stored Procedures?( 100% asked Stored Procedure
Interview Questions )
Answer:
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

19.Can Procedure contain return value?


Answer:
Procedure may or may not contain return value. Function must return the value.

20.How one can execute the procedure?


Answer:
There are two ways to execute a procedure.

1) From the SQL prompt.

EXECUTE [or EXEC] procedure_name;


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

21.How to delete procedure?


Answer:
There are two ways to delete specific procedure:

1.By using the Editor :


By using any SQL editor (toad,SQL developer) user can delete procedure by right clicking
the procedure name and choose delete option.

2.By using Command :


Using following command user can delete procedure.

Drop procedure Procedure_name;


22.Explain different modes of procedures?
Answer:
There are 3 different modes of Procedure:

1.In

2.Out

3.In/Out

1.In mode :
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 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.
2.Out mode:
An OUT parameter returns a value to the calling program. Inside the 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.
3.In/Out mode:
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 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.
23.Explain IN/OUT mode with example?
Answer:
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 the value can be read.
Following is the example of IN/OUT mode:
DECLARE
a number;
b number;
c number;
PROCEDURE findMax(x IN number, y IN number, z OUT number) IS
BEGIN
IF x > y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 147;
b:= 457;
findMax(a, b, c);
dbms_output.put_line(' The maximum of (147, 457) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −

The maximum of (147, 457) : 457

PL/SQL procedure successfully completed.


1.How to display 1 to 100 Numbers with query?
Answer:
Select level from dual connect by level <=100;
Tip: User needs to know the concept of Hierarchical queries. Click here to get concept of
hierarchical queries
2.How to remove duplicate rows from table?(100% asked in Complex SQL Interview
Questions )
Answer:
First Step: Selecting Duplicate rows from table
Tip: Use concept of max (rowid) of table. Click here to get concept of rowid.
Select rollno FROM Student WHERE ROWID <>

(Select max (rowid) from Student b where rollno=b.rollno);


Step 2: Delete duplicate rows
Delete FROM Student WHERE ROWID <>

(Select max (rowid) from Student b where rollno=b.rollno);


3.How to find count of duplicate rows? (95% asked in SQL queries for Interviews )
Answer:
Select rollno, count (rollno) from Student

Group by rollno
Having count (rollno)>1

Order by count (rollno) desc;


4.How to find Third highest salary in Employee table using self-join?(90% asked
Complex SQL Interview Questions )
Answer:
Select * from Employee a Where 3 = (Select Count (distinct Salary) from Employee
where a.salary<=b.salary;
Click here for explanation.
5.How to Show the Max marks and min marks together from student table?
Answer:
Select max (marks) from Student

Union

Select min (marks) from Student;


Tip : Use the concept of union to show the max and min marks together. Click here to get
information about union and union all.
6.How to display following using query?
*
**
***
Answer:
We cannot use dual table to display output given above. To display output use any table. I
am using Student table.

SELECT lpad (‘*’, ROWNUM,’*’) FROM Student WHERE ROWNUM <4;


7.How to display Date in DD-MON-YYYY table?
Answer:
Select to_date (Hire_date,’DD-MON-YYYY’) Date_Format from Employee;
8.If marks column contain the comma separated values from Student table. How to
calculate the count of that comma separated values?
Student Name Marks

Amit 30,130,20,4

Sukruta 100,20,30

Sonali 140,10
Want to display output like :

Student Name Marks Count

Amit 4

Sukruta 3

Sonali 2

Answer:
Select Student_name, regexp_count (marks,’,’) + As “Marks Count” from Student;
Tip: In real scenarios, lot of times developer needs to calculate the number of commas in
the column then regexp_count function is used.
9.How to create the Student_1 table, which is exact replica of Student table?
Answer:
Create Table Student_1 as select * from Student;
10.What is Query to drop all user tables from Oracle?
Answer:
To Drop all tables user needs to write simple PLSQL block

Begin

For I In

(Select * from Tabs) —Tabs is system table in which user get the different user
defined table names.

Loop

Execute immediate (‘Drop Table ‘||i.table_name||’cascade constraints’);

End loop;

End;
11.How to get number of Weekends of current month?
Answer:
SELECT count (*) AS Weekends FROM
(SELECT TRUNC (SYSDATE,’mm’) +LEVEL-1 Current_dt

FROM Dual

CONNECT BY LEVEL <= last_day (SYSDATE) – TRUNC (SYSDATE,’mm’) +1

Where TO_CHAR (Current_dt,’dy’) IN (‘sat’,’sun’);


Let us Fragment the Query for Understanding,

Step 1: Try running internal query


SELECT TRUNC (SYSDATE,’mm’) +LEVEL-1 Current_dt

FROM Dual

CONNECT BY LEVEL <= last_day (SYSDATE) – TRUNC (SYSDATE,’mm’) +1;


The query will give the all the dates from first to last of current date.

Step 2: To count the weekends.


From all the month, we need to calculate the weekends. Weekends means the Saturdays
and Sundays from the month. So here, we need to use To_char function and ‘dy’ attribute of
that function to calculate days. Therefore, we have used Where TO_CHAR (Current_dt,’dy’)
IN (‘sat’,’sun’); condition.
Therefore, Final Query will be,
SELECT count(*) AS Weekends FROM

(SELECT TRUNC (SYSDATE,’mm’) +LEVEL-1 Current_dt

FROM Dual

CONNECT BY LEVEL <= last_day (SYSDATE) – TRUNC (SYSDATE,’mm’) +1

Where TO_CHAR (Current_dt,’dy’) IN (‘sat’,’sun’);


12.What is query to fetch last day of previous month in oracle?
Answer:
Select LAST_DAY (ADD_MONTHS (SYSDATE,-1)) from dual;
13.How to display the String vertically in Oracle?
Answer:
SELECT SUBSTR (‘AMIET’, LEVEL, 1) FROM dual
Connect by level <= length (‘AMIET’);
Output :

T
14.Write query to find the repeated characters from your name?
Answer:
Select regexp_count (‘AmitA’,’A’) as Repeated_character from dual;
15.How to display departmentwise and monthwise maximum salary?
Answer:
Select Department_no, TO_CHAR (Hire_date,’Mon’) as Month from Employee group by
Department_no, TO_CHAR (Hire_date,’mon’);
16.How to get DDL of table in Oracle?
Answer:
To get DDL user needs to use dbms_metadata package and its get_ddl procedure,

Select dbms_metadata.get_ddl (TABLE,’table_name’) from dual;


17.How to convert seconds in to time format?
Answer:
SELECT

TO_CHAR (TRUNC (2700/3600),’FM9900′) || ‘:’ ||

TO_CHAR (TRUNC (MOD (2700, 3600)/60),’FM00′) || ‘:’ ||

TO_CHAR (MOD (2700, 60),’FM00′)

FROM DUAL;
Where 2700 is seconds.

Output:
00:45:00
18.How to calculate number of rows in table without using count function?
Answer:
Select table_name, num_rows from user_tables where table_name=’Employee’;
Tip: User needs to use the system tables for the same. So using user_tables user will get
the number of rows in the table.
19.How to fetch common records from two different tables which has not any joining
condition.
Answer:
Select * from Table1

Intersect

Select * from Table2;


Tip: Use Intersect keyword for fetching common records.
20.Display 4 to 7 records from Employee table.
Answer:
Select * from (Select rownum as ‘No_of_Row’, E.* from Employee E)

Where No_of_Row between 4 and 7;

Вам также может понравиться