SQL Functions

SQL (Structured Query Language) provides a rich set of built-in functions that allow you to perform operations on data within your database. These functions can manipulate strings, perform mathematical calculations, work with dates and times, and much more.

Categories of SQL Functions

SQL functions are typically categorized based on the type of operation they perform:

1. Aggregate Functions

Aggregate functions operate on a set of rows and return a single value. They are often used with the GROUP BY clause.

2. Scalar Functions

Scalar functions operate on a single value and return a single value. They can be used in almost any part of a SQL statement where an expression is allowed.

String Functions

Numeric Functions

Date and Time Functions

3. Window Functions

Window functions perform calculations across a set of table rows that are related to the current row. Unlike aggregate functions, window functions do not collapse rows into a single output row. The rows are referred to as the "window frame".

Using SQL Functions

Functions are typically used in the SELECT clause, WHERE clause, ORDER BY clause, and even within other functions.

Example: Using String and Aggregate Functions

Let's say we have a table named Products with columns ProductName and Price. We want to find the average price and the number of products whose names start with 'A'.


SELECT
    COUNT(*) AS NumberOfProducts,
    AVG(Price) AS AveragePrice,
    SUM(CASE WHEN UPPER(ProductName) LIKE 'A%' THEN 1 ELSE 0 END) AS ProductsStartingWithA
FROM
    Products;
                

Example: Using Date Functions

Retrieve orders placed in the last 30 days.


SELECT
    OrderID,
    OrderDate,
    CustomerID
FROM
    Orders
WHERE
    OrderDate >= DATEADD(day, -30, GETDATE());
                

Custom Functions

Most database systems also allow you to create your own user-defined functions (UDFs) to encapsulate complex logic or reusable computations.

Understanding and utilizing SQL functions is crucial for effective data manipulation, analysis, and reporting. Explore the specific functions available in your database system (e.g., SQL Server, PostgreSQL, MySQL) for a comprehensive list.