đ§Ž Functions in SQL are reusable routines that accept input values, perform a calculation or operation, and return a single value or a table, depending on the function type. SQL provides many built-in functions, and most database systems also allow you to create your own user-defined functions (UDFs).
đ What are SQL Functions?
SQL functions simplify data processing by encapsulating logic into reusable components. Instead of writing the same calculation or transformation repeatedly, you can call a function wherever it is needed.
Information
đ¯ Why Use Functions?
Functions improve code quality and simplify database development.
- đ Reuse business logic.
- đ Reduce duplicate SQL code.
- đ Simplify complex calculations.
- đ Improve query readability.
- đ Return calculated values for use in SQL statements.
đ Types of SQL Functions
| Function Type | Description |
|---|---|
| Built-in Functions | Provided by the database system (for example, COUNT(), AVG(), LOWER()). |
| Scalar Functions | Return a single value. |
| Aggregate Functions | Operate on multiple rows and return one result. |
| User-Defined Functions (UDFs) | Custom functions created by developers. |
| Table-Valued Functions | Return a table instead of a single value (supported by some databases). |
đ Basic Syntax (Scalar Function)
The syntax for creating user-defined functions differs across database systems. The following example uses SQL Server syntax.
Create a Scalar Function (SQL Server)
CREATE FUNCTION function_name
(
@parameter DataType
)
RETURNS ReturnDataType
AS
BEGIN
RETURN expression;
END;đĄ Example: Calculate a Discounted Price
Create a function that calculates a price after applying a 10% discount.
Scalar Function Example
CREATE FUNCTION CalculateDiscount
(
@Price DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Price * 0.90;
END;âļī¸ Call the Function
Execute the Function
SELECT dbo.CalculateDiscount(500.00) AS DiscountedPrice;đ Result
| Input Price | Returned Value |
|---|---|
| 500.00 | 450.00 |
đ Table-Valued Function Example
Some database systems allow functions to return an entire table.
Table-Valued Function (SQL Server)
CREATE FUNCTION GetStudentsByDepartment
(
@Department VARCHAR(100)
)
RETURNS TABLE
AS
RETURN
(
SELECT *
FROM Students
WHERE Department = @Department
);âļī¸ Query a Table-Valued Function
Call a Table-Valued Function
SELECT *
FROM GetStudentsByDepartment('Computer Science');đ Function Workflow
| Step | Description |
|---|---|
| Input | The caller passes parameter values. |
| Processing | The function executes its logic. |
| Return | A scalar value or table is returned. |
| Usage | The returned result can be used in SQL queries. |
âī¸ Functions vs Stored Procedures
| Feature | Function | Stored Procedure |
|---|---|---|
| Returns a Value | â Always | Optional |
| Can Return a Table | â In supported databases | Can return result sets, but not as a table-valued function. |
| Can Be Used Inside a SELECT | â Yes | â No |
| Primary Purpose | Compute and return values. | Perform database operations. |
đŧ Real-World Example
An online shopping application calculates sales tax for every order. Instead of repeating the formula in every query, a function computes the tax whenever it is needed.
Sales Tax Function
CREATE FUNCTION CalculateTax
(
@Amount DECIMAL(10,2)
)
RETURNS DECIMAL(10,2)
AS
BEGIN
RETURN @Amount * 0.18;
END;đī¸ Database Compatibility
| Database System | Function Support |
|---|---|
| SQL Server | â Scalar and table-valued functions. |
| PostgreSQL | â Rich function support with multiple procedural languages. |
| Oracle | â Supports functions using PL/SQL. |
| MySQL | â Supports stored functions that return scalar values. |
| SQLite | Limited built-in support; custom functions are typically added through the host application. |
â ī¸ Advantages
- â Improve code reuse.
- â Simplify calculations.
- â Make queries easier to read.
- â Centralize reusable business logic.
- â Can be called from multiple SQL statements.
â ī¸ Limitations
- â Syntax varies across database systems.
- â Complex functions may impact performance if overused.
- â Some databases restrict what operations functions can perform.
- â Not every database supports table-valued functions.
Warning
â ī¸ Best Practices
Best Practice
đ Key Points to Remember
- đ SQL functions return a value or, in some databases, a table.
- đ Built-in functions and user-defined functions serve different purposes.
- đ Functions improve code reuse and readability.
- đ Functions can often be used directly inside SQL expressions.
- đ User-defined function syntax differs among database systems.
- đ Choose functions for reusable calculations and stored procedures for broader database operations.