🗄️ SQL Q23 / 104

What is a function in SQL?

AI-Powered Answer ✓ Answered

Functions in SQL are named routines that encapsulate a specific piece of logic or calculation, accepting zero or more input parameters and returning a single value or a set of values.

What is a Function in SQL?

In SQL, a function is a database object that performs an action or computation and returns a result. Functions are essential for performing calculations, manipulating data, and encapsulating complex logic into reusable units.

They can be broadly categorized into built-in (system) functions provided by the database management system and user-defined functions (UDFs) created by database users.

Types of SQL Functions

Built-in (System) Functions

These are functions that are pre-defined and provided by the SQL database system (e.g., MySQL, PostgreSQL, SQL Server, Oracle). They cover a wide range of operations including mathematical calculations, string manipulation, date and time operations, and aggregate computations.

  • Aggregate Functions: Operate on a set of rows and return a single summary value (e.g., COUNT(), SUM(), AVG(), MAX(), MIN()).
  • Scalar Functions: Operate on a single value and return a single value (e.g., UPPER(), LOWER(), LENGTH(), GETDATE(), SUBSTRING()).
  • Date Functions: Handle date and time manipulation (e.g., DATEADD(), DATEDIFF(), CURDATE()).
  • String Functions: Manipulate character strings (e.g., CONCAT(), REPLACE()).
sql
SELECT COUNT(OrderID) AS TotalOrders, SUM(TotalAmount) AS GrandTotal
FROM Orders
WHERE OrderDate BETWEEN '2023-01-01' AND '2023-12-31';

User-Defined Functions (UDFs)

UDFs are functions created by database users to perform custom logic that is not available in built-in functions or to encapsulate frequently used complex calculations. They promote code reusability and modularity. UDFs can be scalar (returning a single value) or table-valued (returning a table).

sql
CREATE FUNCTION CalculateTax(@Amount DECIMAL(10, 2), @Rate DECIMAL(5, 2))
RETURNS DECIMAL(10, 2)
AS
BEGIN
    RETURN @Amount * @Rate;
END;
GO

SELECT dbo.CalculateTax(100.00, 0.05) AS TaxAmount;

Why Use Functions?

  • Reusability: Write code once and use it multiple times across different queries or applications.
  • Modularity: Break down complex problems into smaller, manageable units.
  • Maintainability: Changes to business logic encapsulated in a function only need to be updated in one place.
  • Data Integrity: Enforce business rules consistently.
  • Improved Performance: In some cases, functions can optimize query execution by pre-compiling logic (though UDFs can sometimes introduce performance overhead).