0% found this document useful (0 votes)
2 views24 pages

SQL_PL

Uploaded by

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

SQL_PL

Uploaded by

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

SQL/PLSQL

Codd’s Rules:-
Codd's twelve rules are a set of thirteen rules(number from 0 to 12)
proposed by Edgar F.Codd,a pioneer of relational model for databases

Rule 0: Foundation Rule


A relational database management system must manage its stored data
using its relational capabilities
In simple terms, if a database claims to be relational, it must follow all the
other 12 rules.

Rule 1: Information Rule


All data must be stored in table format (rows and columns).
Data should be stored in a structured way, with each column representing
an attribute and each row representing a record.
Example:

Student_ID Name Age


101 Rahul 20
102 Amit 22

Rule 2: Guaranteed Access Rule


Every piece of data in the database must be accessible by using a
combination of table name, primary key, and column name.
This ensures uniqueness and no duplicate data.
Example:

SELECT Age FROM Students WHERE Name = 'Amit';

Rule 3: Systematic Treatment of NULL Values


Fully relational DBMS Supports null values
Null values are used to represent missing information
The Systematic provides a Systematic way to handle missing data

Student_ID Name Age


101 Rahul 20
102 Amit NULL
Here, Amit's age is unknown, not zero.

Rule 4: Active Online Catalog (Data Dictionary)


The database structure (schema, tables, constraints, etc.) must be stored
in the system catalog and should be accessible using SQL queries.
This ensures that users can retrieve metadata (data about data).
Example:

SELECT * FROM INFORMATION_SCHEMA.TABLES;


Rule 5: Comprehensive Data Sublanguage Rule
The system must support at least one relational language (like SQL) to
access and manipulate data.
SQL must support operations like:
Data Definition Language (DDL): CREATE, ALTER, DROP
Data Manipulation Language (DML): INSERT, UPDATE, DELETE
Transaction Control: COMMIT, ROLLBACK
Example

SELECT * FROM Students WHERE Age > 20;

Rule 6: View Updating Rule


A database should allow modifications to views (virtual tables) whenever
possible.
If a view is based on a single table, it should be updatable.
Example:

CREATE VIEW StudentView AS


SELECT Name, Age FROM Students WHERE Age > 20;
Modifying this view should reflect changes in the base table.

Rule 7: High-Level Insert, Update, and Delete


The system must allow inserting, updating, and deleting data using a
single SQL statement instead of processing row-by-row.
Example:
Instead of updating each row separately, use:

UPDATE Students SET Age = Age + 1 WHERE Student_ID = 101;

Rule 8: Physical Data Independence


Changes in physical storage (disk, memory, indexing, etc.) should not affect
the logical structure of the database.
Users and applications should not worry about how data is stored.
Example:
If we change the database storage from HDD to SSD, it should not affect
queries.

Rule 9: Logical Data Independence


Changes in logical schema (table structure, column addition, etc.) should
not impact applications.
Applications should not require modification if we add or remove columns.
Example:
Adding a new column should not break existing queries:

ALTER TABLE Students ADD COLUMN Address VARCHAR(255);


Rule 10: Integrity Independence
Integrity constraints (like primary key, foreign key, unique constraints)
should be stored within the database, not at the application level.
Constraints should be automatically enforced.

ALTER TABLE Students ADD CONSTRAINT pk_student PRIMARY KEY


(Student_ID);
This ensures data integrity without needing application logic.

Rule 11: Distribution Independence


A true RDBMS should work whether the database is centralized or
distributed across multiple locations.
The user should not know whether data comes from a single server or
multiple servers.
Example:
A query should return results regardless of whether data is stored in New
York or India:

SELECT * FROM Students;

Rule 12: Non-Subversion Rule


If a database provides low-level access (e.g., using file handling methods),
it must not bypass relational security and integrity constraints.
All access should be through the relational interface (SQL).
Example:
A user should not be able to delete data using an external program while
bypassing SQL security constraints.

Que 2) Explain different type of data types used in SQL


In SQL, data types define the type of data that can be stored in a table
column. They help ensure data integrity and optimize storage. SQL data
types are categorized into several types:

CHARACTER(n):
This data type represents a fixed length string of exactly 'n' characters
where 'n' is greater than zero and should be an integer.
Storage: n bytes (fixed).
Max Size: 255 characters
Use Case: Storing fixed-length strings like country codes ('IN', 'US').

BIT(n) and BIT VARYING(n):


BIT(n): Represents a fixed-length string of exactly 'n' bits.
BIT VARYING(n): Represents a variable-length string with a maximum
length of 'n' bits.
'n' must be a positive integer in both cases.
DECIMAL(p, s):
DECIMAL(p, q): Represents a decimal number with:
'm' digits (including the sign).
'q' digits after the decimal point (assumed).
Constraints:
0≤q≤p≤m
p>0
'p', 'q', and 'm' must be integers.

INTEGER:
INTEGER is a numeric data type used for storing whole numbers (both
positive and negative).
Storage: 4 bytes
Range:
Signed: -2,147,483,648 to 2,147,483,647
Unsigned: 0 to 4,294,967,295

SMALLINT:
SMALLINT is a numeric data type used to store whole numbers (integers),
but it takes less storage than INT. It is used when you don’t need large
numbers, helping to save storage space in a database.
Storage: 2 bytes
Range:
Signed: -32,768 to 32,767
Unsigned: 0 to 65,535

DATE:
Description: Stores only the date in the format YYYY-MM-DD.
Storage: 3 bytes
Use Case: Storing birthdates, event dates.

DATETIME:
Description: Stores both date and time in the format YYYY-MM-DD
HH:MM:SS.
Storage: 8 bytes
Use Case: Storing timestamps for records, such as when a user registered.

TIMESTAMP:
Description: Similar to DATETIME, but it automatically updates to the
current timestamp when the row is modified.
Storage: 4 bytes
Use Case: Storing last updated times.

TIME:
Description: Stores time values in the format HH:MM:SS.
Storage: 3 bytes
Use Case: Storing durations, working hours.
YEAR:
Description: Stores only a year in YYYY format.
Storage: 1 byte
Use Case: Storing manufacturing years, admission years.

FLOAT:
Description: The FLOAT data type is used to store approximate decimal
values with floating-point precision. It is best used when exact precision is
not required, such as scientific calculations or large-scale measurements.
Storage: 4 bytes
Use Case: Storing measurements like temperature, height, or percentages.

Que 3) What are the different types of constraints that are used in oracle?
Explain any two constraints in details
Two constraints
1. NOT NULL Constraint
2. PRIMARY KEY Constraint
In Oracle, constraints are rules applied to table columns to maintain the
accuracy, integrity, and consistency of data. Constraints enforce specific
conditions to prevent invalid data entry, ensuring the database remains
structured and reliable.

1. NOT NULL Constraint


The NOT NULL constraint ensures that a column cannot contain NULL
values. It is used when a column must always have a value.
Characteristics of NOT NULL Constraint:
Ensures mandatory data entry.
Applied to a single column.
Improves data integrity by preventing missing values.
Cannot be applied to multiple columns at once.
Example:
CREATE TABLE Students (
student_id NUMBER PRIMARY KEY,
name VARCHAR2(50) NOT NULL,
age NUMBER
);
In this example, the name column has a NOT NULL constraint, which means
every student must have a name, and NULL values are not allowed.

Benefits of NOT NULL Constraint:


Prevents incomplete data entry.
Ensures consistency by avoiding NULL values where data is required.
Helps maintain data accuracy.

Use Cases of NOT NULL Constraint:


Ensuring that essential attributes like email, phone number, or customer ID
are always present in a table.
Preventing NULL values in important columns of banking, healthcare, and
financial databases.
2. PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table. It
combines the functionalities of the NOT NULL and UNIQUE constraints.

Characteristics of PRIMARY KEY Constraint:


Ensures each record is uniquely identified.
A table can have only one primary key.
The primary key column cannot contain NULL values.
Can be a single-column or composite key (multiple columns).

Example:
CREATE TABLE Employees (
emp_id NUMBER PRIMARY KEY,
emp_name VARCHAR2(100) NOT NULL,
salary NUMBER
);
In this example, the emp_id column is the primary key, meaning each
employee must have a unique emp_id, and NULL values are not allowed.

Benefits of PRIMARY KEY Constraint:


Guarantees that no duplicate records exist.
Ensures each row has a unique identifier.
Improves search performance by indexing the primary key column.

Use Cases of PRIMARY KEY Constraint:


Assigning a unique identifier to each product in an inventory system.
Ensuring that each customer in a banking database has a unique customer
ID.
Maintaining a unique order ID for each transaction in an e-commerce
application.

3. UNIQUE Constraint
The UNIQUE constraint ensures that all values in a column are distinct.
Unlike the PRIMARY KEY, a UNIQUE constraint allows NULL values, but all
non-NULL values must be unique.

Characteristics of UNIQUE Constraint:


Ensures column values are unique.
Allows NULL values unless specified with NOT NULL.
Can be applied to multiple columns in a table.
Example:
CREATE TABLE Customers (
customer_id NUMBER PRIMARY KEY,
email VARCHAR2(100) UNIQUE
);
In this example, the email column must contain unique values, ensuring
that no two customers have the same email.
4. FOREIGN KEY Constraint
The FOREIGN KEY constraint establishes a relationship between two
tables. It ensures referential integrity by requiring values in the foreign
key column to match values in the referenced primary key column.

Characteristics of FOREIGN KEY Constraint:


Maintains referential integrity between tables.
Prevents deletion of referenced records unless specified with ON DELETE
CASCADE.
Can reference a primary key or unique key in another table.
Example:
CREATE TABLE Orders (
order_id NUMBER PRIMARY KEY,
customer_id NUMBER,
FOREIGN KEY (customer_id) REFERENCES Customers(customer_id)
);

5. CHECK Constraint
The CHECK constraint ensures that values in a column meet a specific
condition.

Characteristics of CHECK Constraint:


Allows enforcing custom business rules.
Can be applied to single or multiple columns.
Cannot reference columns from other tables.
Example:
CREATE TABLE Products (
product_id NUMBER PRIMARY KEY,
price NUMBER CHECK (price > 0)
);

6. DEFAULT Constraint
The DEFAULT constraint assigns a default value to a column when no value
is specified.

Characteristics of DEFAULT Constraint:


Provides a default value for a column.
Does not enforce uniqueness or integrity.
Example:
CREATE TABLE Orders (
order_id NUMBER PRIMARY KEY,
order_date DATE DEFAULT SYSDATE
);
UNIT 2:

Que 1) What is view? What are the uses of view? Write syntax to update and
delete view.

1. Introduction to Views
A view in SQL is a virtual table that represents the result of a stored
query. Unlike a table, a view does not store data permanently but
dynamically fetches data from one or more underlying tables whenever it
is accessed. Views are commonly used to simplify complex queries, enhance
security, and ensure data consistency.

1. Characteristics of Views
A view is a virtual table, meaning it does not store data but retrieves it
dynamically from base tables.
It can be used like a regular table in SELECT statements.
It simplifies query execution by hiding complex joins and aggregations.
Views can restrict access to sensitive data by displaying only selected
columns or rows.
Some views allow updates, but modifications must meet certain conditions

2. Uses of Views in SQL


Views are widely used in database systems for various reasons, including:
1 Data Abstraction
Views provide an abstraction layer that simplifies user interaction with
complex database schemas. For example, instead of writing a lengthy JOIN
query every time, a user can refer to a predefined view.

2 Security and Access Control


By restricting access to certain columns or rows, views enhance security.
For example, an HR department may have a view displaying only employee
names and salaries without exposing sensitive details like Social Security
Numbers (SSNs).

3 Simplification of Complex Queries


When working with multiple tables, views help reduce the complexity of SQL
queries by encapsulating frequently used joins, filters, and aggregations.

4 Data Consistency and Reusability


Using views ensures that users always access consistent and updated
data, improving maintainability and reducing redundancy.

Creating a View in SQL

CREATE VIEW view_name AS


SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE VIEW HighSalaryEmployees AS
SELECT emp_id, emp_name, salary
FROM Employees
WHERE salary > 50000;

Updating a View
If you need to modify an existing view, use the CREATE OR REPLACE VIEW
statement:
CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
CREATE OR REPLACE VIEW HighSalaryEmployees AS
SELECT emp_id, emp_name, salary
FROM Employees
WHERE salary > 60000;

Deleting a View
To remove a view, use the DROP VIEW statement:

DROP VIEW view_name;


Example:
DROP VIEW HighSalaryEmployees;

Advantages of Views
Enhanced Security
Views restrict user access to specific columns and rows, helping enforce
data privacy.

Query Optimization
By encapsulating complex queries, views improve query efficiency and
reduce redundancy.

Data Independence
Users can access consistent data through views, even if the underlying
database structure changes.

Simplified Data Management


Views facilitate better data organization and abstraction, making database
interaction more intuitive.
Que 2) Explain the different iterative statements used in PL/SQL
In PL/SQL, iterative statements (also known as loops) are used to execute
a block of code repeatedly based on a condition. PL/SQL supports the
following types of loops:

1. Basic LOOP
The LOOP statement repeatedly executes a block of code until explicitly
exited using the EXIT or EXIT WHEN statement.
It does not have an automatic termination condition; you must explicitly
exit the loop.

LOOP
-- Statements
EXIT WHEN condition;
END LOOP;

Example
DECLARE
counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5; -- Exit when counter exceeds 5
END LOOP;
END;

2. WHILE LOOP
The WHILE loop executes as long as the given condition evaluates to TRUE.
The condition is checked before executing the loop body.

WHILE condition LOOP


-- Statements
END LOOP;

Example
DECLARE
counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
END LOOP;
END;
3. FOR LOOP
The FOR loop executes a block of statements for a fixed number of
iterations.
It uses an implicit counter that automatically increments/decrements.
Syntax
FOR counter_variable IN start_value .. end_value LOOP
-- Statements
END LOOP;

Example
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END

4. Cursor FOR LOOP


This loop is used to iterate through records returned by a cursor without
explicitly declaring it.
It automatically opens, fetches, and closes the cursor.

Syntax
FOR record_variable IN (SELECT column_name FROM table_name) LOOP
-- Statements
END LOOP;

Example
BEGIN
FOR emp_rec IN (SELECT emp_name FROM employees) LOOP
DBMS_OUTPUT.PUT_LINE('Employee: ' || emp_rec.emp_name);
END LOOP;
END;

5. NESTED LOOPS
PL/SQL supports nested loops, meaning you can place a loop inside another
loop.
Example:
BEGIN
FOR i IN 1..3 LOOP
FOR j IN 1..2 LOOP
DBMS_OUTPUT.PUT_LINE('i=' || i || ', j=' || j);
END LOOP;
END LOOP;
END;
EXIT and CONTINUE Statements
EXIT – Terminates the loop immediately.
EXIT WHEN condition – Exits when a condition is met.
CONTINUE – Skips the remaining statements in the loop and starts the
next iteration.
CONTINUE WHEN condition – Skips the remaining statements only if the
condition is met.

Example Using CONTINUE:

BEGIN
FOR i IN 1..5 LOOP
IF i = 3 THEN
CONTINUE; -- Skips the iteration when i = 3
END IF;
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END;

Que 3 List and explain all the sections of PL/SQL block


A PL/SQL block is a fundamental structure in Oracle's Procedural
Language/Structured Query Language (PL/SQL). It consists of four
sections:

1. Declaration Section (Optional)


Starts with the keyword DECLARE.
Used to declare variables, constants, cursors, exceptions, etc.
This section is optional but useful for storing values and handling
exceptions.
Example:
DECLARE
emp_name VARCHAR2(50);
emp_salary NUMBER;
BEGIN
emp_name := 'Rahul';
emp_salary := 50000;
END;

2. Execution Section (Mandatory)


Starts with the keyword BEGIN.
Contains SQL statements like INSERT, UPDATE, DELETE, SELECT INTO, and
procedural statements like loops, conditions, etc.
It is mandatory and executes the logic of the program.
Example:
BEGIN
emp_name := 'Rahul';
emp_salary := emp_salary + 5000;
END;

3. Exception Handling Section (Optional)


Starts with the keyword EXCEPTION.
Used to handle errors and exceptions gracefully.
If an error occurs, it prevents the program from crashing by handling it
properly.

Example:
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No record found!');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Some other error occurred.');

4. End Section
The END keyword is used to mark the end of the PL/SQL block.
It does not have a separate keyword but is necessary for closing the block.

Complete PL/SQL Block Example:


DECLARE
emp_name VARCHAR2(50);
emp_salary NUMBER := 50000;
BEGIN
emp_name := 'Rahul';
emp_salary := emp_salary + 5000;
DBMS_OUTPUT.PUT_LINE('Updated Salary: ' || emp_salary);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occurred.');
END;

Unit 3
Que 1) What is cursor ? Explain attributes of Explicit cursor
A cursor in PL/SQL is a pointer to a result set of a SQL query. It allows
row-by-row processing of query results. There are two types of cursors in
PL/SQL:

Types of Cursor:
1 Implicit Cursor – Automatically created by Oracle for single-row queries
(e.g., SELECT INTO).
2 Explicit Cursor – Defined explicitly by the programmer for multi-row
queries.
Attributes of Explicit Cursor in PL/SQL
Explicit cursors in PL/SQL have four important attributes:

%FOUND
Returns TRUE if a row is fetched successfully.
Returns FALSE if no row is fetched.
Example:
IF cursor_name%FOUND THEN
DBMS_OUTPUT.PUT_LINE('Row fetched successfully.');
END IF;

%NOTFOUND
Returns TRUE if no row is fetched.
Returns FALSE if a row is fetched.
Example:
IF cursor_name%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('No more rows left to fetch.');
END IF;

%ISOPEN
Returns TRUE if the cursor is open.
Returns FALSE if the cursor is closed.
Example
IF cursor_name%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is still open.');
END IF;

%ROWCOUNT
Returns the number of rows fetched so far.
Example:
DBMS_OUTPUT.PUT_LINE('Rows fetched: ' || cursor_name%ROWCOUNT);

DECLARE
CURSOR emp_cursor IS SELECT emp_id, emp_name FROM employees;
emp_record employees%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
EXIT WHEN emp_cursor%NOTFOUND; -- Exit loop when no more rows
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_record.emp_id || ',
Name: ' || emp_record.emp_name);
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total Rows Fetched: ' ||
emp_cursor%ROWCOUNT);
CLOSE emp_cursor;
END;
Que 2) Write a procedure to find the minimum of three numbers in PL/SQL

CREATE OR REPLACE PROCEDURE FIND_MINIMUM(


num1 IN NUMBER,
num2 IN NUMBER,
num3 IN NUMBER
)
IS
min_value NUMBER;
BEGIN
-- Find the minimum using LEAST function
min_value := LEAST(num1, num2, num3);
-- Display the minimum value
DBMS_OUTPUT.PUT_LINE('The minimum value is: ' || min_value);
END FIND_MINIMUM;
/

How to Execute:
SET SERVEROUTPUT ON;
BEGIN
FIND_MINIMUM(10, 5, 8);
END;
/
Output:
The minimum value is: 5

Que 3) How will you create,call and remove a stored procedure ?Exaplin in PL/SQL
In PL/SQL, a stored procedure is a named block of PL/SQL code that
performs a specific task and can be called multiple times. Below is a
detailed explanation of how to create, call, and remove a stored procedure
in PL/SQL.

1. Creating a Stored Procedure


Creating a stored procedure to insert a record into the employees table
CREATE OR REPLACE PROCEDURE add_employee (
emp_id NUMBER,
emp_name VARCHAR2,
emp_salary NUMBER
)
IS
BEGIN
INSERT INTO employees (id, name, salary)
VALUES (emp_id, emp_name, emp_salary);
COMMIT; -- Commit the transaction
END add_employee;
/
2. Calling a Stored Procedure
A stored procedure can be called using the EXEC command or inside an
anonymous PL/SQL block using CALL or BEGIN ... END;.
Method 1: Using EXECUTE

EXEC add_employee(101, 'Rahul', 50000);

3. Removing a Stored Procedure


A stored procedure can be deleted using the DROP PROCEDURE statement.

DROP PROCEDURE add_employee;

Unit 4

Que 1) What are triggers? Explain BEFORE and AFTER trigger in PL/SQL

Triggers in PL/SQL
A trigger is a special type of stored procedure in PL/SQL that is
automatically executed (fired) when a specific event occurs in the
database. Triggers are commonly used to enforce business rules, maintain
data integrity, and perform auditing tasks.

Types of Triggers in PL/SQL


Triggers can be classified based on:
Timing:
BEFORE Trigger: Executes before the triggering event occurs.
AFTER Trigger: Executes after the triggering event occurs.
Event Type:
INSERT Trigger: Fires when a row is inserted into a table.
UPDATE Trigger: Fires when a row is updated.
DELETE Trigger: Fires when a row is deleted.

BEFORE Trigger in PL/SQL


A BEFORE trigger is executed before the actual database operation
(INSERT, UPDATE, DELETE) takes place.
It is generally used for validation or modifying data before it is committed
to the table.

Example: BEFORE INSERT Trigger


CREATE OR REPLACE TRIGGER before_insert_employee
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 5000 THEN
:NEW.salary := 5000;
END IF;
END;
/
Explanation:
This trigger fires before an INSERT operation on the employees table.
If the inserted salary is less than 5000, it automatically sets it to 5000.

AFTER Trigger in PL/SQL


An AFTER trigger is executed after the database operation (INSERT)
UPDATE, DELETE) has been completed.
It is useful for logging, auditing, or sending notifications.

Example: AFTER INSERT Trigger

CREATE OR REPLACE TRIGGER after_insert_employee


AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (emp_id, action, action_time)
VALUES (:NEW.emp_id, 'INSERT', SYSTIMESTAMP);
END;
/

Explanation:
This trigger fires after an INSERT operation on the employees table.
It logs the insertion event in an employee_audit table with a timestamp.
Que 2) What is function?write a function to find factorial of given number in PL/
SQL
What is a Function?
A function in PL/SQL is a named PL/SQL block that returns a single value.
Functions are used to perform calculations and return a result. They help
in code reusability and modularity.

PL/SQL Function to Find Factorial of a Given Number

DECLARE
num NUMBER := 5;
fact NUMBER;
FUNCTION factorial(n IN NUMBER) RETURN NUMBER
IS
result NUMBER := 1;
BEGIN
IF n < 0 THEN
RETURN NULL;
END IF;
FOR i IN 1..n LOOP
result := result * i;
END LOOP;
RETURN result;
END factorial;
BEGIN
fact := factorial(num);
DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is: ' || fact);
END;
/

What is function?State syntax and purpose of a)Creating function


adndropping function in PL/SQL
What is a Function in PL/SQL?
A function in PL/SQL is a named PL/SQL block that performs a specific
task and returns a single value. Functions are mainly used to encapsulate
reusable logic and computations in a structured way.

Syntax for Creating a Function in PL/SQL


To create a function, you use the CREATE FUNCTION statement.
Syntax:
CREATE OR REPLACE FUNCTION function_name
(param1 datatype, param2 datatype, ...)
RETURN return_datatype
IS
BEGIN
RETURN value;
EXCEPTION
END function_name;
Purpose of Creating a Function:
Reusability: Avoid redundant code by defining logic once and reusing it.
Modularity: Improves code organization and readability.
Performance: Optimizes execution by reducing repetitive computations.

Example:
CREATE OR REPLACE FUNCTION get_salary(emp_id NUMBER)
RETURN NUMBER
IS
emp_salary NUMBER;
BEGIN
SELECT salary INTO emp_salary FROM employees WHERE employee_id =
emp_id;
RETURN emp_salary;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 0;
END get_salary;

DROP FUNCTION get_salary;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy