Commonly Used MySQL Functions You Must Know
MySQL is one of the most popular databases used all over the world for storing data. Developed by Oracle Corporation, the “My” part comes from the name of the daughter of Micheal Widenius, co-founder of MySQL, while SQL stands for Structured Query Language. Due to its advanced features and freeware nature, it is used by companies like Netflix, Verizon, Twitter among others as their primary database.
The main component of MySQL is its server, the MySQL Server. This is where the data is stored. A client like a web browser communicates with the server. MySQL functions are an important part of MySQL that enable this communication. In this article, we’ll discuss about some commonly used MySQL functions.
What is an MySQL Function?
A MySQL function is a stored program that can be called when required and passed parameters to get a value in return. You can create your own functions, but there are many built-in functions provided you can use off the shelves.
You can use the functions in SQL statements or as queries in MySQL. Alternatively, they can also be used within a MySQL programming environment.
Types of MySQL Functions
There are different types of MySQL Functions. These can be divided into 7 categories. Those are:
1. MySQL Aggregate Functions
In these type of functions, multiple rows are added to provide a single summary value as output. The AVG() is the most common Aggregate function used in MySQL. It takes in multiple numbers are input and returns their average as output.
The syntax for the Aggregate functions is:
This code will return the average price of all the product’s price listed in the products table.
The first one returns the number of rows in a set.
Syntax:
The above code will return all rows from count_employees table.
The above expression will find the biggest amount from the salaries table.
This code will select the minimum price from the grocery table.
This code will return the population standard variance.
2. Comparison Functions
These types of MySQL functions are used to compare the values in a row or array and returns the desired value, without performing any calculations. For example, in GREATEST() function, it returns the greatest value in the row as output.
Some example of MySQL Comparison Functions are:
In the above code, COALESCE function will look for the values in state and if it finds NULL, it will replace it with N/A.
The above code will return the highest and lowest values in the list. If there’s a NULL value, then it’ll return NULL without doing any calculations.
It checks whether the argument is NULL or not.
3. Control Flow and Expression Functions
MySQL Control Flow Functions are the functions to use if you want to add logic to your MySQL program. These functions save you the time of writing procedural code on your own.
Commonly used functions of this category are:
CASE functions evaluates each condition and then performs the corresponding statement. If nothing found, then executes the else_result.
If the expression evaluates to true, then true_expression is executed, otherwise false_expression.
Returns expr_1 if it is not NULL, otherwise returns expr_2.
Returns NULL expr_1 is equal to expr_2, otherwise returns expr_1.
4. Date Functions
If you want to manipulate date and time in a MySQL environment, then employ Date functions. One of the functions, DAY(), returns the day of the month of a specific date as output.
Common date functions in MySQL are:
Returns the current date in the YYYY-MM-DD format.
Calculates the time difference between the first and second date.
Selects the date from the current date.
It takes in two arguments. First is the starting date and second is the interval value that is added to the starting date.
5. String Functions
If you want to work with character string data in MySQL and manipulate them at will, then you should be using MySQL string functions. For example, CONCAT() will combine two or more strings into an unified string. Please note, this is different from aggregate function and is meant only to manipulate strings. While aggregate functions can manipulate other data type as well.
Common string functions in MySQL are:
Converts the arguments to strings followed by concatenating to a single value. NULL is the output if any of the arguments in NULL.
INSTR check for the first appearance of the substring in a string. First argument is the string (str), second argument is substring (substr).
Returns the length of the string (str) in bytes.
6. Window Functions
Window functions in MySQL allow you to take inputs from the window of multiple rows. You should use them in solving analytical queries. These are distinguished from other MySQL functions by the OVER prefix.
Some common MySQL window functions include:
Calculates and returns the cumulative distribution of a particular value within the set.
DENSE_RANK function assigns rank to each row present within a partition or result set. This returns consecutive rank values.
FIRST_VALUE() will select the first row of a window frame depending on the clauses mentioned.
7. Math Functions
Math functions in MySQL allows you to carry out mathematical calculations. For example, ROUND() function will round off a number to a specific number of decimal places.
Commonly used MySQL match functions are:
The ABS function will return the absolute positive value of n. For example, -20 will return 20.
This function will round off the number
This function will truncate the number (X) to a specific number of decimal places which is specified as D. So TRUNCATE(1.555, 1) will return 1.5.
These built-in function save a lot of your programming hours. There are many more useful built-in MySQL functions which you can access here. Apart from that, you can create your own!
MySQL is one of the most popular databases used all over the world for storing data. Developed by Oracle Corporation, the “My” part comes from the name of the daughter of Micheal Widenius, co-founder of MySQL, while SQL stands for Structured Query Language. Due to its advanced features and freeware nature, it is used by companies like Netflix, Verizon, Twitter among others as their primary database.
The main component of MySQL is its server, the MySQL Server. This is where the data is stored. A client like a web browser communicates with the server. MySQL functions are an important part of MySQL that enable this communication. In this article, we’ll discuss about some commonly used MySQL functions.
What is an MySQL Function?
A MySQL function is a stored program that can be called when required and passed parameters to get a value in return. You can create your own functions, but there are many built-in functions provided you can use off the shelves.
You can use the functions in SQL statements or as queries in MySQL. Alternatively, they can also be used within a MySQL programming environment.
Types of MySQL Functions
There are different types of MySQL Functions. These can be divided into 7 categories. Those are:
1. MySQL Aggregate Functions
In these type of functions, multiple rows are added to provide a single summary value as output. The AVG() is the most common Aggregate function used in MySQL. It takes in multiple numbers are input and returns their average as output.
The syntax for the Aggregate functions is:
Code:
function_name(DISTINCT | ALL expression)
- function_name is the name of the function
- Inside the brackets, you can either use DISTINCT or ALL depending on whether you want to calculate distinct values or all values including duplicates
- Finally provide the expression consisting of column and arithmetic operation
- AVG()
Code:
AVG(DISTINCT | ALL expression)
SELECT
AVG(buyprice) ‘Average Price’
FROM
products;
- COUNT()
The first one returns the number of rows in a set.
Syntax:
Code:
SELECT COUNT(*)
FROM count_employees;
- MAX()
Code:
SELECT MAX(amount)
FROM salaries;
- MIN()
Code:
SELECT MIN(buyPrice)
FROM grocery;
- VARIANCE()
Code:
SELECT VARIANCE(total_cost)
FROM database;
2. Comparison Functions
These types of MySQL functions are used to compare the values in a row or array and returns the desired value, without performing any calculations. For example, in GREATEST() function, it returns the greatest value in the row as output.
Some example of MySQL Comparison Functions are:
- COALESCE()
Code:
SELECT COALESCE(state, N/A)
FROM addresses;
- GREATEST() and LEAST()
Code:
SELECT
employee_id
LEAST (s1, s2, s3, …, sN) low,
GREATEST (s1, s2, s3,…, sN) high
FROM
employees;
- ISNULL()
Code:
SELECT ISNULL (NULL);
3. Control Flow and Expression Functions
MySQL Control Flow Functions are the functions to use if you want to add logic to your MySQL program. These functions save you the time of writing procedural code on your own.
Commonly used functions of this category are:
- CASE
Code:
CASE
WHEN condition1 then statement1
WHEN condition2 then statement2
[ELSE else_result]
END
- IF()
Code:
SELECT IF(expression, true_expression, false_expression)
- IFNULL()
Code:
IFNULL(expr_1, expr_2)
- NULLIF
Code:
NULLIF(expr_1, expr_2)
4. Date Functions
If you want to manipulate date and time in a MySQL environment, then employ Date functions. One of the functions, DAY(), returns the day of the month of a specific date as output.
Common date functions in MySQL are:
- CURDATE()
Code:
SELECT CURDATE()
- DATEDIFF()
Code:
SELECT DATEDIFF(first_date, second_date)
- DAY()
Code:
SELECT DAY(‘Date’)
- DATE_ADD()
Code:
SELECT DATE_ADD(start_date, INTERVAL expr unit);
5. String Functions
If you want to work with character string data in MySQL and manipulate them at will, then you should be using MySQL string functions. For example, CONCAT() will combine two or more strings into an unified string. Please note, this is different from aggregate function and is meant only to manipulate strings. While aggregate functions can manipulate other data type as well.
Common string functions in MySQL are:
- CONCAT()
Code:
SELECT CONCAT(str1, str2, str3, ...)
- INSTR()
Code:
SELECT INSTR(str, substr)
- LENGTH()
Code:
SELECT LENGTH(str);
6. Window Functions
Window functions in MySQL allow you to take inputs from the window of multiple rows. You should use them in solving analytical queries. These are distinguished from other MySQL functions by the OVER prefix.
Some common MySQL window functions include:
- CUME_DIST()
Code:
CUME_DIST() OVER {
PARTITION BY expr, ….
ORDER BY expr [ASC | DESC], ….
}
- DENSE_RANK()
Code:
DENSE_RANK() OVER {
PARTITION BY <expr>[{, <expr>...}]
ORDER_BY <expr> [ASC | DESC], [{, <expr>}]
}
- FIRST_VALUE()
Code:
FIRST_VALUE (expr) OVER {
[partition_clause]
[order_clause]
[frame_clause]
}
7. Math Functions
Math functions in MySQL allows you to carry out mathematical calculations. For example, ROUND() function will round off a number to a specific number of decimal places.
Commonly used MySQL match functions are:
- ABS()
Code:
SELECT ABS(n);
- ROUND()
Code:
SELECT ROUND(n, [d]);
(n)
to the decimal places ([d]). [d] is optional here.- TRUNCATE()
Code:
SELECT TRUNCATE(X, D);
- DELETE()
Code:
DELETE FROM table_name WHERE condition;
Code:
SELECT IF(expression, true_expression, false_expression)