Lesson 18 - SQL Server Inbuilt and User Defined
Functions
Functions in SQL Server are the database objects that
contains a set of SQL statements to perform a
specific task. A function accepts input parameters,
perform actions, and then return the result. We should
note that functions always return either a single value or a
table. The main purpose of functions is to replicate the
common task easily. We can build functions one time and
can use them in multiple locations based on our needs.
SQL Server does not allow to use of the functions for
inserting, deleting, or updating records in the database
tables.
The following are the rules for creating SQL Server
functions:
o A function must have a name, and the name cannot
begin with a special character such as @, $, #, or
other similar characters.
o SELECT statements are the only ones that operate
with functions.
o We can use a function anywhere such as AVG,
COUNT, SUM, MIN, DATE, and other functions with
the SELECT query in SQL.
o Whenever a function is called, it compiles.
o Functions must return a value or result.
o Functions use only input parameters.
o We cannot use TRY and CATCH statements in
functions.
Types of Functions
SQL Server categorizes the functions into two types:
o System Functions
o User-Defined Functions
Let us describe both types in detail.
Advertisement
1
System Functions
Functions that are defined by the system are known as
system functions. In other words, all the built-in
functions supported by the server are referred to as
System functions. The built-in functions save us time while
performing the specific task. These types of functions
usually work with the SQL SELECT statement to calculate
values and manipulate data.
Here is the list of some system functions used in
the SQL Server:
o String Functions (LEN, SUBSTRING, REPLACE,
CONCAT, TRIM)
o Date and Time Functions (datetime, datetime2,
smalldatetime)
o Aggregate Functions (COUNT, MAX, MIN, SUM, AVG)
o Mathematical Functions (ABS, POWER, PI, EXP, LOG)
o Ranking Functions (RANK, DENSE_RANK,
ROW_NUMBER, NTILE)
The following picture shows all the built-in database
functions used in the SQL Server:
2
SQL Server Functions
1. Cast Function: CAST()
The cast function converts a data type into another data
type.
Cast Function Example:
SELECTCast(10ASVARCHAR);
Output:
'10'
2. Coalesce Function: COALESCE()
The coalesce function returns the first non-null value from
a list of expressions.
3
Coalesce Function Example:
SELECTCOALESCE(NULL,'value2','value3');
Output:
'value2'
3. Is Null Function: ISNULL()
The is null function checks if an expression is null; if it is, it
returns a replacement value.
Is Null Function Example:
SELECTIsnull('value','null');
Output:
'value'
4. If Null Function: IFNULL()
The if null function is similar to the is null function, but the
arguments are reversed.
If Null Function Example:
SELECTIfnull('value','null');
Output:
'value'
5. NVL Function: NVL()
The NVL function replaces null values with a specified
default value.
NVL Function Example:
SELECTNvl(NULL,'default value');
Output:
4
'default value'
6. Case Expression: CASE
The case expression performs conditional operations
based on a specified expression.
Case Expression Example:
SELECTCASE
WHEN1=1THEN'true'
ELSE'false'
END;
Output:
'true'
7. Convert Function: CONVERT()
The convert function converts a value into a specified data
type.
Convert Function Example:
SELECTCONVERT(VARCHAR,10);
Output:
'10'
8. Split Function: STRING_SPLIT()
The split function splits a string into a table of substrings.
Split Function Example:
SELECT*
FROMString_split('apple,banana,cherry',',');
Output:
apple banana cherry
9. Random Function: RAND()
5
The random function generates a random number
between 0 and 1.
Random Function Example:
SELECTRand();
Output:
0.7750247322012854
10. If Function: IF()
The if function performs a conditional operation based on
a specified expression.
If Function Example:
SELECTIF(1=1,'true','false');
Output:
'True'
11. Mid Function: MID()
The mid function extracts a substring from a string,
starting at a specified position and with a specified length.
Mid Function Example:
SELECTMid('apple',2,3);
Output:
'ppl'
SQL Date Functions
12. Date Add Function: DATEADD()
The date add function adds a specified number of intervals
(such as days, months, or years) to a date.
Date Add Function Example:
6
SELECTDateadd(day,7,'2023-05-05');
Output:
'2023-05-12'
13. Date Format Function: DATE_FORMAT()
The date format function reformats a date value into a
string with a specified format.
Date Format Example:
SELECTDate_format('2023-05-05','%m/%d/%Y');
Output:
'05/05/2023'
14. Date Part Function: DATEPART()
The date part function extracts a specified part of a date,
such as year, month, or day.
Date Part Example:
SELECTDatepart(year,'2023-05-05');
Output:
2023
15. Day of the Week Function: DAYOFWEEK()
The day of the week function returns the day of the week
for a given date.
Day of the Week Example:
SELECTDayofweek('2023-05-05');
Output:
7
16. Week Function: WEEK()
The week function returns the week number for a given
date.
Week Function Example:
SELECTWeek('2023-05-05');
Output:
18
17. Weekday Function: WEEKDAY()
The weekday function returns the weekday index for a
given date.
Weekday Function Example:
SELECTWeekday('2023-05-05');
Output:
18. Year Function: YEAR()
The year function extracts the year from a date value.
Year Function Example:
SELECTYear('2023-05-05');
Output:
2023
SQL String Functions
19. Length Function: LEN()
The length function is used to return the length of a string.
Length Function Example:
8
SELECTLen('banana');
Output:
20. Left Function: LEFT()
The left function extracts a specified number of characters
from the beginning of a string.
Left Function Example:
SELECTLEFT('banana',3);
Output:
'ban'
21. Right Function: RIGHT()
The right function extracts a specified number of
characters from the end of a string.
Right Function Example:
SELECTRIGHT('banana',3);
Output:
'ana'
22. Trim Function: TRIM()
The trim function removes leading and trailing spaces
from a string.
Trim Function Example:
SELECTTrim(' banana ');
Output:
'banana'
9
23. Ascii Function: ASCII()
The ascii function returns the ASCII code value for a
specified character.
Ascii Function Example:
SELECTAscii('A');
Output:
65
24. Concatenate Function: CONCAT()
The concatenate function links two or more strings
together.
Concat Function Example:
SELECTConcat('apple','banana','cherry');
Output:
'applebananacherry'
25. Format Function: FORMAT()
The format function reformats a value into a specified
string format.
Format Function Example:
SELECTFormat(12345.6789,'#,##0.00');
Output:
12,345.68
26. Replace Function: REPLACE()
The replace function replaces a specified string with
another string in a given expression.
Replace Function Example:
10
SELECTReplace('banana','a','e');
Output:
Benene
27. Substring Function: SUBSTRING()
The SUBSTRING function extracts a substring from a given
string.
Substring Function Example:
SELECTSubstring('banana',2,3);
Output:
'man'
28. In String Function: INSTR()
The in string function finds the position of a specified
substring within a string.
In String Function Example:
SELECTInstr('banana','a');
Output:
29. Stuff Function: STUFF()
The stuff function replaces a substring within a string with
another substring.
Stuff Function Example:
SELECTStuff('banana',2,3,'oro');
Output:
'borona'
11
Looking for more SQL functions? Check out these
additional guides:
Aggregate SQL Functions
SQL Keywords, Operators, and Statements
SQL Math Functions
MySQL Functions
Using SQL Server Functions
SQL server functions are powerful tools that can make
data management and analysis more efficient and
effective. With a wide range of functions available, you
can easily manipulate and transform data to get the
insights you need. The examples and definitions we’ve
provided here should give you a good understanding of
some of the most commonly used SQL server functions
and inspire you to explore more advanced functions as
you become more comfortable with SQL.
SQL Math Functions
In the world of SQL, math functions play a significant role
in performing advanced calculations and analyzing
complex data. They can be a key component to your data
strategy that will help you better manipulate and manage
your company's data.
SQL Math Functions
The SQL functions below are based on the following table:
Database: Beverages
ID PRODUCT UNIT INVENTOR PRICE
# NAME Y
101 Water Pallet - 40 Cases 10 200
102 Lemonade Pallet - 40 Cases 5 400
103 Soda 3 Gallon Bag 8 94
104 Seltzer Pallet - 40 Cases 3 350
105 Milk Crate - 4 Gallons 2 12
1. Sum Function: SUM()
12
The sum function returns the total of all values in a
column.
Sum Function Example
SELECTSum(inventory)
FROMbeverages;
Output:
28
/*In this example, the sum function calculates the total of
all values in the “Inventory” column.
2. Average Function: AVG()
The average function returns the average of all values in a
column.
Average Function Example
SELECTAverage(inventory)
FROMbeverages;
Output:
5.6
/*In this example, the output is 5.6 because that’s the
average of all values in the “Inventory” column.
3. Round Function: ROUND()
The round function rounds a number to a specified
number of decimal places. In the following syntax, the first
number represents the number you want to round, while
the second represents the number of decimal places you
want to round to.
Round Function Example
SELECTRound(330.3333,1)
Output:
13
330.3
/*In this example, 330.3333 is rounded to the first decimal
point.
4. Truncate Function: TRUNCATE()
Like the round function, the truncate function also rounds
a number to the specified number of decimal places.
Truncate Function Example
SELECTTruncate(330.3333,1)
Output:
330.3
/*In this example, 330.3333 is rounded to the first decimal
point.
5. Max Function: MAX()
The max function returns the largest number or value in a
given column.
Max Function Example
SELECTMax(price)
FROMbeverages;
Output:
400
/* The output for this example is 400 because lemonade is
the highest price at 400$ per pallet.
6. Min Function: MIN()
The min function returns the smallest number or value in a
given column.
Min Function Example
14
SELECTMin(price)
FROMbeverages;
Output:
12
/* The output for this example is 12 because milk is the
lowest price at 12$ per crate.
7. Count Function: COUNT()
The count function returns the number of rows that match
the given criteria.
Count Function Example
SELECTCount(inventory)
FROMbeverages
Output:
/* The output for this example is five because that’s how
many rows there are for the “Inventory” column in the
“Beverages” table.
8. Power Function: POWER()
The power function takes the first specified number and
raises it to the power of the second number.
Power Function Example
SELECTPower(10,2);
Output:
100
/* In this example, 10 is raised to the power of 2, which
equals 100.
9. Log Function: LOG()
15
The log function returns the natural logarithmic value of a
given number. You can also specify the base by adding an
additional number, like in the example below.
Log Function Example
SELECTLog(5,2)
Output:
2.3219280948873622
/* In this example, we returned the logarithmic value of 5
to the base of 2.
10. Absolute Function: ABS()
The absolute function returns the absolute value of a
given number.
Absolute Function Example
SELECTAbs(-8)
Output:
/* This example calculates the absolute value of -8, which
is 8.
11. Square Root Function: SQRT()
The square root function calculates the square root of a
given number.
Square Root Function Example
SELECTSqrt(100);
Output:
10
16
/* This example calculates the square root of 100, which is
10.
12. Sine Function: SIN()
The sine function returns the sine of a given number.
Sine Function Example
SELECTSin(100);
Output:
-0.50636564110975879
/*This example returns the sine of 100
13. Cosine Function: COS()
The cosine function calculates the cosine of a given
number.
Cosine Function Example
SELECTCos(100);
Output:
0.86231887228768389
/*This example returns the cosine of 100
14. Modulo Function: MOD()
The modulo or mod function calculates the remainder of a
number divided by another number.
Modulo Function Example
SELECTMod(8,3);
Output:
17
/*For this example, the output would be 2 because 8
divided by 3 creates a remainder of 2.
15. Ceil Function: CEIL()
The ceil or ceiling function rounds a given number up to
the nearest integer.
Ceil Function Example
SELECTCeil(91.8);
Output:
92
/* This example rounds the number 91.8 to the nearest
integer, which is 92.
Note: The ceil function can be used with MySQL. For more
MySQL functions, click here.
By utilizing these functions in your SQL queries, you
can manipulate data quickly and accurately and perform
complex calculations that save valuable time and effort.
From basic addition and subtraction to more complex
operations like logarithms, we hope these math functions
provide a helpful starting point for anyone seeking to work
more efficiently with relational databases in SQL.
Aggregate SQL Functions
In the world of SQL, aggregate functions play a vital role in
summarizing large amounts of data and performing
powerful calculations. Whether you're new to SQL or
simply looking to refresh your knowledge, understanding
what aggregate functions are and how to use them can
vastly improve your data strategy and make your
everyday work easier.
What are Aggregate SQL Functions?
An aggregate function is an SQL function that returns a
single value calculated from a set of values. These values
18
are typically those in a column or group of columns
meeting certain conditions.
Before we dive into a slew of different aggregate
functions, let's look at a simple example.
Aggregate SQL Function Example
Let's say we have a table named `sales` with columns
`Product` and `Revenue`. If we wanted to calculate the
total revenue for each product, we could use the SUM
aggregate function, which looks like this:
SELECT product,
Sum(revenue) AS Total_Revenue
FROM sales
GROUP BY product;
This SQL statement will group the sales table by product
and then calculate the total revenue for each product
using the SUM aggregate function. The result will return a
table with two columns: `Product` and
`Total_Revenue`.
Now that we've covered this example, let's review a
comprehensive list of aggregate SQL functions.
Aggregate SQL Functions
The functions in this section will be based on the following
database:
Database: Fruits
ID# PRODUCT UNIT INVENTOR PRICE
NAME Y
1 Apple LB 50 0.75
19
2 Orange LB 75 0.60
3 Banana LB 100 0.35
4 Pineapple Unit 20 2.50
5 Watermelo Unit 15 5.00
n
1. Average Function: AVG()
The average function calculates the average value of a
specified column.
Average Function Example
SELECTAvg(price)ASAveragePrice
FROMfruits;
Output:
1.24
2. Count Function: COUNT()
This function counts the number of rows that match a
specified condition.
Count Function Example
SELECTCount(*)ASFruitsWithInventoryGreaterThan50
FROMfruits
WHEREinventory>=50;
Output:
20
3
3. Maximum Function: MAX()
The max function returns the maximum value in a
specified column.
Maximum Function Example
SELECTMax(price)ASMaximumPrice
FROMfruits;
Output:
4. Minimum Function: MIN()
The min function returns the minimum value in a specified
column.
Minimum Function Example
SELECTMin(inventory)ASMinimumInventory
FROMfruits;
Output:
15
5. Sum Function: SUM()
The Sum Function calculates the sum of a specified
column.
Sum Function Example
SELECTSum(inventory)ASTotalInventory
FROMfruits;
Output:
260
Note: For more math functions, check out our guide here.
21
6. Group Concatenates Function: GROUP_CONCAT()
This function links the values of a column into a single
string, separated by a specified delimiter.
Group Concatenates Function Example
SELECTGroup_concat(`product
name`SEPARATOR', ')ASFruits
FROMfruits;
Output:
Apple, Orange, Banana, Pineapple, Watermelon
7. Standard Deviation Function: STD()
This SQL function calculates the standard deviation of a
specified column.
Standard Deviation Function Example
SELECTStd(price)ASStandardDeviation
FROMfruits;
Output:
1.80052309609941
8. Variance Function: VAR()
The variance function calculates the variance of a
specified column.
Variance Function Example
SELECTVar(inventory)ASVariance
FROMfruits;
Output:
1616
9. Median Function: MEDIAN()
22
The median function calculates the median value of a
specified column.
Median Function Example
SELECTAvg(inventory)ASmedianinventory
FROM(
SELECTinventory
FROMfruits
ORDERBYinventorylimit2-
(
SELECTcount(*)
FROMfruits) % 2offset
(
SELECT(count(*)-1)/2
FROMfruits))subquery;
Output:
50
10. First Function: FIRST()
This function the first value in a specified column.
First Function Example
SELECTfirst_value(`productname`)OVER(ORDERBY`produc
tNAME`)ASfirstfruit
FROMfruits;
Output:
Apple
Using SQL Aggregate Functions
Aggregate SQL functions are essential for performing
calculations and summarizing data in a database. These
functions allow you to retrieve valuable insights from your
data by calculating averages, sums, counts, and more.
Whether you're analyzing sales data, tracking customer
behavior, or evaluating performance metrics, aggregate
23
functions help you make informed decisions and uncover
meaningful patterns in your data.
User-Defined Functions
Functions that are created by the user in the system
database or a user-defined database are known as user-
defined functions. The UDF functions accept parameters,
perform actions, and returns the result. These functions
help us to simplify our development by encapsulating
complex business logic and making it available for reuse
anywhere based on the needs. The user-defined functions
make the code needed to query data a lot easier to write.
They also improve query readability and functionality, as
well as allow other users to replicate the same procedures.
SQL Server categorizes the user-defined functions
mainly into two types:
1. Scalar Functions
2. Table-Valued Functions
Here are the descriptions of these UDF functions.
Scalar Functions
Scalar function in SQL Server always accepts
parameters, either single or multiple and returns a
single value. The scalar functions are useful in the
simplification of our code. Suppose we might have a
complex computation that appears in a number of queries.
In such a case, we can build a scalar function that
encapsulates the formula and uses it in each query
instead of in each query.
The following are the syntax illustrate the creation
of scalar function in SQL Server:
24
CREATE FUNCTION schema_name.function_name (para
meter_list)
RETURNS data_type AS
BEGIN
statements
RETURN value
END
The above syntax parameters are described below:
We will first define the function name after the CREATE
FUNCTION keywords. The name of the schema is
optional. If we will not define the schema name, SQL
Server uses default schema dbo. Next, we will define the
list of parameters enclosed in parenthesis. Third, we will
write the statements for the function and then, in
the RETURNS statement, define the data type of the
return value. Finally, we have added the RETURN
statement to return a value inside the function's body.
Example
This example will create a function to calculate the net
sales based on the quantity, price, and discount value:
. CREATE FUNCTION udfNet_Sales(
. @quantity INT,
. @price DEC(10,2),
. @discount DEC(3,2)
. )
. RETURNS DEC(10,2)
. AS
. BEGIN
. RETURN @quantity * @price * (1 - @discount);
. END;
Now, we can use this function to calculate the net sales of
any sales order in the defined table.
The following picture display where we can find the scalar
functions:
25
We can call the scalar functions the same as the built-in
function in SQL Server. For example, we can call the above
udfNet_Sales function as below:
SELECT dbo.udfNet_Sales(25, 500, 0.2) AS net_sales;
Executing this function will return the net sales:
SQL Server also allows us to modify the scalar function
by using the ALTER keyword. Here is the syntax to do
this:
ALTER FUNCTION schema_name.function_name (parame
ter_list)
RETURNS data_type AS
BEGIN
statements
RETURN value
END
We can use the below statement to remove the scalar
function from the SQL Server database:
DROP FUNCTION [schema_name.]function_name;
Table-Valued Functions
26
Table-valued functions in SQL Server are the user-
defined function that returns data of a table type. Since
this function's return type is a table, we can use it the
same way as we use a table.
We can categorize the table-valued function into two
types:
1. Inline Table-Values Functions
This UDF function returns a table variable based on the
action performed by the function. A single SELECT
statement should be used to determine the value of the
table variable.
Example
The below example will create a table-values function and
retrieve the data of the employee table:
--It creates a table-valued function to get employees
CREATE FUNCTION fudf_GetEmployee()
RETURNS TABLE
AS
RETURN (SELECT * FROM Employee)
In this syntax, the RETURNS TABLE specifies that the
function will return a table. Since there is
no BEGIN...END statement, it simply queries data from
the employee table. Also, if it does not have any
parameters, it will be called directly.
We can call the table-valued functions by using
the FROM clause of the SELECT query. For example, we
can call the above udf_GetEmployee function as below:
SELECT * FROM udf_GetEmployee();
Executing this function will return the below result:
27
SQL Server also allows us to modify the table-valued
functions using the ALTER keyword instead of the CREATE
keyword. The rest of the script is the same.
Multi-statement table-valued functions (MSTVF)
This UDF function returns a table variable based on the
action performed by the function. It can contain single or
multiple statements to produce the result, and it is also a
function that returns the result of multiple statements in a
tabular form. It is useful because we can execute multiple
statements in this function and get aggregated results into
the returned table. We can define this function by using a
table variable as the return value. Inside the function, we
execute multiple queries and insert data into this table
variable.
The following example creates a function
name 'MULTIVALUED' that returns the
'@Employee' table. It contains three fields named id,
emp_name, and salary from the 'Employee' table using
INSERT statement, and then uses UPDATE statement to
update the employee name.
CREATE FUNCTION MULTIVALUED()
RETURNS @Employee TABLE
(id INT, emp_name VARCHAR(50), salary INT) AS
BEGIN
INSERT INTO @Employee
SELECT E.id, E.emp_name, E.salary FROM Employee E;
UPDATE @Employee SET emp_name = 'Graeme Smit
h' WHERE id = 3;
RETURN
END
28
We can call the multi-statement table-valued functions by
using the FROM clause of the SELECT query. For
example, we can call the above function as below:
SELECT * FROM MULTIVALUED();
Executing this function will return the below result:
When should table-valued functions be used?
Table-valued functions are commonly used as
parameterized views. Table-valued functions are more
flexible than stored procedures because they can be used
anywhere tables are used.
Conclusion
This article will explain a complete overview of functions
used in the SQL Server. Here we have learned mainly two
types of functions used in the SQL Server: system and
user-defined functions.
29