SQL functions are pre-written blocks of code that perform specific tasks within queries.
They save you time and effort by encapsulating common operations, making your code more readable and maintainable.
Categorization of popular SQL functions:
1. Scalar Functions:
ABS()
, SQRT()
, ROUND()
, etc.UPPER()
, LOWER()
, SUBSTRING()
, etc.CURDATE()
, DATEDIFF()
, etc.2. Aggregate Functions:
COUNT()
: Calculates the number of rows in a set.SUM()
: Computes the total of a numeric column.AVG()
: Returns the average of a numeric column.MIN()
, MAX()
: Find the minimum and maximum values in a column.3. Conditional Functions:
CASE WHEN
... THEN
... ELSE
... END
SQL functions are built-in operations that perform specific tasks and return a single value.
These functions can be used to manipulate data, perform calculations, format output, and more.
Some common SQL functions:
Aggregate Functions:
SELECT COUNT(*) FROM employees;
SELECT SUM(salary) FROM employees;
SELECT AVG(salary) FROM employees;
SELECT MIN(salary) FROM employees;
SELECT MAX(salary) FROM employees;
String Functions:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;
SELECT SUBSTRING(description, 1, 10) AS short_description FROM products;
SELECT UPPER(last_name) AS last_name_upper FROM employees;
Date Functions:
SELECT CURRENT_DATE;
SELECT DATE_FORMAT(birth_date, '%Y-%m-%d') AS formatted_date FROM employees;
SELECT DATEDIFF(end_date, start_date) AS days_difference FROM projects;
Math Functions:
SELECT ROUND(salary, 2) FROM employees;
SELECT ABS(-10);
Conditional Functions:
SELECT
These are just a few examples of SQL functions.
Each database system may have its own set of functions with additional features and variations.