SQL Functions

SQL functions are built-in operations that perform calculations or manipulations on data. They can be used in various parts of SQL statements, such as the SELECT list, the WHERE clause, and the ORDER BY clause.

Categories of SQL Functions

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

Aggregate Functions

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

Example: Using COUNT() and AVG()


SELECT COUNT(customer_id), AVG(order_total)
FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
                

Scalar Functions

Scalar functions operate on a single value and return a single value. They can be applied to each row individually.

String Functions

Example: Using CONCAT() and UPPER()


SELECT CONCAT(UPPER(first_name), ' ', UPPER(last_name)) AS full_name
FROM employees
WHERE department = 'Sales';
                

Numeric Functions

Example: Using ROUND()


SELECT product_name, ROUND(price, 2) AS rounded_price
FROM products;
                

Date and Time Functions

Example: Using DATEADD()


SELECT order_id, order_date, DATEADD(day, 7, order_date) AS due_date
FROM orders;
                

Conversion Functions

Example: Using CAST()


SELECT CAST(order_id AS VARCHAR(10)) + '-ORD' AS order_identifier
FROM orders;
                

Window Functions

Window functions perform calculations across a set of table rows that are somehow related to the current row. Unlike aggregate functions, window functions do not cause rows to be grouped into a single output row. They return a value for each row.

Example: Using ROW_NUMBER()


SELECT
    product_name,
    price,
    ROW_NUMBER() OVER (ORDER BY price DESC) AS rank_by_price
FROM products;
                

Understanding and utilizing SQL functions is crucial for effective data manipulation and analysis in databases.