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

Advanced Database Lab part About Function

SQL functions are reusable sub-programs in SQL that facilitate data processing and manipulation, categorized into built-in and user-defined functions. Built-in functions include aggregate and scalar functions, while user-defined functions allow for custom operations. The document also outlines the syntax for creating and calling functions, alongside examples of their application in SQL queries.

Uploaded by

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

Advanced Database Lab part About Function

SQL functions are reusable sub-programs in SQL that facilitate data processing and manipulation, categorized into built-in and user-defined functions. Built-in functions include aggregate and scalar functions, while user-defined functions allow for custom operations. The document also outlines the syntax for creating and calling functions, alongside examples of their application in SQL queries.

Uploaded by

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

SQL Functions

SQL Functions
SQL functions are simply sub-programs, which are commonly used and re-
used throughout SQL database applications for processing or manipulating
data. All SQL database systems have DDL (data definition language) and
DML (data manipulation language) tools to support the creation and
maintenance of databases.

.
SQL Functions
DDL is responsible for tasks related to database creation, modification, and
maintenance, while DML is responsible for tasks related to the manipulation
of data, which essentially means DML is the programming interface of the
database. The DML, like other programming languages, consists of
instructions which are used to process or compute data within the database.

The DML also supports functions, and these are referred to as SQL
functions. SQL functions are small programs that may have zero or more
input parameters but can return only one value
Why we need Function In SQL
There are many advantages of using functions.
 A function needs to be written only once and can be reused multiple
times. This saves time and effort and supports modular programming.
 Functions improve performance and efficiency of the database. SQL
functions are compiled and cached before use.
 Complex programming logic can be decomposed into a number of
smaller and simpler functions, thus making it easier to understand and
maintain.
Classification of SQL Function
There are many ways to classify SQL functions.
 built-in functions and : The built-in functions are standard functions
which are already provided by the SQL database system
 user-defined functions: user-defined functions are functions which are
created by the user for a specific purpose.
Built-in functions
SQL provides many built-in functions to perform operations on data. These
functions are useful while performing mathematical calculations, string
concatenations, sub-strings etc
SQL built-in functions are divided into two categories,
 Aggregate Functions
 Scalar Functions
Aggregate Functions
SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a
column.
Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
The scalar functions
The scalar functions act on the input values and can return
text, numeric, or time and date values.
Examples:
Trim()
Concat()
Current_Time()
Current_Date()
Len()
Some SQL Function Examples
Examples
We'll be using the table named 'EmpSalary' shown here for all the examples discussed.
Example : use of len()
SELECT employeeNo, FirstName, len(FirstName) as FirstNameLength FROM EmpSalary;
Example 2 Concat and trim
SELECT employeeNo, concat(trim(LastName),', ',trim(FirstName)) as fullName,
len(concat(trim(LastName),', ',trim(FirstName))) as lengthOfFullName from EmpSalary;

In this SQL statement, there are three built-in functions used: concat, trim, and len. The
output after execution is as shown in the diagram here.
Cont.
The key point to note here is that every function acts on each row of data, and
a function can contain another function.
 The trim function removes trailing blanks from any field.
 The concat function then concatenates the firstName and lastName fields,
inserting a comma in between to produce the complete name.
 The len function gives the length of the full name, including the comma
and blank space in between firstName and lastName.
Cont.
Now, let's take an example of aggregate functions. As the name
suggests, aggregate functions acts on an aggregate or group of records
in the table.
SELECT department, count(department) as noEmployees, sum(salary)
as totalDeptSal, avg(salary) as avgDeptSal from empSalary group by
department;

What will be the output?


User Defined Functions
SQL Server Functions are useful objects
. in SQL Server databases. A SQL
Server function is a code snippet that can be executed on a SQL Server
 A function must have a name and a function name can never start with
a special character such as @, $, #, and so on.
 Functions only work with select statements.
 Functions can be used anywhere in SQL, like AVG, COUNT, SUM,
MIN, DATE and so on with select statements.
 Functions compile every time.
 Functions must return a value or result.
 Try and catch statements are not used in functions.
Syntax of User Defined
Functions in SQL
CREATE FUNCTION function_name (parameter_list)
RETURNS data_type
AS
BEGIN
statements
RETURN value
END
Return_Type: Data Type: Please specify the data type of return value. For example,
VARCHAR, INT, FLOAT, etc.
Syntax of User Defined
Functions in SQL
Function_Name: You can specify any name you wish to give other than the system
reserved keywords. Please try to use meaningful names so that you can identify them
easily.
@Parameter_Name: Every function accepts zero or more parameters; it completely
depends upon the user requirements. While declaring the parameters don’t forget the
appropriate data type. For example (@name VARCHAR(50), @number INT)
Function Body: Any query, or any complex mathematical calculations you want to
implement in this particular function.
Create SQL Function with No
parameters example
From the below query, you can observe that we are summing the Yearly Income of the
MyEmployee table.

SQL User Defined Functions - SQL Scalar Function example


--

CREATE FUNCTION NoParameters ()


RETURNS INT
AS
BEGIN
RETURN (SELECT SUM(Salary) FROM EmpSalary)
END
How To Call
Syntax to call sql function:
SELECT dbo.<FunctionName>

SELECT dbo.NoParameters()
Create SQL Function with parameters
example
Example1: Create a Function in SQL Server which will return the cube of a given value.

CREATE FUNCTION cube(@X INT)


To execute the above function c
RETURNS INT
like
AS
below
BEGIN
SELECT dbo.cube(5)
RETURN @X * @X *@X

END
Other examples
Create function Fun_EmployeeInformation()
returns table
as
return(select * from Employee )
Examples: User Defined Functions
create database exercise
use exercise

create table Student


(
fname varchar(20),
studID int primary key,
sex char(6)
)
Examples: User Defined Functions
create table Stud_Grade
(
studID int ,
courseNo int,
CourseTitle varchar(20),
CrHr int,
Grade char,
constraint pk_stud_Grade primary key(studID,courseNo),
constraint fk_stud_Grade foreign key(studID) references student(studID)
)
Examples: User Defined Functions
Question1. create a function that convert letter grades to
numbers?
First insert 10 row of data for each table
Solution Q1
--This function will convert letter grade to number
go
create function NumberGrade(@grade char)
returns int
Solution Q1
as
begin
declare @numgrade int
if @grade='A'
set @numgrade= 4
else if @grade='B'
set @numgrade= 3
else if @grade='C'
set @numgrade= 2
else if @grade='D'
set @numgrade= 1
else
set @numgrade= 0
return @numgrade
end
go
How to call a function
Call A function that changes letter grade C to number grade

select dbo.NumberGrade('C')
Question2: define the function that calculates GPA
Use previously created function(numbergrade)
go
create function fn_GPA(@studID int)
returns float
as
begin
declare @TotalWeight float
declare @crHrs_sum float
declare @GPA float
Question2: define the function that calculates GPA

select @TotalWeight=(select
sum(dbo.numberGrade(stud_Grade.Grade )* CrHr) from stud_Grade
where studID=@studID)
select @crHrs_sum=(select SUM(crHr) from stud_Grade where studID
=@studID)
set @GPA=@TotalWeight/@crHrs_sum
return @GPA
end
go
Question2: Write one single function calculates GPA

go
create function GPA(@studID int)
returns float
as
begin
Question2: Write one single function calculates GPA
declare @TotalWeight float
declare @crHrs_sum float
declare @GPA float
select @TotalWeight =(select SUM((case Grade
when 'A' then 4*stud_Grade.CrHr
when 'B' then 3*stud_Grade.CrHr
when 'C' then 2*stud_Grade.CrHr
when 'D' then 1*stud_Grade.CrHr
when 'F' then 0 end ))
Question2: Write one single function calculates GPA
from stud_Grade where stud_Grade.studID =@studID)
select @crHrs_sum=(select SUM(stud_Grade.CrHr) from stud_Grade
where studID=@studID)
set @GPA=@TotalWeight/@crHrs_sum
return @GPA
end
go

Example: For the student with id 2 grade will be


select dbo.fn_GPA(2)
Question3: Write one single function calculates max of 2 numbers
go
create function fn_max(@num1 int, @num2 int)
returns int
begin
declare @max int
if (@num1>@num2)
set @max=@num1
else
set @max=@num2
return @max
end
go
Exercise:
1.Write SQL Function that calculates average of 4 numbers
2. Write SQL Function that calculates age given that Birth
Date of Student. First design student table with Birth Date
value. After that based on the value provided in student table
design a function.
About your project (20%)
1. Create database using name of your project(1 point)
2. By using the above database, create all tables with their possible attribute, data
type, relationship and use necessary constraints for each attributes.(4 points)
3. Apply all concepts what you have learnt from the advanced database concepts
 Database security (2 points)
 SQL Functions both user defined and built in functions (3 points)
 SQL transactions (3 points)
 SQL Stored Procedures (2 points)
 SQL triggers (3 points)
 Database backup (this is will be done by yourself)(2 points)

You might also like