Dbms
Dbms
Module 2
Slide 1-2
What is SQL?
• Structured Query Language, is a powerful language used for managing and manipulating
relational databases.
• It provides a standardized way to interact with databases, making it an essential tool for anyone
working with data.
• SQL commands are like instructions to a table.
• SQL can perform various tasks like creating a table, adding data to tables, dropping the table,
modifying the table, set permission for users.
Slide 1-3
• These SQL commands are mainly categorized into five categories:
4
Data Definition Language (DDL) Commands
• DDL, which stands for Data Definition Language, is a subset of SQL(Structured Query
• These commands are used to create, alter, and delete database objects like tables, indexes, and
schemas.
5
Data Definition Language (DDL) Commands
CREATE: This command is used to create a new database object. For example, creating a new table, a view, or a
database.
6
Data Definition Language (DDL) Commands
2. ALTER: This command is used to modify an existing database object, such as adding, deleting, or
7
Data Definition Language (DDL) Commands
3. DROP: This command is used to delete an existing database object like a table, a view, or other objects.
4. TRUNCATE: This command is used to delete all data from a table, but the structure of the table remains. It’s a fast
8
Data Manipulation Language (DML) Commands in SQL
• Data Manipulation Language (DML) is a subset of SQL commands used for adding
(inserting), deleting, and modifying (updating) data in a database.
• The primary DML commands in SQL include:
• INSERT: This command is used to add new rows (records) to a table.
• Syntax: INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1,
value2, value3, ...);
• UPDATE: This command is used to modify the existing records in a table.
• Syntax: UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE
condition;
• The WHERE clause specifies which records should be updated. Without it, all records in the
table will be updated.
• DELETE: This command is used to remove one or more rows from a table.
• Syntax: DELETE FROM table_name WHERE condition;
• Like with UPDATE, the WHERE clause specifies which rows should be deleted. Omitting the
WHERE clause will result in all rows being deleted. Slide 1-9
Data Manipulation Language (DML) Commands in SQL
• The SELECT statement is used to query and extract data from a table, which can
Slide 1-10
Data Control Language (DCL) Commands in SQL
Data Control Language (DCL) is a subset of SQL commands used to control access to data in a database.
GRANT: This command is used to give users access privileges to the database. These privileges
can include the ability to select, insert, update, delete, and so on, over database objects like tables
and views.
• For example, GRANT SELECT ON employees TO user123; gives user123 the permission to read data from
from a user.
• For example, REVOKE SELECT ON employees FROM user123; would remove user123‘s
Slide 1-12
Transaction Control Language (TCL) Commands in SQL
Transaction Control Language (TCL) is a subset of SQL commands used to manage transactions in a
database.
• Transactions are important for maintaining the integrity and consistency of data.
COMMIT: This command is used to permanently save all changes made in the current transaction.
• Syntax: COMMIT;
• When you issue a COMMIT command, the database system will ensure that all changes made during the current
Slide 1-13
Transaction Control Language (TCL) Commands in SQL
ROLLBACK: This command is used to undo changes that have been made in the
current transaction.
• Syntax: ROLLBACK;
• If you issue a ROLLBACK command, all changes made in the current transaction are
discarded, and the state of the data reverts to what it was at the beginning of the transaction.
Slide 1-14
Data Query Language (DQL) Commands in SQL
Data Query Language (DQL) is a subset of SQL commands used primarily to query and retrieve data from existing
database tables.
• In SQL, DQL is mostly centered around the SELECT statement, which is used to fetch data according to specified
criteria.
• Basic Syntax:
• WHERE Clause:
• Example:
JOIN Clauses:
• Used to combine rows from two or more tables based on a related column between them.
• Types include INNER JOIN, LEFT JOIN, RIGHT JOIN, FULL JOIN.
• Syntax:
Slide 1-16
Data Query Language (DQL) Commands in SQL
Slide 1-17
Data Query Language (DQL) Commands in SQL
JOIN / INNER JOIN
Slide 1-18
Data Query Language (DQL) Commands in SQL
LEFT JOIN
Slide 1-19
Data Query Language (DQL) Commands in SQL
LEFT JOIN RIGHT JOIN
Slide 1-20
Data Query Language (DQL) Commands in SQL
FULL JOIN
Slide 1-21
Data Query Language (DQL) Commands in SQL
GROUP BY Clause: Used with aggregate functions (like COUNT, MAX, MIN, SUM, AVG) to
group the result set by one or more columns.
Syntax:
Slide 1-22
Data Query Language (DQL) Commands in SQL
ORDER BY Clause: Used to sort the result set in ascending or descending order.
Syntax:
SELECT column1, column2 FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Slide 1-23
MySQL Data Types
• String,
• Numeric, and
Slide 1-24
String Data Types
• CHAR(size):
• A FIXED length string (can contain letters, numbers, and special characters).
• The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1
• VARCHAR(size):
• A VARIABLE length string (can contain letters, numbers, and special characters).
• The size parameter specifies the maximum string length in characters - can be from 0 to 65535.
Slide 1-25
Numeric Data Types
INT(size):
• A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is
from 0 to 4294967295.
FLOAT(size, d):
• A floating point number. The total number of digits is specified in size. The number of digits
after the decimal point is specified in the d parameter.
26
Date and Time Data Types
• DATE:
• Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31’.
• TIME(fsp):
• It is used to specify the time format. Its format is hh:mm:ss. Its supported range is
from '-838:59:59' to '838:59:59'
Slide 1-27
Constraints in SQL
• NOT NULL - Ensures that a column cannot have a NULL value
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
Slide 1-28
NOT NULL Constraint
• The NOT NULL constraint enforces a column to NOT accept NULL values.
• This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record
without adding a value to this field.
• Example:
Slide 1-29
PRIMARY KEY Constraint:
• The PRIMARY KEY constraint uniquely identifies each record in a table.
• Primary keys must contain UNIQUE values, and cannot contain NULL values.
• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL,
FirstName varchar(255), Age int, PRIMARY KEY (ID));
Slide 2-30
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.
• However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age
int, UNIQUE (ID));
Slide 1-31
FOREIGN KEY Constraint
• The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
• A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
• The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
• Example:
• CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY
KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));
Slide 2-32
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.
• If you define a CHECK constraint on a table it can limit the values in certain columns based on
values in other columns in the row.
• Example:
• CREATE TABLE Person (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int,
CHECK (Age>=18));
33
DEFAULT Constraint
• The default value will be added to all new records, if no other value is specified.
• Example:
• CREATE TABLE Persons (ID int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Age int,
City varchar(255) DEFAULT ‘Bangalore’);
• The DEFAULT constraint can also be used to insert system values, by using functions like GETDATE():
• Example:
• CREATE TABLE Orders (ID int NOT NULL, OrderNumber int NOT NULL, OrderDate date DEFAULT GETDATE());
34
SQL Operators:
SQL operators are categorized in the following categories:
1. SQL Arithmetic Operators
2. SQL Comparison Operators
3. SQL Logical Operator
4. SQL Set Operators
Slide 2-35
SQL Arithmetic Operators
• The Arithmetic Operators perform the mathematical operation on the numerical data of the SQL tables.
• These operators perform addition, subtraction, multiplication, and division operations on the numerical operands.
• Following are the various arithmetic operators performed on the SQL data:
• SQL Addition Operator (+)
36
SQL Addition Operator (+)
• Syntax of SQL Addition Operator:
SELECT operand1 + operand2;
• Example:
SELECT Emp_Salary + 20000 as Emp_New_Salary FROM Employee_details;
37
SQL Multiplication Operator (*)
• Syntax of SQL Multiplication Operator:
• Example:
• Example:
38
SQL Modulus Operator (%)
• Syntax of SQL Modulus Operator:
• Example:
39
SQL Comparison Operators
1.SQL Equal Operator (=)
40
SQL Equal Operator (=)
• The Equal Operator in SQL shows only data that matches the specified value in the query.
41
SQL Greater Than Operator (>)
• The Greater Than Operator in SQL shows only those data which are greater than the value of the right-hand
operand.
42
SQL Less Than Operator (<)
• The Less Than Operator in SQL shows only those data from the database tables which are less than the value of
the right-side operand.
43
SQL Logical Operators
1. SQL ALL operator
3. SQL OR operator
5. SQL IN operator
44
SQL ALL Operator
• The ALL operator in SQL compares the specified value to all the values of a column from the
sub-query in the SQL database.
1.SELECT,
2.HAVING, and
3.WHERE.
45
SQL ALL Operator
• Syntax of ALL operator:
SELECT column_Name1, ...., column_NameN FROM table_Name WHERE column
Comparison_operator ALL (SELECT column FROM tablename2)
• Example:
SELECT Emp_Id, Emp_Name FROM Employee_details WHERE Emp_Salary > ALL ( SELECT Emp
_Salary FROM Employee_details WHERE Emp_City = Jaipur)
• The outer query selects Emp_Id and Emp_Name from the table Employee_details.
• The WHERE clause filters the results based on a condition.
• The condition Emp_Salary > ALL (...) compares the salary of each employee with the salaries of all employees from Jaipur.
• The inner query (SELECT Emp_Salary FROM Employee_details WHERE Emp_City = 'Jaipur') retrieves the salaries of
employees from Jaipur.
• The ALL keyword ensures that the salary of the outer query's employee is greater than all salaries retrieved by the inner query
for employees from Jaipur.
46
• So, the query will return the Emp_Id and Emp_Name of employees whose salary is greater than all employees from Jaipur.
SQL AND Operator
• The AND operator in SQL would show the record from the database table if all the conditions separated by the
AND operator evaluated to True.
• It is also known as the conjunctive operator and is used with the WHERE clause.
• Example:
47
SQL OR Operator
• Syntax of OR operator:
Example:
48
SQL BETWEEN Operator
• The BETWEEN operator in SQL shows the record within the range mentioned in the SQL query. This operator
operates on the numbers, characters, and date/time operands.
• If there is no value in the given range, then this operator shows NULL value.
• Example:
49
SQL IN Operator
• The IN operator in SQL allows database users to specify two or more values in a WHERE clause.
• This logical operator minimizes the requirement of multiple OR conditions.
• This operator makes the query easier to learn and understand.
• This operator returns those rows whose values match with any value of the given list.
IN operator:
SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name WHERE column_name IN (list_of_
values);
• Example:
SELECT * FROM Employee_details WHERE Emp_Id IN (202, 204, 205);
NOT IN:
Example:
SELECT * FROM Employee_details WHERE Emp_Id NOT IN (202,205);
50
SQL NOT Operator
• The NOT operator in SQL shows the record from the table if the condition evaluates to false. It
is always used with the WHERE clause.
• Example:
51
SQL LIKE Operator
• The LIKE operator in SQL shows those records from the table which match with the given pattern specified in the
sub-query.
• The percentage (%) sign is a wildcard which is used in conjunction with this logical operator.
• This operator is used in the WHERE clause with the following three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement
• Syntax of LIKE operator:
SELECT column_Name1, column_Name2 ...., column_NameN FROM
table_Name WHERE column_name LIKE pattern;
• Example:
SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%’ ; (starts with)
SELECT * FROM Employee_details WHERE Emp_Name LIKE '%y’ ; (Ends with)
SELECT * FROM Employee_details WHERE Emp_Name LIKE 'S%y’; (Both)
52
SQL Set Operators
• The Set Operators in SQL combine a similar type of data from two or more
SQL database tables.
• It mixes the result, which is extracted from two or more SQL queries, into a
single result.
• Set operators combine more than one select statement in a single query and
return a specific result set.
53
SQL Set Operators
1.SQL Union Operator
54
SQL Union Operator
• The SQL Union Operator combines the result of two or more SELECT statements
and provides the single output.
• The data type and the number of columns must be the same for each SELECT
statement used with the UNION operator.
• This operator does not show the duplicate records in the output table.
55
SQL Union Operator
• Syntax of UNION Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
UNION
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:
SELECT Emp_ID, Emp_Name FROM Employee_details1 UNION
SELECT Emp_ID, Emp_Name FROM Employee_details2 ;
56
SQL Set Operators
Table: T1_STUDENT Table: T2_STUDENT
Favourite_Subj Favourite_S
ID Name Hometown Percentage ID Name Hometown Percentage
ect ubject
1 Soniya Jain Udaipur 89 Java
1 Soniya Jain Udaipur 89 Java
2 Harshada Sharma Kanpur 92 C Programming 2 Ishwari Dixit Delhi 86 Python
3 Anuja Rajput Jaipur 78 C++
3 Anuja Rajput Jaipur 78 C++
Operating
Machine 4 Pakhi Arora Surat 70
4 Pranali Singh Nashik 88 System
Learning
5 Renuka Deshmukh Panipat 90 Data Science 5 Renuka Deshmukh Panipat 90 Data Science
Cloud
6 Swati Kumari Faridabad 93 Computer
Computing 6 Jayshree Patel Pune 91
Networks
7 Prachi Jaiswal Gurugram 96 DBMS
7 Prachi Jaiswal Gurugram 96 DBMS
57
SQL Union ALL Operator
• The SQL Union Operator is the same as the UNION operator, but the only difference is that it also shows the
same record.
• Syntax of UNION ALL Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1 [WHERE conditions]
UNION ALL
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:
• If we want to see the employee name of each employee of both tables in a single output. For this, we have to
write the following query in SQL:
SELECT Emp_Name FROM Employee_details1 UNION ALL
SELECT Emp_Name FROM Employee_details2 ;
58
SQL Intersect Operator
• The SQL Intersect Operator shows the common record from two or more SELECT statements. The data type and the number of
columns must be the same for each SELECT statement used with the INTERSECT operator.
• Syntax of INTERSECT Set operator:
SELECT column1, column2 ...., columnN FROM table_Name1
[WHERE conditions]
INTERSECT
SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
• Example:
59
SQL Minus Operator
• The SQL Minus Operator combines the result of two or more SELECT statements and shows only the results from the first data
set.
• Syntax of MINUS operator:
SELECT column1, column2 ...., columnN FROM First_tablename [WHERE conditions]
MINUS
SELECT column1, column2 ...., columnN FROM Second_tablename [WHERE conditions];
• Suppose, we want to see the name of employees from the first result set after the combination of both tables
SELECT Emp_Name FROM Employee_details1
MINUS
SELECT Emp_Name FROM Employee_details2 ;
60
Types of SQL Aggregation Function
61
SQL Aggregate Functions
62
COUNT FUNCTION
• COUNT function is used to Count the number of rows in a database table.
• COUNT function uses the COUNT(*) that returns the count of all the rows in a
63
COUNT FUNCTION
• Syntax
COUNT(*)
or COUNT( [ALL|DISTINCT] expression )
• Example:
SELECT COUNT(*) FROM PRODUCT_MAST;
• COUNT with WHERE
SELECT COUNT(*) FROM PRODUCT_MAST WHERE RATE>=20;
• COUNT() with DISTINCT
SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST;
64
COUNT FUNCTION
• COUNT() with GROUP BY
Example:
SELECT COMPANY, COUNT(*) FROM
PRODUCT_MAST GROUP BY COMPANY;
COUNT() with HAVING
SELECT COMPANY, COUNT(*) FROM
PRODUCT_MAST GROUP BY COMPANY
HAVING COUNT(*)>2;
65
SUM Function
• Sum function is used to calculate the sum of all selected columns.
• It works on numeric fields only.
• Syntax
SUM() or
SUM( [ALL|DISTINCT] expression )
• Example: SUM()
SELECT SUM(COST) FROM PRODUCT_MAST;
66
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.
• Syntax
• Example:
67
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.
• Syntax
MAX() or
• Example:
68
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.
• Syntax
• Example:
69
Views in SQL
• Views in SQL are considered as a virtual table. A view also contains
rows and columns.
• To create the view, we can select the fields from one or more tables
present in the database.
• A view can either have specific rows based on certain condition or all
the rows of a table.
70
Advantages of View:
1. Complexity
2. Security
3. Consistency
4. Data Integrity
5. Storage Capacity
71
Disadvantages of View:
• The DML statements which can be performed on a view created using single base table have certain
restrictions are:
1.You cannot INSERT if the base table has any not null column that do not appear in view.
2.You cannot INSERT or UPDATE if any of the column referenced in the INSERT or UPDATE contains
group functions or columns defined by expression.
3.You can't execute INSERT, UPDATE, DELETE statements on a view, if with read only option is enabled.
72
Sample table:
Student_Detail
STU_ID NAME ADDRESS
1 Stephan Delhi
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
STU_ID NAME MARKS AGE
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
73
Creating view
• A view can be created using the CREATE VIEW statement.
• We can create a view from a single table or multiple tables.
• Syntax: STU_ID NAME ADDRESS
CREATE VIEW view_name AS 1 Stephan Delhi
SELECT column1, column2..... 2 Kathrin Noida
FROM table_name 3 David Ghaziabad
• Query:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
75
• In the given example, a view is created named MarksView from two tables Student_Detail and Student_Marks.
• Query:
CREATE VIEW MarksView AS
SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Student_Marks.MARKS
FROM Student_Detail, Student_Marks
WHERE Student_Detail.NAME = Student_Marks.NAME;
• SELECT * FROM MarksView;
76
View
• Deleting View
• A view can be deleted using the Drop View statement.
• Syntax
DROP VIEW view_name;
77
Types of Views:
78
Types of Views
1.Join View: A join view is a view that has more than one table or view in its from
clause and it does not use any Group by Clause, Distinct and set operation.
79
Types of Views
• Example
• Assume there are two tables: The first table is User_Address, which maps each user to a ZIP code; the second
table is User_Score, which records all the scores of each user. The question is, how to write a SQL query to find
the number of users who scored higher than 200 for each ZIP code?
• Without using an inline view, we can accomplish this in two steps:
80
Trigger in SQL
• A Trigger in Structured Query Language is a set of procedural statements which
are executed automatically when there is any response to certain events on the
particular table in the database.
• In SQL, this concept is the same as the trigger in real life. For example, when we
pull the gun trigger, the bullet is fired.
81
Triggers
• In Structured Query Language, triggers are called only either before or after
the below events:
1.INSERT Event: This event is called when the new row is entered in the table.
2.UPDATE Event: This event is called when the existing record is changed or
modified in the table.
3.DELETE Event: This event is called when the existing record is removed from the
table.
82
Types of Triggers in SQL
• Following are the six types of triggers in SQL:
1.AFTER INSERT Trigger
This trigger is invoked after the insertion of data in the table.
2.AFTER UPDATE Trigger
This trigger is invoked in SQL after the modification of the data in the table.
3.AFTER DELETE Trigger
This trigger is invoked after deleting the data from the table.
4.BEFORE INSERT Trigger
This trigger is invoked before the inserting the record in the table.
5.BEFORE UPDATE Trigger
This trigger is invoked before the updating the record in the table.
6.BEFORE DELETE Trigger
This trigger is invoked before deleting the record from the table.
83
Syntax of Trigger in SQL
CREATE TRIGGER Trigger_Name
[ BEFORE | AFTER ]
ON [Table_Name]
AS
85
The following query shows the structure of theStudent_Trigger table:
DESC Student_Trigger;
86
• The following query fires a trigger before the insertion of the student record in the
table:
87
• The following query inserts the record into Student_Trigger table:
INSERT INTO Student_Trigger (Student_RollNo,
Student_FirstName, Student_EnglishMarks,
Student_PhysicsMarks, Student_ChemistryMarks,
Student_MathsMarks, Student_TotalMarks,
Student_Percentage) VALUES
( 201, Sorya, 88, 75, 69, 92, 0, 0);
• To check the output of the above INSERT statement,
SELECT * FROM Student_Trigger;
88
OUTPUT
Student_RollNo Student_FirstNa Student_English Student_Physics Student_chemistr Student_MathsM Student_TotalMar Student_Percenta
me Marks Marks yMarks arks ks ge
89
Advantages of Triggers in SQL
• Following are the three main advantages of triggers in Structured Query
Language:
1.SQL provides an alternate way for maintaining the data and referential integrity
in the tables.
2.Triggers helps in executing the scheduled tasks because they are called
automatically.
3.They allow the database users to validate values before inserting and updating.
90
Disadvantages of Triggers in SQL
91
PL/SQL Procedure
• The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.
• 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.
92
How to pass parameters in procedure
• When you want to create a procedure or function, you have to define parameters.
There are three ways to pass parameters in procedure:
94
Create procedure example
• 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 int(10) primary key, name varchar(100));
Now write the procedure code to insert record in user table.
• Procedure Code:
create or replace procedure "INSERTUSER"
(id IN NUMBER, name IN VARCHAR2) is
begin insert into user values(id,name);
end;
95
PL/SQL program to call procedure
• Let's see the code to call above created procedure.
BEGIN
insertuser(101,'Rahul');
dbms_output.put_line('record inserted successfully’);
END;
• Now, see the "USER" table, you will see one record is inserted.
ID NAME
101 Rahul
96
PL/SQL Drop Procedure
• Syntax for drop procedure
97
Advantages
• Using Procedures result in performance improvement of the application.
• Reduce the traffic between the database and the application.
• Code reusability
Disadvantages
• Stored procedures can cause a lot of memory usage.
• MySQL does not provide the functionality of debugging the stored procedures.
98
PL/SQL Function
• The PL/SQL Function is very similar to PL/SQL Procedure.
• The main difference is, a function must always return a value, and on the
other hand a procedure may or may not return a value.
• Except this, all the other things of PL/SQL procedure are true for PL/SQL
function too.
99
Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name [parameters]
100
PL/SQL Function
• Function_name: specifies the name of the function.
• [OR REPLACE] option allows modifying an existing function.
• The optional parameter list contains name, mode and types of the parameters.
• IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
• Function_body contains the executable part.
• The AS keyword is used instead of the IS keyword for creating a standalone function.
101
PL/SQL Function Example
create or replace function adder(n1 in number, n2 in number)
return number
is
n3 number(8);
begin
n3 :=n1+n2;
return n3;
end;
102
PL/SQL Function Example
• Now write another program to call the function.
DECLARE
n3 number(2);
BEGIN
n3 := adder(11,22);
dbms_output.put_line('Addition is: ' || n3);
END;
103
PL/SQL
DECLARE
Function Example
a number; Consider an example to demonstrate Declaring, Defining and Invoking a simple
b number; PL/SQL function which will compute and return the maximum of two values.
c number;
FUNCTION findMax(x IN number, y IN number)
104
PL/SQL Drop Function
Syntax for removing your created function:
105
106