Mysql Functions
Mysql Functions
MYSQL FUNCTIONS........................................................................................................................................................1
A. MYSQL AGGREGATE FUNCTIONS.............................................................................................................................1
MySQL Aggregate Functions............................................................................................................................................1
Introduction to MySQL aggregate functions................................................................................................................1
AVG function................................................................................................................................................................... 2
COUNT function.............................................................................................................................................................2
SUM function...................................................................................................................................................................2
MAX function................................................................................................................................................................... 3
MIN function....................................................................................................................................................................3
MySQL AVG........................................................................................................................................................................4
Introduction to MySQL AVG function...........................................................................................................................4
MySQL AVG examples..................................................................................................................................................4
MySQL AVG with DISTINCT.....................................................................................................................................5
MySQL AVG with GROUP BY clause.....................................................................................................................5
MySQL AVG with HAVING clause...........................................................................................................................6
MySQL AVG function with subquery........................................................................................................................6
MySQL AVG function with NULL values.................................................................................................................7
MySQL AVG with control flow function....................................................................................................................7
MySQL COUNT..................................................................................................................................................................8
Introduction to the MySQL COUNT function...............................................................................................................8
MySQL COUNT(*)......................................................................................................................................................8
MySQL COUNT(expression).....................................................................................................................................9
MySQL COUNT(DISTINCT expression).................................................................................................................9
MySQL COUNT examples............................................................................................................................................9
MySQL COUNT with GROUP BY..............................................................................................................................10
MySQL COUNT IF........................................................................................................................................................12
MySQL INSTR Function..................................................................................................................................................13
Introduction to the MySQL INSTR function...............................................................................................................13
The MySQL INSTR function examples......................................................................................................................13
The INSTR function vs. LIKE operator......................................................................................................................14
MySQL SUM.....................................................................................................................................................................16
Introduction to MySQL SUM function.........................................................................................................................16
MySQL SUM function examples.................................................................................................................................17
1 of 142
MySQL SUM with GROUP BY................................................................................................................................17
MySQL SUM with HAVING.....................................................................................................................................18
MySQL SUM with LIMIT..........................................................................................................................................18
MySQL SUM with NULL..........................................................................................................................................19
MySQL SUM with JOIN...........................................................................................................................................19
MySQL MIN Function.......................................................................................................................................................20
Introduction to MySQL MIN function..........................................................................................................................20
MySQL MIN function examples..................................................................................................................................20
MySQL MIN with subquery......................................................................................................................................21
MySQL MIN with GROUP BY.................................................................................................................................21
MySQL MIN with correlated subquery...................................................................................................................22
MySQL MAX Function.....................................................................................................................................................23
Introduction to MySQL MAX function.........................................................................................................................23
MySQL MAX function examples.................................................................................................................................23
MySQL MAX function in subquery.........................................................................................................................24
MySQL MAX with GROUP BY clause...................................................................................................................25
MySQL MAX with HAVING clause.........................................................................................................................25
MySQL GROUP_CONCAT Function.............................................................................................................................26
Introduction to MySQL GROUP_CONCAT function................................................................................................26
MySQL GROUP_CONCAT examples.......................................................................................................................27
MySQL GROUP_CONCAT with CONCAT_WS function example....................................................................31
MySQL GROUP_CONCAT function: common mistakes........................................................................................31
MySQL GROUP_CONCAT applications...............................................................................................................32
References.................................................................................................................................................................... 32
MySQL Standard Deviation.............................................................................................................................................32
Introduction to standard deviation..............................................................................................................................32
Population standard deviation vs. sample standard deviation............................................................................33
MySQL standard deviation functions.........................................................................................................................33
Examples of MySQL standard deviation functions..................................................................................................34
Examples of population standard deviation functions.........................................................................................34
Examples of sample standard deviation functions...............................................................................................35
B. MYSQL STRING FUNCTIONS....................................................................................................................................36
MySQL CONCAT Function..............................................................................................................................................36
MySQL CONCAT function...........................................................................................................................................36
MySQL CONCAT_WS function: Concatenate strings with a separator................................................................38
2 of 142
MySQL String Length.......................................................................................................................................................39
Examples of LENGTH and CHAR_LENGTH functions...........................................................................................40
An application of MySQL string length functions......................................................................................................42
Reference...................................................................................................................................................................... 42
MySQL LEFT Function....................................................................................................................................................43
Introduction to MySQL LEFT function........................................................................................................................43
MySQL LEFT function examples................................................................................................................................43
Using MySQL LEFT function with literal strings example...................................................................................43
Using MySQL LEFT function with a column example..........................................................................................44
MySQL Replace String Function....................................................................................................................................46
Introduction to MySQL REPLACE string function....................................................................................................47
MySQL REPLACE string function example..............................................................................................................47
MySQL SUBSTRING Function.......................................................................................................................................48
MySQL SUBSTRING with position parameter.........................................................................................................48
MySQL SUBSTRING with position and length.........................................................................................................49
MySQL TRIM Function....................................................................................................................................................50
Introduction to the MySQL TRIM function.................................................................................................................50
MySQL TRIM function examples................................................................................................................................51
MySQL LTRIM and RTRIM function..........................................................................................................................52
MySQL FIND_IN_SET Function.....................................................................................................................................53
Introduction to MySQL FIND_IN_SET function........................................................................................................53
The MySQL FIND_IN_SET examples.......................................................................................................................54
MySQL FIND_IN_SET: simple examples..............................................................................................................54
MySQL FIND_IN_SET: querying data from table example................................................................................54
MySQL NOT FIND_IN_SET example....................................................................................................................55
MySQL FIND_IN_SET function vs. IN operator.......................................................................................................56
MySQL FORMAT Function.............................................................................................................................................57
Introduction to the MySQL FORMAT function..........................................................................................................57
MySQL FORMAT function examples.........................................................................................................................57
C. MYSQL CONTROL FLOW FUNCTIONs.....................................................................................................................61
MySQL CASE Expression...............................................................................................................................................61
Introduction to MySQL CASE expression.................................................................................................................61
MySQL CASE function examples...............................................................................................................................62
MySQL IF Statement........................................................................................................................................................64
MySQL IF statement syntax........................................................................................................................................64
3 of 142
MySQL IF ELSE statement.........................................................................................................................................65
MySQL IF ELSEIF ELSE statement..........................................................................................................................66
MySQL IF statement examples..................................................................................................................................67
MySQL IFNULL................................................................................................................................................................ 68
Introduction to MySQL IFNULL function....................................................................................................................69
MySQL IFNULL function examples............................................................................................................................69
MySQL NULLIF................................................................................................................................................................ 71
Introduction to MySQL NULLIF function....................................................................................................................71
MySQL NULLIF examples...........................................................................................................................................71
Using NULLIF function to prevent division by zero error.........................................................................................72
D. MYSQL DATE AND TIME FUNCTIONS....................................................................................................................74
MySQL CURDATE Function...........................................................................................................................................75
Introduction to MySQL CURDATE function................................................................................................................75
CURDATE vs. NOW....................................................................................................................................................75
MySQL DATEDIFF Function...........................................................................................................................................76
Introduction to MySQL DATEDIFF function..............................................................................................................76
MySQL DATEDIFF examples.....................................................................................................................................76
MySQL DAY Function......................................................................................................................................................78
Introduction to MySQL DAY function..........................................................................................................................78
MySQL DAY function examples..................................................................................................................................79
MySQL DATE_ADD Function.........................................................................................................................................80
Introduction to MySQL DATE_ADD function..............................................................................................................80
MySQL DATE_ADD function examples......................................................................................................................81
MySQL DATE_ADD function usage notes.................................................................................................................82
Interval Handling.......................................................................................................................................................82
Automatic DATETIME conversion..........................................................................................................................83
Invalid starting date..................................................................................................................................................83
Adjusted day, month, or year..................................................................................................................................84
MySQL DATE_SUB Function.........................................................................................................................................85
Introduction to MySQL DATE_SUB function..............................................................................................................85
MySQL DATE_SUB: negative interval........................................................................................................................86
MySQL DATE_SUB: Invalid or malformed date........................................................................................................86
MySQL DATE_SUB: automatic adjusted day............................................................................................................87
MySQL DATE_FORMAT Function.................................................................................................................................87
4 of 142
Introduction to MySQL DATE_FORMAT function....................................................................................................87
MySQL DATE_FORMAT examples...........................................................................................................................90
MySQL DATE_FORMAT with ORDER BY...........................................................................................................91
MySQL DAYNAME Function...........................................................................................................................................92
Introduction to MySQL DAYNAME function................................................................................................................93
MySQL DAYNAME function examples........................................................................................................................93
MySQL DAYOFWEEK Function.....................................................................................................................................96
MySQL EXTRACT Function............................................................................................................................................96
Introduction to the MySQL EXTRACT function........................................................................................................96
MySQL EXTRACT function examples.......................................................................................................................97
MySQL NOW() Function................................................................................................................................................102
Introduction to MySQL NOW() function...................................................................................................................102
MySQL NOW() function calculations.......................................................................................................................103
MySQL NOW() as a default value for a column.....................................................................................................103
MySQL MONTH Function.............................................................................................................................................104
Introduction to MySQL MONTH function...................................................................................................................104
MySQL MONTH function examples...........................................................................................................................105
Practical usages of MySQL MONTH function.........................................................................................................106
MySQL STR_TO_DATE() Function.............................................................................................................................107
Introduction to MySQL STR_TO_DATE function...................................................................................................107
MySQL STR_TO_DATE examples..........................................................................................................................107
MySQL SYSDATE Function..........................................................................................................................................109
Introduction to MySQL SYSDATE function..............................................................................................................109
SYSDATE vs. NOW...................................................................................................................................................110
MySQL TIMEDIFF Function..........................................................................................................................................112
Introduction to MySQL TIMEDIFF function............................................................................................................112
MySQL TIMEDIFF function examples.....................................................................................................................113
MySQL TIMEDIFF function and truncated incorrect time value..........................................................................114
MySQL TIMESTAMPDIFF Function............................................................................................................................115
Introduction to MySQL TIMESTAMPDIFF function................................................................................................115
MySQL TIMESTAMPDIFF function examples........................................................................................................115
Calculating ages using MySQL TIMESTAMPDIFF function.................................................................................117
MySQL WEEK Function................................................................................................................................................118
Introduction to MySQL WEEK function.....................................................................................................................118
5 of 142
MySQL WEEK function example..............................................................................................................................119
MySQL WEEKDAY Function.........................................................................................................................................120
MySQL YEAR Function.................................................................................................................................................121
Introduction to MySQL YEAR function.....................................................................................................................121
MySQL YEAR function and indexes........................................................................................................................122
E. MYSQL COMPARISON FUNCTIONS......................................................................................................................124
MySQL COALESCE Function.......................................................................................................................................125
Introduction to MySQL COALESCE function..........................................................................................................125
MySQL COALESCE function examples..................................................................................................................125
MySQL COALESCE and CASE expression...........................................................................................................127
MySQL COALESCE vs. IFNULL..............................................................................................................................128
MySQL GREATEST And LEAST, Max and Min of Two or More Fields.................................................................128
Introduction to MySQL GREATEST and LEAST functions...................................................................................128
MySQL GREATEST and LEAST examples................................................................................................................129
The Essential Guide To MySQL ISNULL Function.....................................................................................................131
Introduction to MySQL ISNULL function.................................................................................................................131
MySQL ISNULL function & IS NULL operator........................................................................................................131
F. OTHER MYSQL FUNCTIONS...................................................................................................................................132
MySQL LAST_INSERT_ID Function...........................................................................................................................132
Introduction to MySQL LAST_INSERT_ID function...............................................................................................133
MySQL LAST_INSERT_ID example........................................................................................................................133
MySQL CAST Function.................................................................................................................................................134
Introduction to MySQL CAST function.....................................................................................................................134
MySQL CAST function examples.............................................................................................................................135
MYSQL FUNCTIONS
A. MySQL aggregate functions
MySQL aggregate functions – provide a brief overview of the most commonly used MySQL
aggregate functions
6 of 142
INSTR – return the position of the first occurrence of a substring in a string.
GROUP_CONCAT – concatenate strings from a group into a string with various options such
as DISTINCT , ORDER BY and SEPARATOR .
MySQL standard deviation functions – shows you how to compute population standard deviation
and sample standard deviation.
The data that you need is not always stored in the tables. However, you can get it by performing the
calculations of the stored data when you select it.
For example, you cannot get the total amount of each order by simply querying from
the orderdetails table because the orderdetails table stores only quantity and price of each item.
You have to select the quantity and price of an item for each order and calculate the order’s total.
To perform such calculations in a query, you use aggregate functions.
By definition, an aggregate function performs a calculation on a set of values and returns a single value.
MySQL provides many aggregate functions that include AVG , COUNT , SUM , MIN , MAX , etc. An aggregate
function ignores NULL values when it performs calculation except for the COUNT function.
7 of 142
AVG function
The AVG function calculates the average value of a set of values. It ignores NULL values in the
calculation.
1 AVG(expression)
You can use the AVG function to calculate the average buy price of all products in the products table by
using the following query:
COUNT function
The COUNT function returns the number of the rows in a table. For example, you can use
the COUNT function to get the number of products in the products table as the following query:
The COUNT function has several forms such as COUNT(*) and COUNT(DISTINCT expression) . For more
information, check it out the COUNT function tutorial.
SUM function
The SUM function returns the sum of a set of values. The SUM function ignores NULL values. If no matching
row found, the SUM function returns a NULL value.
To get the total sales of each product, you can use the SUM function in conjunction with the GROUP
BY clause as follows:
8 of 142
More information on the SUM function in detail.
MAX function
The MAX function returns the maximum value in a set of values.
1 MAX(expression)
For example, you can use the MAX function to get the most expensive product in the products table as
the following query:
MIN function
The MIN function returns the minimum value in a set of values.
1 MIN(expression)
For example, the following query uses the MIN function to find the product with the lowest price in
the products table:
In this tutorial, we have shown you how to use the most commonly used MySQL aggregate functions.
MySQL AVG
Summary: in this tutorial, you will learn how to use MySQL AVG function to calculate the average value
of a set of values or an expression.
1 AVG(DISTINCT expression)
9 of 142
You use the DISTINCT operator in the AVG function to calculate the average value of the distinct values.
For example, if you have a set of values 1,1,2,3, the AVG function with DISTINCT operation will return two
i.e., (1 + 2 + 3) / 2 .
To calculate average buy price of all products in the products table, you use the AVG function as the
following query:
Notice that the FORMAT function is used to format the average value returned by the AVG function.
You can add a WHERE clause to the SELECT statement to calculate the average value of a subset of
values. For example, to calculate the average buy price of products whose product line is Classic Cars ,
you use the following query:
You can use AVG function to calculate the average of distinct buy prices by adding the DISTINCT operator
as follows:
The result is slightly different from the average buy price without using the DISTINCT operator.
For example, to calculate the average buy price of products for each product line, you use the AVG function
with the GROUP BY clause as the following query:
1 SELECT productline,
2 AVG(buyprice) 'Avarage Price'
3 FROM products
4 GROUP BY productline;
For example, if you want to select only product lines that have product’s average buy prices are greater
than 50, you can use the following query:
11 of 142
1 SELECT productline,
2 AVG(buyprice) 'Avarage Price'
3 FROM products
4 GROUP BY productline
5 HAVING AVG(buyprice) > 50;
How it works.
Third, calculate the average value of the values in the val column by using the AVG function:
The statement returns 2 as expected because the NULL value is not included in the calculation of
the AVG function.
For example, to calculate the ratio of the average buy price of Classic Cars product line to average buy
price of all products, you use the following statement:
Because the AVG function ignores the NULL values in the calculation so
the AVG(IF(productline='Classic Cars',buyprice,NULL)) expression calculates the average buy
price for only products whose product line is Classic Cars .
In this tutorial, we have shown you some useful techniques to calculate the average value of a set of
values by using MySQL AVG function.
MySQL COUNT
Summary: in this tutorial, you will learn how to use the MySQL COUNT function to count the number
rows in a table.
13 of 142
Introduction to the MySQL COUNT function
The COUNT function returns the number of rows in a table. The COUNT function allows you to count all rows
in a table or rows that match a particular condition.
1 COUNT(expression)
The return type of the COUNT function is BIGINT . The COUNT function returns zero if there was no
matching row found.
There are several forms of the COUNT function: COUNT(*) , COUNT(expression) and COUNT(DISTINCT
expression) .
MySQL COUNT(*)
The COUNT(*) function returns the number of rows in a result set returned by a SELECT statement.
The COUNT(*) function counts rows that contain no-NULL and NULL values.
If you use the COUNT(*) function to count the number rows in a table without using the WHERE
clauseand selecting other columns, it will perform very fast.
This optimization is applied to MyISAM tables only because the number of rows of a MyISAM table is
stored in the table_rows column in the tables table of the information_schema database; therefore,
MySQL COUNT(expression)
The COUNT(expression) returns the number of rows that do not contain NULL values.
14 of 142
8 VALUES(1),(1),(2),(2),(NULL),(3),(4),(NULL),(5);
9 -- select data from demos table
10 SELECT * FROM demos;
To count all rows in the demos table, you use the COUNT(*) function as follows:
1 SELECT COUNT(*)
2 FROM demos;
You can add a WHERE clause to specify a condition to count e.g., to count only rows whose val column
contains number 2, you use the following query:
1 SELECT COUNT(*)
2 FROM demos
3 WHERE val = 2;
If you specify the val column in the COUNT function, the COUNT function counts all rows whose val column
contains non-NULL values only. See the following query:
1 SELECT COUNT(*)
2 FROM demos
3 WHERE val = 2;
15 of 142
To count unique rows in the demos table, you add the DISTINCT operator to the COUNT function as the
following query:
Two duplicate values 1,2 and two NULL values are ignored in the counting.
For example, to find how many products in each product line, you use the COUNT function with the GROUP
BY clause as follows:
16 of 142
To find the number of products supplied by vendors, you use the following query:
To find which vendor supplies at least 9 products, you use the COUNT function in the HAVING clause as
the following query:
MySQL COUNT IF
You can use a control flow function e.g., IF, IFNULL, CASE, etc., in the COUNT function to count rows
whose values match a condition.
For example, the following query finds how many orders are cancelled, on hold and disputed:
The IF function returns 1 if the order’s status is cancelled, on hold or disputed, otherwise, it returns NULL .
The COUNT function only counts 1, not NULL values, therefore, the query returns the number of orders
based on the corresponding status.
In this tutorial, you have learned various techniques to count the number of rows in a table using the
MySQL COUNT function.
The INSTR function returns the position of the first occurrence of a substring in a string. If the substring is
not found in the str, the INSTR function returns zero (0).
1 INSTR(str,substr);
The INSTR function is not case sensitive. It means that it does not matter if you pass the lowercase,
uppercase, title case, etc., the results are always the same.
If you want the INSTR function to perform searches in case-sensitive manner on a non-binary string, you
use the BINARY operator to cast a one the argument of the INSTR function from a non-binary string to a
binary string.
18 of 142
The following statement returns the same result because the INSTR function is case-insensitive.
To force INSTR function to search based on case-sensitive fashion, you use the BINARY operator as
follows:
The result is different because mysql vs. MySQL now with the BINARY operator.
Suppose you want to find product whose name contains the car keyword, you can use the INSTR function
as follows:
1 SELECT
2 productName
3 FROM
4 products
5 WHERE
6 INSTR(productname,'Car') > 0;
19 of 142
Besides the INSTR function, you can use the LIKE operator to match the Car pattern.
1 SELECT
2 productname
3 FROM
4 products
5 WHERE
6 productname LIKE '%Car%';
Both queries return the same result. So which one is faster, the INSTR or the LIKE operator?
The answer is the that they are the same. They are both case-sensitive and perform full table scans.
If you use the LIKE operator with the prefix search, on this indexed column, the LIKE operator will
perform faster than the INSTR function.
1 SELECT
2 productname
3 FROM
4 products
5 WHERE
6 productname LIKE '1900%';
1 EXPLAIN SELECT
2 productname
3 FROM
4 products
5 WHERE
6 productname LIKE '1900%';
And compare with the following statement that uses the INSTR function.
20 of 142
1 EXPLAIN SELECT
2 productname
3 FROM
4 products
5 WHERE
6 instr(productname,'1900');
The INSTR function performs a table scan even though the productname column has an index. This is
because MySQL cannot make any assumption about the semantics of the INSTR function, whereby
MySQL can utilize its understanding of the semantics of the LIKE operator.
The fastest way to test if a substring exists in a string is to use a full-text index. However, it is required a
configure and maintain the index properly.
In this tutorial, you have learned how to use the INSTR function to find the position of the first occurrence
of a substring in a string.
MySQL SUM
Summary: in this tutorial, you will learn how to use the MySQL SUM function to calculate the sum of a set
of values or an expression.
1 SUM(DISTINCT expression)
If you use the SUM function in a SELECT statement that returns no matching row, the SUM function
returns NULL , not zero.
The DISTINCT operator allows you to calculate distinct values in the set.
21 of 142
MySQL SUM function examples
Let’s take a look at the orderdetails table in the sample database.
You can calculate the total amount of the order number 10100 by using the SUM function as the following
query:
Notice that the FORMAT function is used for formatting the returned value of the SUM function.
For example, you can calculate the total amount of each order by using the SUM function with the GROUP
BY clause as follows:
1 SELECT orderNumber,
2 FORMAT(SUM(quantityOrdered * priceEach),2) total
3 FROM orderdetails
4 GROUP BY orderNumber
5 ORDER BY SUM(quantityOrdered * priceEach) DESC;
22 of 142
MySQL SUM with HAVING
You can use the SUM function in the HAVING clause to filter the result based on a specific condition. For
example, you can calculate the total amount of orders and only select the orders whose total amounts are
greater than 60000 .
1 SELECT orderNumber,
2 FORMAT(SUM(quantityOrdered * priceEach),2)
3 FROM orderdetails
4 GROUP BY orderNumber
5 HAVING SUM(quantityOrdered * priceEach) > 60000
6 ORDER BY SUM(quantityOrdered * priceEach);
1 SELECT SUM(buyprice)
2 FROM products
3 ORDER BY buyprice DESC
4 LIMIT 10;
It doesn’t work because the SELECT statement with the SUM function returns one row, and
the LIMIT clause constrains the number of rows to return i.e., 3.
23 of 142
3 FROM products
4 ORDER BY buyprice DESC
5 LIMIT 10) price;
How it works.
The subquery selects the top 10 most expensive products based on the buy prices.
The outer query calculates the sum of the buy prices of the top 10 expensive products returned from
the subquery.
For example, to calculate the sum of amount of the cancelled orders, you use the following statement:
24 of 142
In this tutorial, you have learned how to use the MySQL SUM function to calculate the sum of a set of
values.
1 MIN(DISTINCT expression);
If you specify the DISTINCT operator, the MIN function returns the minimum value of distinct values,
which is the same as omitting the DISTINCT In other words, the DISTINCT operator does not have any
effect to the MIN function. It is just for ISO compatibility.
Notice that the DISTINCT operator takes effect in other aggregate functions such
as SUM, AVG and COUNT.
To get the cheapest product in the products table, which is the product that has the lowest buy price, you
use the following query:
1 SELECT
2 MIN(buyPrice)
25 of 142
3 FROM
4 products;
1 SELECT
2 productCode, productName, buyPrice
3 FROM
4 products
5 WHERE
6 buyPrice = (
7 SELECT
8 MIN(buyPrice)
9 FROM
10 products);
How it works.
The subquery returns the lowest buy price product in the products table.
The outer query selects the product whose buy price is equal to the lowest price returned from the
subquery.
1 SELECT
2 productline, MIN(buyprice)
3 FROM
4 products
5 GROUP BY productline;
26 of 142
If you want to select not only the product line but also other columns in the products table such as
product code and product name, you need to use a correlated subquery.
1 SELECT
2 productline, productCode, productName, buyprice
3 FROM
4 products a
5 WHERE
6 buyprice = (
7 SELECT
8 MIN(buyprice)
9 FROM
10 products b
11 WHERE
12 b.productline = a.productline);
For each product line from the outer query, the correlated subquery selects the lowest price product in the
product line and returns the lowest price. The returned lowest price is then used as the input for the outer
query to select the related product data including product line, product code, product name and buy price.
If you want to achieve the same result without using the MIN function and a subquery, you can use a self
join with a LEFT JOIN clause as the following query:
27 of 142
1 SELECT
2 a.productline, a.productCode, a.productName, a.buyprice
3 FROM
4 products a
5 LEFT JOIN
6 products b ON a.productline = b.productline
7 AND b.buyprice < a.buyprice
8 WHERE
9 b.productcode IS NULL;
In this tutorial, you have learned how to use the MySQL MIN function to find the minimum value in a set of
values.
1 MAX(DISTINCT expression)
If you add the DISTINCT operator, the MAX function returns the maximum value of distinct values, which is
the same as the maximum value of all values. It means the DISTINCT operator does not take any effects
in the MAX function.
Notice that DISTINCT operator takes effect in other aggregate functions such as COUNT, SUM, and AVG.
To get the largest payment in the payments table, you use the following query:
28 of 142
1 SELECT
2 MAX(amount)
3 FROM
4 payments;
1 SELECT
2 *
3 FROM
4 payments
5 WHERE
6 amount = (
7 SELECT
8 MAX(amount)
9 FROM
10 payments);
How it works.
The outer query gets the payment whose amount is equal to the largest amount returned from the
subquery and also other related payment’s information.
Another way to do this without using the MAX function is to sort the result set in descending order using
the ORDER BY clause and get the first row using the LIMIT clause as the following query:
1 SELECT
2 *
3 FROM
4 payments
5 ORDER BY amount DESC
6 LIMIT 1;
If you don’t index the amount column, the second query executes faster because it examines all rows in
the payments table, while the first query examines all the rows in the payments table twice, one in the
29 of 142
subquery and one in the outer query. However, if the amount column is indexed, the first query will
perform faster.
1 SELECT
2 customerNumber, MAX(amount)
3 FROM
4 payments
5 GROUP BY customerNumber
6 ORDER BY MAX(amount);
For example, the following query finds the largest payment of each customer; and based on the returned
payments, get only payments whose amounts are greater than 80000 .
1 SELECT
2 customerNumber, MAX(amount)
3 FROM
4 payments
5 GROUP BY customerNumber
6 HAVING MAX(amount) > 80000;
30 of 142
In this tutorial, we have shown you how to use the MySQL MAX function to find the maximum value in a set
of values.
1 GROUP_CONCAT(DISTINCT expression
2 ORDER BY expression
3 SEPARATOR sep);
The following is an example that demonstrates how the GROUP_CONCAT function works.
1 CREATE TABLE t (
2 v CHAR
3 );
4
5 INSERT INTO t(v) VALUES('A'),('B'),('C'),('B');
6
7 SELECT
8 GROUP_CONCAT(DISTINCT v
9 ORDER BY v ASC
10 SEPARATOR ';')
11 FROM
12 t;
31 of 142
The DISTINCT clause allows you to eliminate duplicate values in the group before concatenating them.
The ORDER BY clause allows you to sort the values in ascending or descending order before
concatenating. By default, it sorts the values in ascending order. If you want to sort the values in the
descending order, you need to specify explicitly the DESC option.
The SEPARATOR specifies a literal value inserted between values in the group. If you do not specify a
separator, the GROUP_CONCAT function uses a comma (,) as the default separator.
The GROUP_CONCAT function ignores NULL values. It returns NULL if there was no matching row found or
all arguments are NULL values.
The GROUP_CONCAT function returns a binary or non-binary string, which depends on the arguments. by
default, the maximum length of the return string is 1024. In case you need more than this, you can extend
the maximum length by setting the group_concat_max_len system variable at SESSION or GLOBAL level.
32 of 142
To get all countries where customers locate as a comma-separated string, you use
the GROUP_CONCAT function as follows:
1 SELECT
2 GROUP_CONCAT(country)
3 FROM
4 customers;
However, some customers locate in the same country. To remove the duplicate country’s names, you add
the DISTINCT clause as the following query:
1 SELECT
2 GROUP_CONCAT(DISTINCT country)
3 FROM
4 customers;
It is more readable if the country’s names are in ascending order. To sort the country’s name before
concatenating, you use the ORDER BY clause as follows:
33 of 142
1 SELECT
2 GROUP_CONCAT(DISTINCT country
3 ORDER BY country)
4 FROM
5 customers;
To change the default separator of the returned string from a comma (,) to a semi-colon (;), you use
the SEPARATOR clause as the following query:
1 SELECT
2 GROUP_CONCAT(DISTINCT country
3 ORDER BY country
4 SEPARATOR ';')
5 FROM
6 customers;
Great! now you know how the GROUP_CONCAT function works. Let’s put it in a practical example.
Each customer has one or more sale representatives. In other words, each sales employee is in charge of
one or more customers. To find out who in charge of which customers, you use the inner join clause as
follows:
1 SELECT
2 employeeNumber, firstname, lastname, customername
3 FROM
4 employees
5 INNER JOIN
6 customers ON customers.salesRepEmployeeNumber = employees.employeeNumber
7 ORDER BY firstname , lastname;
34 of 142
Now, we can group the result set by the employee number and concatenate all employees that are being
in charge of the employee by using the GROUP_CONCAT function as follows:
1 SELECT
2 employeeNumber,
3 firstName,
4 lastName,
5 GROUP_CONCAT(DISTINCT customername
6 ORDER BY customerName)
7 FROM
8 employees
9 INNER JOIN
10 customers ON customers.salesRepEmployeeNumber = employeeNumber
11 GROUP BY employeeNumber
12 ORDER BY firstName , lastname;
35 of 142
The result set is much easier to read.
First, you concatenate the last name and first name of each customer’s contact using
the CONCAT_WS function. The result is contact’s full name.
1 SELECT
2 GROUP_CONCAT(CONCAT_WS(', ', contactLastName, contactFirstName)
3 SEPARATOR ';')
4 FROM
5 customers;
Note that GROUP_CONCAT function concatenates string values in different rows while
the CONCAT_WS or CONCAT function concatenates two or more string values in different columns.
For example, the GROUP_CONCAT function returns the result of values: 1 2 , and 3 as the ‘1,2,3’ string.
If you supply this result to the IN operator, the query is not working.therefore, the query may not return
any result. For example, the following query will not work as desired.
Because, the IN operator accepts a list of values e.g., (1,2,3) not a string that consists of a list of values
(‘1,2,3’). As the result, the following query will not work as expected.
1 SELECT
2 id, name
3 FROM
4 table_name
5 WHERE
6 id IN GROUP_CONCAT(id);
36 of 142
Because the GROUP_CONCAT function is an aggregate function, tTo sort the values, you must use
the ORDER BY clause inside the function, not in the ORDER BY in the SELECT statement.
The following example demonstrates the incorrect usage of the ORDER BY clause in the context of using
the GROUP_CONCAT function:
1 SELECT
2 GROUP_CONCAT(DISTINCT country
3 SEPARATOR ';')
4 FROM
5 customers
6 ORDER BY country;
The SELECT clause returns one string value so the ORDER BY clause does not take any effect in this
statement.
Create tags for blog posts, articles or products e.g., ‘mysql, mysql aggregate function, mysql
tutorial’.
In this tutorial, we have introduced you to MySQL GROUP_CONCAT function that concatenates non-
NULL values from a group of strings into a string with various options.
References
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat – MySQL
GROUP_CONCAT function.
A low standard deviation shows that the values in the data set are close to the mean. And the high
standard deviation indicates that the values of the dataset are spread out over a large range of values.
37 of 142
A standard deviation is a square root of the variance, which can be calculated by using the following
steps:
Step 1. Calculate the average of all values in the data set to get the average or mean e.g., suppose
the data set consists of 1, 2 and 3, the mean is (1+2+3)/3 = 2.
Step 2. Compute the difference of the value from the mean for each value, and square the result of
each e.g., (1-2)2= (-1)2 = 1, (2-2)2 = (0)2 = 0, (3-2)2 = (1)2 = 1.
Step 3. Calculate the average values in step 2, which produces the variance. And then take a
square root of the variance to get the standard deviation of all values in the data set e.g., square
root of ((1 + 0 + 1)/3) = 0.816497
A sigma letter (σ) represents the standard deviation. The following equations illustrate how to calculate
population standard deviation and sample standard deviation:
The calculation of population standard deviation and sample standard deviation is slightly different. When
calculating the variance of sample standard deviation, divide by N-1 instead of N, where N is the number
of values in the data set.
To calculate population standard deviation, you use one of the following functions:
38 of 142
STD(expression) – returns population standard deviation of the expression. The STD function
returns NULL if there was no matching row.
To calculate the sample standard deviation, you use the STDDEV_SAMP (expression) function.
MySQL also provides some functions for population variance and sample variance calculation:
1 SELECT customerNumber,
2 COUNT(*) orderCount
3 FROM orders
4 WHERE status = 'Shipped'
5 GROUP BY customerNumber;
39 of 142
Second, the following statement calculates the population standard deviation of the number of orders of
the customers:
1 SELECT FORMAT(STD(orderCount),2)
2 FROM (SELECT customerNumber, count(*) orderCount
3 FROM orders
4 GROUP BY customerNumber) t;
Notice that the FORMAT function is used for formatting the result of the STD function.
First, the following query returns the customer numbers and their number of the shipped orders:
Second, the following query uses the STDDEV_SAMP function to calculate the sample standard
deviation:
1 SELECT FORMAT(STDDEV_SAMP(orderCount),2)
2 FROM (SELECT customerNumber, count(*) orderCount
3 FROM orders
4 WHERE status = 'Shipped'
5 GROUP BY customerNumber) t;
In this tutorial, we have introduced you to standard deviation. Then, we showed you how to use the
MySQL standard deviation functions to calculate population standard deviation and sample standard
deviation of an expression.
40 of 142
B. MySQL string functions
CONCAT – combine two or more strings into one string.
LENGTH & CHAR_LENGTH – get the length of strings in bytes and in characters.
FORMAT – format a number with a specific locale, rounded to the number of decimals
To concatenate two or more quoted string values, you place the string next to each other as the following
syntax:
MySQL string concatenation is cleaner in comparison with other database management systems. For
example, if you use PostgreSQL or Oracle, you have to use the string concatenation operator ||. In
Microsoft SQL server, you use the addition arithmetic operator (+) to concatenate string values.
Besides using spaces for string concatenation, MySQL provides two other functions that concatenate
string values: CONCAT and CONCAT_WS .
1 CONCAT(string1,string2, ... );
41 of 142
The CONCAT function converts all arguments to the string type before concatenating. If any argument
is NULL , the CONCAT function returns a NULL value.
The following statement concatenates two quoted strings: MySQL and CONCAT .
1 SELECT CONCAT('MySQL','CONCAT');
If you add a NULL value, the CONCAT function returns a NULL value as follows:
1 SELECT CONCAT('MySQL',NULL,'CONCAT');
To get the full names of contacts, you use the CONCAT function to concatenate first name, space, last
name as the following statement:
1 SELECT
2 concat(contactFirstName,' ',contactLastName) Fullname
3 FROM
4 customers;
42 of 142
MySQL CONCAT_WS function: Concatenate strings with a
separator
MySQL provides a special form of the CONCAT function: CONCAT_WS function. The CONCAT_WS function
concatenates two or more string values with a predefined separator.
1 CONCAT_WS(seperator,string1,string2, ... );
The first argument is the separator for other arguments: string1, string2, …
The CONCAT_WS function adds the separator between string arguments and returns a single string with the
separator inserted between string arguments.
The following statement concatenates two string values: John and Doe, and separates these two strings
by a comma:
1 SELECT CONCAT_WS(',','John','Doe');
The CONCAT_WS function returns NULL if and only if the first argument, which is the separator, is NULL .
See the following example:
43 of 142
Unlike the CONCAT function, the CONCAT_WS function skips NULL values after the separator argument. In
other words, it ignores NULL values.
The following statement constructs complete addresses using the CONCAT_WS function:
1 SELECT
2 CONCAT_WS(CHAR(13),
3 CONCAT_WS(' ', contactLastname, contactFirstname),
4 addressLine1,
5 addressLine2,
6 CONCAT_WS(' ', postalCode, city),
7 country,
8 CONCAT_WS(CHAR(13), '')) AS Customer_Address
9 FROM
10 customers;
In this tutorial, you have learned how to use MySQL CONCAT and CONCAT_WS functions to concatenate one
or more string value into a single string.
MySQL supports various character sets such as latin1 , utf8 , etc. You use the SHOW CHARACTER
SET statement to get all character sets supported by MySQL database server.
44 of 142
1 SHOW CHARACTER SET;
The Maxlen column stores the number of bytes for character sets. In MySQL, a string can be in any
character set. If a string contains 1-byte characters, its length measured in characters and its length
measured in bytes are equal. However, if a string contains multi-byte characters, its length in bytes is
typically greater than its length in characters.
To get the length of a string measured in bytes, you use the LENGTH function as follows:
1 LENGTH(str);
You use the CHAR_LENGTH function to get the length of a string measured in characters as follows:
1 CHAR_LENGTH(str);
45 of 142
How it works.
First, we convert the MySQL String Length string into ucs2 character set, which is UCS-
2 Unicode that holds 2-byte characters.
Second, we use the CHAR_LENGTH and LENGTH functions to get the length of the @s string in bytes
and in characters. Because the @s string contains 2-byte characters, its length in character is 19,
while its length in bytes is 38.
The following statements demonstrate how the LENGTH and CHAR_LENGTH functions that work with 1-byte
characters:
We use the latin1 character set for the @s string. The latin1 character set contains 1-byte characters;
therefore, its length in bytes and its length in character are equal.
Notice that some character sets hold characters whose number of bytes can be varied e.g., for
the utf8 character set:
The CHAR_LENGTH and LENGTH returns the same result. However, if a string has special characters, the
result is different. See the following example:
46 of 142
An application of MySQL string length functions
Suppose we have a posts table that stores blog posts with four
columns postid , title , excerpt and content . (We make the posts table as simple as possible for the
demonstration purpose).
First, we create the posts table by using the CREATE TABLE statement:
Second, we insert some blog posts into the posts table by using the INSERT statement:
We can use the CHAR_LENGTH function to check if the except has more than 20 characters, we append
an ellipsis (…) to the excerpt as the following query:
1 SELECT postid,
2 title,
3 IF(CHAR_LENGTH(excerpt) > 20,
4 CONCAT(LEFT(excerpt,20), '...'),
5 excerpt) summary
6 FROM posts;
In the SELECT statement, we use the IF function to check if the length of the excerpt column is greater
than 20, we concatenate the excerpt with the ellipsis (…) by using the CONCAT statement, otherwise we
just get the excerpt .
In this tutorial, we have shown you how to use MySQL string length functions to get the length of a string
in bytes and in characters.
Reference
47 of 142
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_length – MySQL LENGTH
function
http://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_char-length – MySQL
CHAR_LENGTH function
1 LEFT(str,length);
1. The str is the string that you want to extract the substring.
2. The length is a positive integer that specifies the number of characters will be returned.
The LEFT function returns the leftmost length characters from the str string. It returns a NULL value if
either str or length argument is NULL .
If the length is zero or negative, the LEFT function returns an empty string. If the length is greater than
the length of the str string, the LEFT function returns the entire str string.
Notice that the SUBSTRING (or SUBSTR) function also provides the same functionality as
the LEFT function.
48 of 142
The following statement returns the entire string because the length exceeds the length of the string.
The following statements return an empty string because the length is zero or negative.
The following statement returns a NULL value because the length is NULL
Suppose you want to display the product name and product description on a catalog. The product
description is long, therefore, you want to take just the first 50 characters for displaying.
49 of 142
The following statement uses the LEFT function to return the first 50 characters of the product description.
1 SELECT
2 productname, LEFT(productDescription, 50) summary
3 FROM
4 products;
The LEFT function returns the first 50 characters. It does not care about words.
You want to get the first 50 characters without cutting the word in the middle. To achieve this, you use the
following steps:
1 SELECT
2 LEFT(productdescription, 50)
3 FROM
4 products;
1 SELECT
2 REVERSE(LEFT(productdescription, 50))
3 FROM
4 products;
3) Get the first space’s position in the reversed substring using the LOCATE function.
1 SELECT
2 LOCATE(' ',REVERSE(LEFT(productdescription, 50))) first_space_pos
3 FROM
4 products;
50 of 142
4) Minus 1 from the position. In case you don’t find any space, keep the position zero.
1 SELECT
2 IFNULL(NULLIF(LOCATE(' ', REVERSE(LEFT(productDescription, 50))), 0) - 1, 0)
3 FROM
4 products;
5) Minus the position from the 50, you got the position. Let’s call it as last_space_pos.
1 SELECT
2 productDescription,
3 (50 - IFNULL(NULLIF(LOCATE(' ', REVERSE(LEFT(productDescription, 50))), 0) - 1, 0)) last_space_pos
4 FROM
5 products;
SELECT
1
productDescription, LEFT(productDescription, last_space_pos)
2
FROM
3
(SELECT
4
productDescription,
5
(50 - IFNULL(NULLIF(LOCATE(' ', REVERSE(LEFT(productDescription, 50))), 0) - 1, 0)) last_space_pos
6
FROM
7
products) AS t;
8
In this tutorial, you have learned how to use the LEFT function to return the left part of a string with a
specified length.
51 of 142
Introduction to MySQL REPLACE string function
MySQL provides you with a useful string function called REPLACE that allows you to replace a string in a
column of a table by a new string.
1 REPLACE(str,old_string,new_string);
The REPLACE function has three parameters. It replaces the old_string by the new_string in
the string
Notice there is a statement also called REPLACE used to insert or update data. You should not confuse
the REPLACE statement with the REPLACE string function.
The REPLACE function is very handy to search and replace text in a table such as updating obsolete URL,
correcting a spelling mistake, etc.
1 UPDATE tbl_name
2 SET
3 field_name = REPLACE(field_name,
4 string_to_find,
5 string_to_replace)
6 WHERE
7 conditions;
Note that when searching for text to replace, MySQL uses the case-sensitive match to perform a search
for a string to be replaced.
1 UPDATE products
2 SET
3 productDescription = REPLACE(productDescription,
4 'abuot',
5 'about');
The query finds all occurrences of a spelling mistake abuot and replaces it by the correct word about
in the productDescription column of the products table.
It is very important to note that in the REPLACE function, the first parameter is the column name without
quotes (“). If you put the quotes to the field name like “field_name”, the query will update the content of
that column to “field_name”, which is causing unexpected data loss.
52 of 142
The REPLACE function does not support regular expression so if you need to replace a text string by a
pattern you need to use MySQL user-defined function (UDF) from external library, check it out
here MySQL UDF with Regex
The SUBSTRING function returns a substring with a given length from a string starting at a specific position.
We will examine each form of the SUBSTRING function in the following sections.
1 SUBSTRING(string,position);
2 SUBSTRING(string FROM position);
1. The string argument is the string that you extract the substring.
2. The position argument is an integer that specifies the starting character of the substring. The
position can be a positive or negative integer.
If the position is positive, the SUBSTRING function extracts the substring from the start of the string. See
the following string.
For example, to get the ” SUBSTRING ” out of the ” MySQL SUBSTRING ” string, the position of the substring
must be 7 as the following SELECT statement:
If the position is negative, the SUBSTRING function extracts the substring from the end of the string. See
the following ” MYSQL SUBSTRING ” string:
53 of 142
To get the ” SUBSTRING ” out of the ” MySQL SUBSTRING ” using a negative position, you must pass -10 to
the position argument as follows:
Notice that if the position is zero, the SUBSTRING function returns an empty string:
Besides the MySQL-specific syntax, you can use SQL-standard syntax with the FROM keyword to call
the SUBSTRING function.
For example, the following statement gets the SUBSTRING from the MySQL SUBSTRING string using the
SQL-standard syntax:
1 SUBSTRING(string,position,length);
The following is the SQL-standard version of above statement, which is longer but more expressive.
Besides the string and position arguments, the SUBSTRING function has an additional length argument.
The length is a positive integer that specifies the number of characters of the substring.
If the sum of position and length is greater than the number of characters of the string,
the SUBSTRING function returns a substring starting from the position to the end of the string.
For example, to get the ” MySQL ” from the ” MySQL SUBSTRING “, you use the following statement:
54 of 142
1 SELECT SUBSTRING('MySQL SUBSTRING',1,5);
Or
In case you want to use the negative position, you use the following statement:
The SUBSTR() is the synonym for the SUBSTRING() so you can use both of them interchangeably.
In this tutorial, you have learned about the SUBSTRING function that extracts a substring with a given
length from a string starting at a specific position.
To keep the data in the correct format, before inserting or updating data in the database, you need to
clean it up. One of the most important tasks in data cleansing is to remove the unwanted leading and
trailing characters.
MySQL provides a very useful string function named TRIM to help you clean up the data. The following
illustrates the syntax of the TRIM function.
55 of 142
The TRIM function provides a number of options
You can use the LEADING , TRAILING , or BOTH option to explicitly instruct the TRIM function to remove
leading, trailing, or both leading and trailing unwanted characters from a string.
If you don’t specify anything, the TRIM function uses the BOTH option by default.
The [removed_str] is the string that you want to remove. By default, it is a space. It means that if you
don’t specify a specific string, the TRIM function removes spaces only.
The TRIM function returns a string that has unwanted characters removed.
The following statements remove the newline characters at the end of a string.
1 SELECT
56 of 142
2 TRIM(TRAILING '\n' FROM field_name)
3 FROM table_name;
1 SELECT
2 TRIM(TRAILING '\r' FROM field_name)
3 FROM table_name;
1 SELECT
2 TRIM(TRAILING '\r\n' FROM field_name)
3 FROM table_name;
Note that based on the platform, the new line could be \n (Unix or Linux), \r (Mac), or both (\r\n).
In case the data already in the database and you want to clean up the spaces or any other unwanted
characters, you can use the TRIM function in the UPDATE statement.
We will take the products table in the sample database for the demonstration.
The following statement removes all spaces of the product names in the products table.
1 UPDATE products
2 SET
3 productname = TRIM(productname);
Notice that the TRIM function only removes the unwanted leading and/ or trailing characters from a string.
If you want to remove the unwanted characters in the middle of a string, you should use
the REPLACE function instead.
The following statement uses the LTRIM function to remove the leading spaces of a string.
57 of 142
1 SELECT LTRIM(' MySQL LTRIM function');
The following statement uses the RTRIM function to remove the trailing spaces of a string.
In this tutorial, you have learned how to use the TRIM function to remove the unwanted leading and
trailing characters from a string.
1 FIND_IN_SET(needle,haystack);
The first parameter needle is the string that you want to find.
The FIND_IN_SET function returns an integer or a NULL value depending on the value of the arguments:
Return zero if the needle is not in the haystack or the haystack is an empty string.
58 of 142
Note that the function will not work properly if the needle contains a comma (,). In addition, MySQL will
use bit arithmetic optimization if the needle is a constant string and the haystack is a column of type
SET.
1 SELECT FIND_IN_SET('y','x,y,z'); -- 2
1 SELECT FIND_IN_SET('a','x,y,z');
The following statement also returns 0 because the second argument is an empty string.
1 SELECT FIND_IN_SET('a','');
The following statement returns NULL because the first argument is NULL.
1 SELECT FIND_IN_SET(NULL,'x,y,z');
The following statement also returns NULL because the second argument is NULL.
1 SELECT FIND_IN_SET('a',NULL);
Third, to find the division that accepts red belt, you can use the FIND_IN_SET function as follows:
1 SELECT
2 name, belts
3 FROM
4 divisions
5 WHERE
6 FIND_IN_SET('red', belts);
For example, to find the divisions that do not accept black belt, you use the following statement:
1 SELECT
2 name, belts
3 FROM
4 divisions
5 WHERE
6 NOT FIND_IN_SET('black', belts);
60 of 142
MySQL FIND_IN_SET function vs. IN operator
The IN operator determines whether a value matches a list of values. For example, to find the division
whose name is O-1 or O-2 , you use the IN operator as follows.
1 SELECT
2 name, belts
3 FROM
4 divisions
5 WHERE
6 name IN ('O-1' , 'O-2');
You can achieve the same result with the FIND_IN_SET function as the following query:
1 SELECT
2 name, belts
3 FROM
4 divisions
5 WHERE
6 FIND_IN_SET(name, 'O-1,O-2');
You use the IN operator when you want to match a value with a list of values in the database. And you
use the FIND_IN_SET function when you want to match a value with a comma-separated list of values
stored in the database.
In this tutorial, you have learned how to use the FIND_IN_SET function to find a string in a comma-
separated list of strings.
61 of 142
MySQL FORMAT Function
Summary: this tutorial shows you how to use the MySQL FORMAT function to format decimal numbers in
various locales.
The result of the expression is a decimal with many decimal places. To format those numbers, you use
the FORMAT function with the following syntax:
1 FOMRAT(N,D,locale);
The FORMAT function formats the number N to format like ‘#,###,###.##’, rounds to D decimal places. It
returns a value as a string.
The following statement uses the FORMAT function with the second argument zero, therefore, the result
does not have any decimal places.
62 of 142
The following statement uses the de_DE locale instead of the en_US locale:
As you see in the result, the de_DE locale use dot (.) for grouping thousand and comma (,) for decimal
mark.
To calculate the stock value of each product, you multiply the quantity in stock and buy price as follows:
1 SELECT
2 productname, quantityInStock * buyPrice stock_value
3 FROM
4 products;
63 of 142
The result does not look good because there are many decimal places.
To make it better, you can combine two functions: FORMAT & CONCAT. The FORMAT function formats
the stock value rounded to 2 decimal places. And the CONCAT function adds the USD symbol ($) at the
beginning of the stock value string:
1 SELECT
2 productname,
3 CONCAT('$',
4 FORMAT(quantityInStock * buyPrice, 2)) stock_value
5 FROM
6 products;
Notice that the FORMAT function returns a string value. It means that if you want to sort the results of the
FORMAT function using the ORDER BY clause, MySQL will sort the results using string-based not
numeric-based.
64 of 142
For example, the following statement sorts the stock values alphabetically.
1 SELECT
2 productname,
3 CONCAT('$',
4 FORMAT(quantityInStock * buyPrice, 2)) stock_value
5 FROM
6 products
7 ORDER BY stock_value;
To sort the stock values numerically, you put the expression in the ORDER BY clause as follows:
1 SELECT
2 productname,
3 CONCAT('$',
4 FORMAT(quantityInStock * buyPrice, 2)) stock_value
5 FROM
6 products
7 ORDER BY quantityInStock * buyPrice;
65 of 142
In this tutorial, we have shown you how to use the MySQL FORMAT function to format a number in
various locale names.
IFNULL – return the first argument if it is not NULL , otherwise returns the second argument.
NULLIF – return NULL if the first argument is equal to the second argument, otherwise, returns the
first argument.
1 CASE value
2 WHEN compare_value_1 THEN result_1
3 WHEN compare_value_2 THEN result_2
4…
5 ELSE result END
1 CASE
2 WHEN condition_1 THEN result_1
3 WHEN condition_2 THEN result_2
4…
5 ELSE result END
In the second form, the CASE expression returns the result such as result_1 , result_2 , etc., if the
condition is true. If all conditions are false, then the result in the ELSE part is returned. If the ELSE part is
omitted, the CASE expression returns NULL .
66 of 142
The CASE expression returns the result whose data type depends on the context where it is used. For
example, if the CASE expression is used in string context, it returns the result as a string. If
the CASE expression is used in a numeric context, it returns the result as an integer, a decimal, or a real
value.
Suppose you want to sort the customers by state, and if the state is NULL , you want to use the country as
the sorting criterion instead. To achieve this, you can use the first form of the CASE expression as follows:
1 SELECT
2 customerName, state, country
3 FROM
4 customers
5 ORDER BY (CASE
6 WHEN state IS NULL THEN country
7 ELSE state
8 END);
67 of 142
In this example, we used the CASE expression in the ORDER BY clause to determine the field, state or
country, which we want to sort.
In the next example, we will use the orders table in the sample database to demonstrate the second form
of the CASE expression.
If you want to see the number of sales orders by their statuses e.g., the number of shipped orders, on-
hold orders, etc., you can use the second form of the CASE expression as follows:
1 SELECT
2 SUM(CASE
3 WHEN status = 'Shipped' THEN 1
4 ELSE 0
5 END) AS 'Shipped',
6 SUM(CASE
7 WHEN status = 'On Hold' THEN 1
8 ELSE 0
9 END) AS 'On Hold',
10 SUM(CASE
11 WHEN status = 'In Process' THEN 1
12 ELSE 0
13 END) AS 'In Process',
14 SUM(CASE
15 WHEN status = 'Resolved' THEN 1
16 ELSE 0
17 END) AS 'Resolved',
18 SUM(CASE
68 of 142
19 WHEN status = 'Cancelled' THEN 1
20 ELSE 0
21 END) AS 'Cancelled',
22 SUM(CASE
23 WHEN status = 'Disputed' THEN 1
24 ELSE 0
25 END) AS 'Disputed',
26 COUNT(*) AS Total
27 FROM
28 orders;
In the SELECT statement, if the status is equal to shipped , on hold , etc., the CASE expression returns
1, otherwise, it returns 0. We used the SUM function to calculate the total of the sales orders for each
status.
In this tutorial, we have shown you how to use the MySQL CASE expression in SELECT statements to
construct conditional queries.
MySQL IF Statement
Summary: in this tutorial, you will learn how to use MySQL IF statement to execute a block of SQL code
based on conditions.
The MySQL IF statement allows you to execute a set of SQL statements based on a certain condition or
value of an expression. To form an expression in MySQL, you can combine literals, variables, operators,
and even functions. An expression can return one of three values TRUE FALSE , or NULL .
Note that there is an IF function that is different from the IF statement specified in this tutorial.
If the expression evaluates to TRUE , then the statements will be executed, otherwise, the control is
passed to the next statement following the END IF .
69 of 142
MySQL IF ELSE statement
In case you want to execute statements when the expression evaluates to FALSE , you use the IF ELSE
statement as follows:
1 IF expression THEN
2 statements;
3 ELSE
4 else-statements;
5 END IF;
70 of 142
MySQL IF ELSEIF ELSE statement
If you want to execute statements conditionally based on multiple expressions, you use the IF ELSEIF
ELSE statement as follows:
1 IF expression THEN
2 statements;
3 ELSEIF elseif-expression THEN
4 elseif-statements;
5 ...
6 ELSE
7 else-statements;
8 END IF;
The IF statement may have multiple ELSEIF branches to check multiple expressions. If no expression
evaluates to TRUE , the else-statements in the ELSE branch will execute.
71 of 142
First, it gets the credit limit from the customers table.
Then, based on the credit limit, it determines the customer level: PLATINUM , GOLD , and SILVER .
The parameter p_customerlevel stores the level of the customer and is used by the calling program.
1 DELIMITER $$
2
3 CREATE PROCEDURE GetCustomerLevel(
4 in p_customerNumber int(11),
5 out p_customerLevel varchar(10))
6 BEGIN
7 DECLARE creditlim double;
8
9 SELECT creditlimit INTO creditlim
10 FROM customers
11 WHERE customerNumber = p_customerNumber;
12
13 IF creditlim > 50000 THEN
14 SET p_customerLevel = 'PLATINUM';
15 ELSEIF (creditlim <= 50000 AND creditlim >= 10000) THEN
16 SET p_customerLevel = 'GOLD';
17 ELSEIF creditlim < 10000 THEN
18 SET p_customerLevel = 'SILVER';
19 END IF;
20
21 END$$
72 of 142
In this tutorial, you have learned how to use MySQL IF statement to execute a block of SQL code based
on conditions.
MySQL IFNULL
Summary: in this tutorial, you will learn about the MySQL IFNULL function, which is a very handy control
flow function to handle NULL values.
1 IFNULL(expression_1,expression_2);
73 of 142
The IFNULL function returns expression_1 if expression_1 is not NULL ; otherwise, it
returns expression_2 . The
The IFNULL function returns a string or a numeric based on the context where it is used.
If you want to return a value based on TRUE or FALSE condition other than NULL , you should use the IF
function.
How it works.
IFNULL(' ',1) returns ' ' because the ' ' string is not NULL .
IFNULL(NULL,'IFNULL function') returns IFNULL function string because the first argument
is NULL .
First, create a new table named contacts using the following statement:
74 of 142
3 ('Cindy Smith',NULL,'(541) 754-3110'),
4 ('Sue Greenspan','(541) 754-3010','(541) 754-3011'),
5 ('Lily Bush',NULL,'(541) 754-3111');
Some contacts have only home phone or business phone. To get all the contact name and phone from
the contacts table, you use the following query:
1 SELECT
2 contactName, bizphone, homephone
3 FROM
4 contacts;
It would be nice if we can get the contact’s home phone if the contact’s business phone is not available.
This is where the
This is where the IFNULL function comes to play. The IFNULL function returns the home phone if the
business phone is NULL .
Third, use the following query to get the names and phones of all the contacts:
1 SELECT
2 contactname, IFNULL(bizphone, homephone) phone
3 FROM
4 contacts;
Notice that you should avoid using the IFNULL function in the WHERE clause, because it degrades the
performance of the query. If you want to check if a value is
If you want to check if a value is NULL or not, you can use IS NULL or IS NOT NULL in the WHERE clause.
In this tutorial, we have introduced you to MySQL IFNULL function and shown you how to use
the IFNULL function in the queries.
75 of 142
MySQL NULLIF
Summary: in this tutorial, you will learn about the MySQL NULLIF function and how to use it to prevent
the division by zero error in a query.
1 NULLIF(expression_1,expression_2);
Notice that the NULLIF function is similar to the following expression that uses the CASE expression:
Note that you should not confuse the NULLIF function a similar function called IFNULL function.
76 of 142
NULIF(1,1) returns NULL because 1 is equal 1.
string
NULLIF('MySQL NULLIF','MySQL NULLIF') returns MySQL NULLIF because two strings are not
equal.
NULLIF(1,NULL) returns 1 because 1 is not equal to NULL
NULLIF(NULL,1) return the first argument i.e., NULL , because NULL is not equal to 1.
In this case, you can use the NULLIF function to prevent the division by zero as follows:
Because zero is equal to zero, the expression NULLIF(0,0) returns NULL. As the result, the statement
returns NULL.
First, to get all orders created in June 2003, you use the following query:
77 of 142
1 SELECT
2 orderNumber, orderdate, requiredDate, shippedDate, status
3 FROM
4 orders
5 WHERE
6 orderDate BETWEEN '2003-06-01' AND '2003-06-30';
Second, calculate the number of shipped orders / the number of cancelled orders in June 2003, you use
the SUM and IF functions.
MySQL issues an error because in June 2003 there was no cancelled order created. It means that
expression SUM(IF(status = 'Cancelled',1,0)) returns zero.
Third, to prevent the division by zero error, you use the NULLIF function as the following query:
1 SELECT
2 SUM(IF(status = 'Shipped', 1, 0)) /
3 NULLIF(SUM(IF(status = 'Cancelled', 1, 0)), 0)
4 FROM
5 orders
6 WHERE
7 orderDate BETWEEN '2003-06-01' AND '2003-06-30';
78 of 142
Because there was no cancelled order created in June 2003, the SUM(IF(status =
'Cancelled',1,0) expression returns zero, which also makes the NULLIF(SUM(IF(status =
'Cancelled',1,0),0) expression returns a NULL value.
In this tutorial, we have introduced you to NULLIF function, which is very handy in some cases such as
preventing division by zero error in queries.
79 of 142
The following example shows how the CURDATE() function is used in the string context.
And the following example illustrates how the CURDATE() function is used in a numeric context:
In this tutorial, you have learned how to use the MySQL CURDATE() function to get the current date value.
80 of 142
Introduction to MySQL DATEDIFF function
The MySQL DATEDIFF function calculates the number of days between two DATE , DATETIME , or
TIMESTAMP values.
1 DATEDIFF(date_expression_1,date_expression_2);
The DATEDIFF function accepts two arguments that can be any valid date or date-time values. If you
pass DATETIME or TIMESTAMP values, the DATEDIFF function only takes the date parts for calculation and
ignores the time parts.
The DATEDIFF function is useful in many cases e.g., you can calculate an interval in days that the
products need to ship to a customer.
To calculate the number of days between the required date and shipped date of the orders, you use
the DATEDIFF function as follows:
1 SELECT
2 orderNumber,
3 DATEDIFF(requiredDate, shippedDate) daysLeft
4 FROM
5 orders
6 ORDER BY daysLeft DESC;
81 of 142
The following statement gets all orders whose statuses are in-process and calculates the number of days
between ordered date and required date:
1 SELECT
2 orderNumber,
3 DATEDIFF(requiredDate, orderDate) remaining_days
4 FROM
5 orders
6 WHERE
7 status = 'In Process'
8 ORDER BY remaining_days;
For calculating an interval in week or month, you can divide the returned value of the DATEDIFF function
by 7 or 30 as the following query:
1 SELECT
2 orderNumber,
3 ROUND(DATEDIFF(requiredDate, orderDate) / 7, 2),
4 ROUND(DATEDIFF(requiredDate, orderDate) / 30,2)
5 FROM
6 orders
7 WHERE
8 status = 'In Process';
82 of 142
Note that the ROUND function is used to round the results.
In this tutorial, you have learned how to use MySQL DATEDIFF function to calculate the number of days
between two date values.
1 DAY(date);
The DAY function accepts one argument that is a date value for which you want to get the day of the
month. If the date argument is zero e.g., '0000-00-00' , the DAY function returns 0. In case the date
is NULL , the DAY function returns NULL .
To get the number of days in a month based on a specified date, you combine
the LAST_DAY and DAY functions as shown in the following example:
83 of 142
4 +-----------------------------+
5| 29 |
6 +-----------------------------+
7 1 row in set (0.00 sec)
The LAST_DAY function returns the last day of the month e.g. 2016-02-29 , and the DAY function returns
the day of the month of that last day that results in the number of days in the month.
See the following orders table in the sample database:
The following statement counts the orders by day of the month for 12 months in 2003.
1 SELECT
2 DAY(orderdate) dayofmonth,
3 COUNT(*)
4 FROM
5 orders
6 WHERE
7 YEAR(orderdate) = 2004
8 GROUP BY dayofmonth
9 ORDER BY dayofmonth;
84 of 142
In this tutorial, you have learned how to use the MySQL DAY function to get the day of the month of a
given date.
INTERVAL expr unit is an interval value to be added to the starting date value.
85 of 142
The DATE_ADD function may return a DATETIME value or a string, depending on the arguments:
DATETIME if the first argument is a DATETIME value or if the interval value has time element such as
hour, minute or second, etc.
String otherwise.
1 SELECT
2 DATE_ADD('1999-12-31 23:59:59',
3 INTERVAL 1 SECOND) result;
4
5 +---------------------+
6 | result |
7 +---------------------+
8 | 2000-01-01 00:00:00 |
9 +---------------------+
10 1 row in set (0.00 sec)
1 SELECT
2 DATE_ADD('1999-12-31 00:00:01',
3 INTERVAL 1 DAY) result;
4
5 +---------------------+
6 | result |
7 +---------------------+
8 | 2000-01-01 00:00:01 |
9 +---------------------+
10 1 row in set (0.00 sec)
1 SELECT
2 DATE_ADD('1999-12-31 23:59:59',
3 INTERVAL '1:1' MINUTE_SECOND) result;
4
5 +---------------------+
6 | result |
7 +---------------------+
8 | 2000-01-01 00:01:00 |
9 +---------------------+
10 1 row in set (0.00 sec)
86 of 142
Add -1 day and 5 hours to 2000-01-01 00:00:00 .
1 SELECT
2 DATE_ADD('1999-12-31 23:59:59.000002',
3 INTERVAL '1.999999' SECOND_MICROSECOND) result;
4
5 +----------------------------+
6 | result |
7 +----------------------------+
8 | 2000-01-01 00:00:01.000001 |
9 +----------------------------+
10 1 row in set (0.00 sec)
Interval Handling
In the interval:
The expr is treated as a string, therefore, you should be careful when you use a non-string value for
the expr . For example, with an interval of HOUR_MINUTE , 5/2 evaluates to 2.5000 (not 2.5 ) and is
treated as 2 hours 5000 minutes as in the following statement:
1 SELECT
2 DATE_ADD('2000-01-01',
3 INTERVAL 5 / 2 HOUR_MINUTE) result;
4
5
6 +---------------------+
7 | result |
8 +---------------------+
9 | 2000-01-04 13:20:00 |
10 +---------------------+
11 1 row in set (0.00 sec)
87 of 142
To ensure the correct interpretation of a non-string interval value, you should use the CAST function as
follows:
1 SELECT
2 DATE_ADD('2000-01-01',
3 INTERVAL CAST(6/4 AS DECIMAL(3,1)) HOUR_MINUTE) result;
4
5 +---------------------+
6 | result |
7 +---------------------+
8 | 2000-01-01 01:05:00 |
9 +---------------------+
10 1 row in set (0.00 sec)
1 SELECT
2 DATE_ADD('2000-01-01', INTERVAL 12 HOUR) result;
3
4 +---------------------+
5 | result |
6 +---------------------+
7 | 2000-01-01 12:00:00 |
8 +---------------------+
9 1 row in set (0.00 sec)
1 SELECT DATE_ADD('2000-02-30',
2 INTERVAL 1 DAY) result;
3 +--------+
4 | result |
5 +--------+
6 | NULL |
7 +--------+
8 1 row in set, 1 warning (0.00 sec)
If you want to see the warning in detail, you use the SHOW WARNINGS statement:
1 SHOW WARNINGS;
2 +---------+------+----------------------------------------+
3 | Level | Code | Message |
4 +---------+------+----------------------------------------+
5 | Warning | 1292 | Incorrect datetime value: '2000-02-30' |
88 of 142
6 +---------+------+----------------------------------------+
7 1 row in set (0.00 sec)
1 SELECT
2 DATE_ADD('2010-01-30',
3 INTERVAL 1 MONTH) result;
4
5 +------------+
6 | result |
7 +------------+
8 | 2010-02-28 |
9 +------------+
10 1 row in set (0.00 sec)
In this example, we added 1 month to the January 30th 2010 that results in February 28th 2010 . The
day was adjusted to the maximum day in February 2010 .
In the year that the February has 29 days, the date will be also adjusted to 29th as shown below:
1 SELECT
2 DATE_ADD('2012-01-30',
3 INTERVAL 1 MONTH) result;
4
5 +------------+
6 | result |
7 +------------+
8 | 2012-02-29 |
9 +------------+
10 1 row in set (0.00 sec)
In this tutorial, you have learned how to use the MySQL DATE_ADD function to add an interval to
a DATE or DATETIME value.
89 of 142
Introduction to MySQL DATE_SUB function
The DATE_SUB() function subtracts a time value (or an interval) from a DATE or DATETIME value. The
following illustrates the DATE_SUB() function:
expr is a string that determines an interval value to be subtracted from the starting date.
The unit is the interval unit that expr should be interpreted e.g., DAY , HOUR , etc.
The following statement uses the DATE_SUB() function to subtract 1 day from the July-4th-2017 :
In this example, the starting date is 2017-07-04 , which is in the yyyy-mm-dd format. The INTERVAL 1
DAY is interpreted as 1 day interval. The result of the DATE_SUB() function is a string value
represented July, 3rd 2017
Similar to the DATE_ADD() function, the data type of the return value of the DATE_SUB() function can be:
a DATETIME value if the first argument is a DATETIME or the interval has time element such as
the hour, minute, second, etc.
a string otherwise.
Because the interval is 3 hours, the result of the DATE_SUB function is a DATETIME value.
90 of 142
MySQL DATE_SUB : negative interval
The expr in the interval can be positive or negative. In case the expr is negative,
the DATE_SUB() function behaves like the DATE_ADD() function as shown in the following example:
In this example, 2017-02-03 is an invalid date, therefore, the result is NULL . In addition, MySQL produced
a warning.
1 SHOW WARNINGS;
2 +---------+------+----------------------------------------+
3 | Level | Code | Message |
4 +---------+------+----------------------------------------+
5 | Warning | 1292 | Incorrect datetime value: '2017-02-29' |
6 +---------+------+----------------------------------------+
7 1 row in set (0.00 sec)
The following examples demonstrate the effects when passing a malformed date or NULL to
the DATE_SUB function:
91 of 142
11 +--------+
12 | result |
13 +--------+
14 | NULL |
15 +--------+
16 1 row in set (0.00 sec)
In this example, we subtracted 1 month from March 30th 2017 therefore the result is February 28th
2017 . The day was adjusted to 28th instead of 30th because February 2017 has 28 days only.
In this tutorial, you have learned how to use the MySQL DATE_SUB() function to subtract an interval from
a DATE or DATETIME value.
1 DATE_FORMAT(date,format)
92 of 142
format : is a format string that consists of predefined specifiers. Each specifier is preceded by a
percentage character ( % ). See the table below for a list of predefined specifiers.
The DATE_FORMAT function returns a string whose character set and collation depend on the settings of
the client’s connection.
The following table illustrates the specifiers and their meanings that you can use to construct a date
format string:
Specifier Meaning
%D Day of the month with English suffix e.g., 0th, 1st, 2nd, etc.
%d Day of the month with leading zero if it is 1 number e.g., 00, 01,02, …31
%I Same as %h
%s Same as %S
%U Week number with leading zero when the first day of week is Sunday e.g.,
00,01,02…53
%u Week number with leading zero when the first day of week is Monday e.g.,
00,01,02…53
%X Year for the week in four digits where the first day of the week is Sunday; often
used with %V
%x Year for the week, where the first day of the week is Monday, four digits; used with
%v
%Y-%m-%d 7/4/2013
%e/%c/%Y 4/7/2013
%c/%e/%Y 7/4/2013
%d/%m/%Y 4/7/2013
%m/%d/%Y 7/4/2013
94 of 142
DATE_FORMAT string Formatted date
%M %e, %Y 4-Jul-13
95 of 142
To select order’s data and format the date value, you use the following statement:
1 SELECT
2 orderNumber,
3 DATE_FORMAT(orderdate, '%Y-%m-%d') orderDate,
4 DATE_FORMAT(requireddate, '%a %D %b %Y') requireddate,
5 DATE_FORMAT(shippedDate, '%W %D %M %Y') shippedDate
6 FROM
7 orders;
We formatted the order date, required date, and shipped date of each order based on different date
formats specified by the format strings.
1 SELECT
2 orderNumber,
3 DATE_FORMAT(shippeddate, '%W %D %M %Y') shippeddate
4 FROM
5 orders
6 WHERE
7 shippeddate IS NOT NULL
8 ORDER BY shippeddate;
96 of 142
In the query, we selected all orders whose shipped date are not NULL and sorted the orders by the
shipped date. However, the orders were not sorted correctly.
The reason is that we used shippeddate as the alias for the output of the DATE_FORMAT function, which
is a string, the ORDER BY clause took the alias and sorted the orders based on string values, not date
values.
To fix this problem, we have to use an alias that is different from the column name; see the following
statement:
1 SELECT
2 orderNumber,
3 DATE_FORMAT(shippeddate, '%W %D %M %Y') 'Shipped date'
4 FROM
5 orders
6 WHERE
7 shippeddate IS NOT NULL
8 ORDER BY shippeddate;
In this tutorial, we have shown you how to use the MySQL DATE_FORMAT function to format date based on
a specified format.
1 DAYNAME(date);
The DAYNAME function accepts 1 argument which is a date that you want to get the name of its weekday.
97 of 142
If the date is NULL or invalid e.g., 2017-02-30 , the DAYNAME function returns NULL .
To get day name a weekday in a specific locale, you need to change the value of
the lc_time_names variable. For example, the following statement sets the locale to French:
Now, let’s query the name of weekday for January 1st, 2000 :
As you can see, the weekday name has been changed to French.
The following table shows the valid locales for lc_time_names supported by MySQL:
98 of 142
Arabic – India ar_IN Icelandic – Iceland is_IS
Arabic – Iraq ar_IQ Indonesian – Indonesia id_ID
Arabic – Jordan ar_JO Italian – Italy it_IT
Arabic – Kuwait ar_KW Italian – Switzerland it_CH
Arabic – Lebanon ar_LB Japanese – Japan ja_JP
Arabic – Libya ar_LY Korean – Republic of ko_KR
Korea
Arabic – Morocco ar_MA Latvian – Latvia lv_LV
Arabic – Oman ar_OM Lithuanian – Lithuania lt_LT
Arabic – Qatar ar_QA Macedonian – FYROM mk_MK
Arabic – Saudi Arabia ar_SA Malay – Malaysia ms_MY
Arabic – Sudan ar_SD Mongolia – Mongolian mn_MN
Arabic – Syria ar_SY Norwegian – Norway no_NO
Arabic – Tunisia ar_TN Norwegian(Bokmål) – nb_NO
Norway
Arabic – United Arab ar_AE Polish – Poland pl_PL
Emirates
Arabic – Yemen ar_YE Portugese – Brazil pt_BR
Basque – Basque eu_ES Portugese – Portugal pt_PT
Belarusian – Belarus be_BY Romanian – Romania ro_RO
Bulgarian – Bulgaria bg_BG Russian – Russia ru_RU
Catalan – Spain ca_ES Russian – Ukraine ru_UA
Chinese – China zh_CN Serbian – Yugoslavia sr_RS
Chinese – Hong Kong zh_HK Slovak – Slovakia sk_SK
Chinese – Taiwan Province zh_TW Slovenian – Slovenia sl_SI
of China
Croatian – Croatia hr_HR Spanish – Argentina es_AR
Czech – Czech Republic cs_CZ Spanish – Bolivia es_BO
Danish – Denmark da_DK Spanish – Chile es_CL
Dutch – Belgium nl_BE Spanish – Columbia es_CO
Dutch – The Netherlands nl_NL Spanish – Costa Rica es_CR
English – Australia en_AU Spanish – Dominican es_DO
Republic
English – Canada en_CA Spanish – Ecuador es_EC
English – India en_IN Spanish – El Salvador es_SV
English – New Zealand en_NZ Spanish – Guatemala es_GT
English – Philippines en_PH Spanish – Honduras es_HN
English – South Africa en_ZA Spanish – Mexico es_MX
English – United Kingdom en_GB Spanish – Nicaragua es_NI
English – United States en_US Spanish – Panama es_PA
English – Zimbabwe en_ZW Spanish – Paraguay es_PY
Estonian – Estonia et_EE Spanish – Peru es_PE
Faroese – Faroe Islands fo_FO Spanish – Puerto Rico es_PR
Finnish – Finland fi_FI Spanish – Spain es_ES
French – Belgium fr_BE Spanish – United States es_US
French – Canada fr_CA Spanish – Uruguay es_UY
French – France fr_FR Spanish – Venezuela es_VE
French – Luxembourg fr_LU Swedish – Finland sv_FI
French – Switzerland fr_CH Swedish – Sweden sv_SE
Galician – Spain gl_ES Tamil – India ta_IN
German – Austria de_AT Telugu – India te_IN
German – Belgium de_BE Thai – Thailand th_TH
German – Germany de_DE Turkish – Turkey tr_TR
99 of 142
German – Luxembourg de_LU Ukrainian – Ukraine uk_UA
German – Switzerland de_CH Urdu – Pakistan ur_PK
Greek – Greece el_GR Vietnamese – Viet Nam vi_VN
The following statement returns the order count grouped by name of weekday in 2004.
1 SELECT
2 DAYNAME(orderdate) weekday,
3 COUNT(*) total_orders
4 FROM
5 orders
6 WHERE
7 YEAR(orderdate) = 2004
8 GROUP BY weekday
9 ORDER BY total_orders DESC;
The number of orders placed on Friday is the highest and there were two orders placed on Sunday.
In this tutorial, you have learned how to use the MySQL DAYNAME function to get the name of weekday for
a particular date.
100 of 142
The following illustrates the DAYOFWEEK function:
1 DAYOFWEEK(date)
The DAYOFWEEK function accepts 1 argument which is a DATE or DATETIME value. It returns an integer
which ranges from 1 to 7 that represents Sunday to Saturday.
The DAYOFWEEK function returns NULL if the date is NULL , zero ( 0000-00-00 ), or invalid.
In this query, the DAYNAME function returns weekday’s name while DAYOFWEEK function returns the
weekday index of December 1st, 2011 .
The unit is the interval that you want to extract from the date . The following are the valid intervals for
the unit argument.
DAY
DAY_HOUR
DAY_MICROSECOND
DAY_MINUTE
DAY_SECOND
HOUR
HOUR_MICROSECOND
HOUR_MINUTE
HOUR_SECOND
MICROSECOND
MINUTE
MINUTE_MICROSECOND
MINUTE_SECOND
101 of 142
MONTH
QUARTER
SECOND
SECOND_MICROSECOND
WEEK
YEAR
YEAR_MONTH
The date is a DATE or DATETIME value from which you extract an interval.
103 of 142
Extract hour_second from a datetime:
104 of 142
Extract month from a datetime:
105 of 142
6 +------+
7 1 row in set (0.00 sec)
The returned type of the NOW() function depends on the context where it is used. For example, in the
following statement, the NOW() function returns the current date and time as a string
1 SELECT NOW();
However, in the numeric context as the following example, the NOW() function returns the current date
and time as a number:
106 of 142
1 SELECT NOW() + 0;
Notice that the NOW() function returns a constant date and time at which the statement started executing.
See the following example:
In the query, the first NOW() function executed, and the SLEEP(5) function paused the execution of the
query for 5 seconds, and the second NOW() function executed. However, both NOW() functions return the
same value though they executed at the different times.
If you want to get exact time at which the statement executes, you need to use SYSDATE() instead; see
the following example:
1 SELECT SYSDATE(), SLEEP(5), SYSDATE();
If you want to change the MySQL server’s time zone to adjust the current date and time returned by
the NOW() function, you use the following statement:
107 of 142
The following statement returns the current date and time, now minus 1 day and now plus 1 day:
1 -- mysql now minus 1 day
2 SELECT (NOW() - INTERVAL 1 DAY) 'NOW - 1 day',
3 NOW(),
4 -- mysql now plus 1 day
5 (NOW() + INTERVAL 1 DAY) 'NOW + 1 day';
First, create a new table named tmp with three columns: id , title and created_on .
The created_on column has default value specified by the NOW() function.
Notice that CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW() so you can use
them interchangeably.
Second, insert a new row into the tmp table without specifying the value for the created_on column:
108 of 142
The value of the created_on column has been updated to the current date and time at which
the INSERT statement executed.
In this tutorial, we have introduced you to MySQL NOW() function that returns the current date and time at
which the statement executed.
The MONTH function returns an integer that represents the month of a specified date value. The following
illustrates the syntax of the MONTH function:
1 MONTH(date);
The MONTH function accepts one argument which is a DATE or DATETIME value. It returns an integer that
ranges from 1 to 12 for January to December.
If you pass a zero date e.g., 0000-00-00 , the MONTH function returns 0. In case you the date is NULL ,
the MONTH function returns NULL .
109 of 142
In this example, we passed the result of the NOW function, which is the current date and time, to
the MONTH function to get the current month.
As mentioned earlier, the MONTH function returns 0 for a zero date as shown in the following example:
The MONTH function returns NULL if the input date value is NULL :
1 SELECT
2 MONTH(orderDate) month,
3 ROUND(SUM(quantityOrdered * priceEach)) subtotal
4 FROM
5 orders
6 INNER JOIN
7 orderdetails USING (orderNumber)
8 WHERE
9 YEAR(orderDate) = 2004
10 GROUP BY month;
110 of 142
The following is the output of the query:
Let’s break the statement into smaller parts to make it easier to understand:
1. The INNER JOIN clause joined two tables orders and orderdetails using the orderNumbercolumn.
2. The MONTH function is applied on the orderDate column to get the month data
3. The SUM function calculated the subtotal of each line item in the sales order
4. The WHERE clause filtered only orders whose order dates in 2004.
In this tutorial, you have learned how to use the MySQL MONTH function to get a month of a specified date.
1 STR_TO_DATE(str,fmt);
The STR_TO_DATE() converts the str string into a date value based on the fmt format string.
The STR_TO_DATE() function may return a DATE , TIME, or DATETIME value based on the input and
format strings. If the input string is illegal, the STR_TO_DATE() function returns NULL.
111 of 142
The STR_TO_DATE() function scans the input string to match the format string. The format string may
contain literal characters and format specifiers that begin with percentage (%) character. Check it out
the DATE_FORMAT function for the list of format specifiers.
The STR_TO_DATE() function is very useful in data migration that involves temporal data conversion from
an external format to MySQL temporal data format.
1 SELECT STR_TO_DATE('21,5,2013','%d,%m,%Y');
Based on the format string ‘%d, %m, %Y’, the STR_TO_DATE() function scans the ‘21,5,2013’ input string.
First, it attempts to find a match for the %d format specifier, which is a day of the month (01…31), in
the input string. Because the number 21 matches with the %d specifier, the function takes 21 as the
day value.
Second, because the comma (,) literal character in the format string matches with the comma in the
input string, the function continues to check the second format specifier %m , which is a month (01…
12), and finds that the number 5 matches with the %m format specifier. It takes the number 5 as the
month value.
Third, after matching the second comma (,), the STR_TO_DATE() function keeps finding a match for
the third format specifier %Y , which is four-digit year e.g., 2012,2013, etc., and it takes the number
2013 as the year value.
The STR_TO_DATE() function ignores extra characters at the end of the input string when it parses the
input string based on the format string. See the following example:
The STR_TO_DATE() sets all incomplete date values, which are not provided by the input string, to zero.
See the following example:
112 of 142
1 SELECT STR_TO_DATE('2013','%Y');
Because the input string only provides year value, the STR_TO_DATE() function returns a date value that
has month and day set to zero.
1 SELECT STR_TO_DATE('113005','%h%i%s');
Similar to the unspecified date part, the STR_TO_DATE() function sets unspecified time part to zero, see
the following example:
1 SELECT STR_TO_DATE('11','%h');
The following example converts the string into a DATETIME value because the input string provides both
date and time parts.
In this tutorial, we have shown you various examples of using the MySQL STR_TO_DATE() function to
convert strings to date and time values.
113 of 142
Introduction to MySQL SYSDATE function
The following illustrates the syntax of the SYSDATE() function:
1 SYSDATE(fsp);
The SYSDATE() function returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' format
if the function is used in a string context or YYYYMMDDHHMMSS format in case the function is used in a
numeric context.
The SYSDATE() function accepts an optional argument fsp that determines whether the result should
include a fractional seconds precision which ranges from 0 to 6.
If you pass the fsp argument, the result will include the fractional seconds precision as shown in the
following example:
It seems that both SYSDATE() and NOW() functions return a same value which is the current date and
time at which it is executed.
However, the SYSDATE() function actually returns the time at which it executes while the NOW() function
returns a constant time at which the statement began to execute.
114 of 142
See the following query:
1 mysql> SELECT NOW(),
2 SLEEP(5),
3 NOW();
4 +---------------------+----------+---------------------+
5 | NOW() | SLEEP(5) | NOW() |
6 +---------------------+----------+---------------------+
7 | 2017-07-13 17:49:18 | 0 | 2017-07-13 17:49:18 |
8 +---------------------+----------+---------------------+
9 1 row in set (5.00 sec)
In this example, we used the SLEEP() function to pause the query for 5 seconds. Within the same
statement the NOW() function always returns a constant which is the time at which the statement began.
Within the same statement, SYSDATE() function returns different time values that reflect the time at which
the SYSDATE() function was executed.
Because the SYSDATE() function is non-deterministic, indexes cannot be utilized for evaluating
expressions that refer to it.
To demonstrate this, we will create a table named tests and insert some data into this table.
Notice that we used a recursive CTE for generating time series. The CTE has been available since
MySQL 8.0
115 of 142
Because the t column has a unique index, the following query should execute fast:
1 SELECT
2 id,
3 t
4 FROM
5 tests
6 WHERE
7 t >= SYSDATE() - INTERVAL 1 DAY;
However, it took 15ms to complete. Let’s see the detail using the EXPLAIN statement.
1 EXPLAIN SELECT
2 id, t
3 FROM
4 tests
5 WHERE
6 t >= SYSDATE() - INTERVAL 1 DAY;
It turned out that MySQL had to scan all the rows in the table to get the data. The index could not utilized.
1 SELECT
2 id,
3 t
4 FROM
5 tests
6 WHERE
7 t >= NOW() - INTERVAL 1 DAY;
With the NOW() function, the index has been used for querying data as shown in the result
the EXPLAIN below:
EXPLAIN SELECT
1
id,
2
t
3
FROM
4
tests
5
WHERE
6
t >= NOW() - INTERVAL 1 DAY;
7
Note that MySQL provides you with the --sysdate-is-now option that can make the SYSDATE() function
behaves the same as the NOW() function.
116 of 142
In this tutorial, you have learned about the MySQL SYSDATE() function and reason why you should
consider twice before using it.
The TIMEDIFF returns the difference between two TIME or DATETIME values. See the following syntax
of TIMEDIFF function.
1 TIMEDIFF(dt1, dt2);
The TIMEDIFF function accepts two arguments that must be the same type, either TIME or DATETIME .
The TIMEDIFF function returns the result of dt1 - dt2 expressed as a time value.
Because the TIMEDIFF function returns a TIME value, its result is limited to the range allowed
for TIME values which is from -838:59:59 to 838:59:59 .
It’s important to note that the TIMEDIFF function accepts values with TIME or DATETIME types. To
compare a difference between two DATE or DATETIME values, you use the DATEDIFF function.
In this example, we calculated the difference between 12:00:00 and 10:00:00 that results in 02:00:00 .
The following example calculates the difference between two DATETIME values:
1 mysql> SELECT
2 TIMEDIFF('2010-01-01 01:00:00',
3 '2010-01-02 01:00:00') diff;
4 +-----------+
5 | diff |
6 +-----------+
7 | -24:00:00 |
117 of 142
8 +-----------+
9 1 row in set (0.00 sec)
If you pass two arguments with different types, one is DATETIME and the other is TIME ,
the TIMEDIFF function also returns NULL.
As you can see, we got one warning. Let’s see what it is by using the SHOW WARNINGS statement.
So the result should be 1416 hours, however, as we mentioned earlier, the result of the TIMEDIFF function
is a TIME value which ranges from -838:59:59 to 838:59:59 . Therefore, MySQL truncated the result.
118 of 142
To fix this problem, you need to use the TIMESTAMPDIFF function as follows:
1 SELECT TIMESTAMPDIFF(
2 HOUR,
3 '2009-01-01 00:00:00',
4 '2009-03-01 00:00:00') diff;
The the following shows the difference between two DATETIME values in hour:
1 +------+
2 | diff |
3 +------+
4 | 1416 |
5 +------+
6 1 row in set (0.00 sec)
In this tutorial, you have learned how to use the MySQL TIMEDIFF function to calculate the difference
between two TIME or DATETIME values.
1 TIMESTAMPDIFF(unit,begin,end);
The TIMESTAMPDIFF function allows its arguments to have mixed types e.g., begin is a DATE value
and end is a DATETIME value. In case you use a DATE value, the TIMESTAMPDIFF function treats it as
a DATETIME value whose time part is '00:00:00' .
The unit argument determines the unit of the result of (end - begin) represented as an integer. The
following are valid units:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
119 of 142
MySQL TIMESTAMPDIFF function examples
The following example returns a difference of 2010-01-01 and 2010-06-01 in months:
1 SELECT
2 TIMESTAMPDIFF(MONTH, '2010-01-01', '2010-06-01') result;
3
4 +--------+
5 | result |
6 +--------+
7| 5|
8 +--------+
9 1 row in set (0.00 sec)
If you want to see the difference in days, you just need to change the unit argument from MONTH to DAY as
follows:
1 SELECT
2 TIMESTAMPDIFF(DAY, '2010-01-01', '2010-06-01') result;
3 +--------+
4 | result |
5 +--------+
6 | 151 |
7 +--------+
8 1 row in set (0.00 sec)
1 SELECT
2 TIMESTAMPDIFF(MINUTE, '2010-01-01 10:00:00', '2010-01-01 10:45:00') result;
3 +--------+
4 | result |
5 +--------+
6 | 45 |
7 +--------+
8 1 row in set (0.00 sec)
Note that the TIMESTAMPDIFF only considers the time part that is relevant to the unit argument. See the
following example:
The difference should be 45 minutes 59 seconds. However, we pass the unit argument as MINUTE ,
therefore, the function returns 45 minutes as expected.
120 of 142
If you use SECOND instead of MINUTE , then the TIMESTAMPDIFF function will consider the SECOND part as
shown in the following example:
1 SELECT
2 TIMESTAMPDIFF(SECOND, '2010-01-01 10:00:00', '2010-01-01 10:45:59') result;
3 +--------+
4 | result |
5 +--------+
6 | 2759 |
7 +--------+
8 1 row in set (0.00 sec)
Third, we use the TIMESTAMPDIFF to calculate the ages of each person in the persons table:
1 SELECT
2 id,
3 full_name,
4 date_of_birth,
5 TIMESTAMPDIFF(YEAR,
6 date_of_birth,
7 '2017-01-01') age
8 FROM
9 persons;
121 of 142
In this statement, we calculated the ages on January 1st 2017 . If you want to calculate the current
ages, you can replace the literal value 2017-01-01 by the NOW function as follows:
1 SELECT
2 id,
3 full_name,
4 date_of_birth,
5 TIMESTAMPDIFF(YEAR,
6 date_of_birth,
7 NOW()) age
8 FROM
9 persons;
In this tutorial, you have learned how to use the MySQL TIMESTAMPDIFF function to calculate the
difference between two DATE or DATETIME values.
Typically, a year has 365 days for a normal year and 366 days for leap year. A year is then divided into
weeks with each week has exact 7 days. So for a year we often has 365 / 7 = 52 weeks that range from 1
to 52.
To check whether a particular date belongs to which week number, you use the WEEK function as follows:
1 WEEK(date, mode);
mode is an optional argument that determines the logic of week number calculation. It allows you to
specify whether the week should start on Monday or Sunday and the returned week number should
be between 0 and 52 or 0 and 53.
122 of 142
If you ignore the mode argument, the WEEK function will use the value of
the default_week_format system variable by default.
To get the current value of default_week_format variable, you use the SHOW VARIABLES statement as
follows:
In our server, the default value of default_week_format is 0. The following table illustrates how
the mode argument influcences the WEEK function:
The ” with 4 or more days this year ” in the above table means:
If the week that contains January 1st and has 4 or more days in the new year, the week is
numbered as week 1.
Otherwise, the week is numbered as the last week of the previous year and the next week is week
1.
The WEEK function returns a week number followed according to ISO 8601:1988
123 of 142
The following statement returns the number of orders per week in 2013 using the WEEK function:
1 SELECT
2 WEEK(orderDate) week_no,
3 COUNT(*)
4 FROM
5 orders
6 WHERE
7 YEAR(orderDate) = 2003
8 GROUP BY WEEK(orderDate);
In this tutorial, you have learned how to use the MySQL WEEK function to get the week number from a
specified date.
1 WEEKDAY(date)
124 of 142
The WEEKDAY function accepts 1 argument which is a DATE or DATETIME value. It returns an integer which
ranges from 0 to 6 that represents Monday to Sunday.
The WEEKDAY function returns NULL if the date is NULL , invalid or zero ( 0000-00-00 ).
See the following example:
1 mysql> SELECT DAYNAME('2010-01-01'), WEEKDAY('2010-01-01');
2 +-----------------------+-----------------------+
3 | DAYNAME('2010-01-01') | WEEKDAY('2010-01-01') |
4 +-----------------------+-----------------------+
5 | Friday | 4|
6 +-----------------------+-----------------------+
7 1 row in set (0.00 sec)
In this example, we used the DAYNAME function to get the weekday’s name and WEEKDAY function to get
the weekday index of January 1st, 2010 .
1 YEAR(date);
The YEAR() function returns a year value in the range 1000 to 9999 . If the date is zero,
the YEAR() function returns 0.
The following example returns the year of January 1st 2017 which is 2017 .
1 SELECT YEAR('2017-01-01');
2
3 +--------------------+
4 | YEAR('2017-01-01') |
5 +--------------------+
6| 2017 |
7 +--------------------+
8 1 row in set (0.00 sec)
125 of 142
In this example, the YEAR() function returns the year information of the current date and time provided by
the NOW() function.
If the date is NULL , the YEAR() function will return NULL as shown in the following example:
1 SELECT YEAR(NULL);
2 +------------+
3 | YEAR(NULL) |
4 +------------+
5| NULL |
6 +------------+
7 1 row in set (0.00 sec)
The following query uses the YEAR() function to get the number of orders shipped per year.
1 SELECT
2 YEAR(shippeddate) year,
3 COUNT(ordernumber) orderQty
4 FROM
5 orders
6 WHERE
7 shippeddate IS NOT NULL
8 GROUP BY YEAR(shippeddate)
9 ORDER BY YEAR(shippeddate);
126 of 142
In this example, we use the YEAR() function to extract year information out of the shipped date and use
the COUNT() function to count the number of delivered orders. The GROUP BY clause group the number of
orders by year.
The dt column will store the date data. The following statement creates an index on the dt column of
the dates table.
We will insert lots of dates into the dates table. The easiest way is to use a recursive CTE to generate the
date series and insert this date series into the dates table.
The following recursive CTE generates the dates between '1800-01-01' and '2020-12-31' :
To insert this date series into the dates table, you use the following INSERT statement:
You can find the number of rows in the dates table by using the following query:
1 SELECT
2 COUNT(*)
3 FROM
4 dates;
127 of 142
The dates table has 80354 rows.
To get all the dates in 2014, you use the following query:
1 SELECT
2 *
3 FROM
4 dates
5 WHERE
6 YEAR(dt) = 2014;
Or
1 SELECT
2 *
3 FROM
4 dates
5 WHERE
6 dt BETWEEN '2014-01-01' and '2014-12-31';
However, there is a difference in terms of performance. The first query examines all rows in
the dates table and some rows in the index while the second one uses the index only which is much
faster.
1 EXPLAIN SELECT
2 *
3 FROM
4 dates
5 WHERE
6 YEAR(dt) = 2014;
And
1 EXPLAIN SELECT
2 *
3 FROM
4 dates
5 WHERE
6 dt BETWEEN '2014-01-01' and '2014-12-31';
128 of 142
Even though the MySQL YEAR() function is handy, when it comes to performance, you should always
consider using it.
In this tutorial, we have introduced you the MySQL YEAR() function and gave you some examples of
using it.
GREATEST & LEAST – take n arguments and return the greatest and least values of the n arguments
respectively.
1 COALESCE(value1,value2,...);
The COALESCE function takes a number of arguments and returns the first non-NULL argument. In case
all arguments are NULL, the COALESCE function returns NULL.
The following shows some simple examples of using the COALESCE function:
129 of 142
The following query returns customer name, city, state, and country of all customers in
the customers table.
1 SELECT
2 customerName, city, state, country
3 FROM
4 customers;
As you see, the state column has NULL values because some this information is not applicable to the
country of some customers.
To substitute the NULL value in the result set, you can use the COALESCE function as follows:
1 SELECT
2 customerName, city, COALESCE(state, 'N/A'), country
3 FROM
4 customers;
130 of 142
In this example, if the value in the state column is NULL, the COALESCE function will substitute it by
the N/A string. Otherwise, it returns the value of the state column.
Another typical example of using the COALESCE function is to substitute value in one column by another
when the first one is NULL.
Imagine you have to display articles on an overview page where each article contains the title, expert, and
publish date (and also the read more link the article page). The first task you need to do is to query this
data from the articles table:
1 SELECT
2 id, title, excerpt, published_at
3 FROM
4 articles;
As you see the article with id 2 does not have the excerpt, which is not nice for displaying.
131 of 142
A typical solution is to get the first number of characters in the body of the article for displaying as the
excerpt. This is why the COALESCE function comes into play.
1 SELECT
2 id, title, COALESCE(excerpt, LEFT(body, 150)), published_at
3 FROM
4 articles;
In this example, if the value in the excerpt column is NULL, the COALESCE function returns the first 150
characters of the content in the body column.
1 SELECT
2 id,
3 title,
4 (CASE
5 WHEN excerpt IS NULL THEN LEFT(body, 150)
6 ELSE excerpt
7 END) AS excerpt,
8 published_at
9 FROM
10 articles;
In this example, the CASE expression is more lengthy than using the COALESCE function.
The IFNULL function works great with two arguments whereas the COALESCE function works
with n arguments. In case the number of arguments is two, both functions are the same.
In this tutorial, you have learned how to use the MySQL COALESCE function to substitute NULL values.
132 of 142
Summary: in this tutorial, you will learn how to use MySQL GREATEST and LEAST functions to find the
greatest and smallest values of two or more fields respectively.
The arguments may have mixed data types. The following comparison rules are applied to both functions:
If any argument is NULL, the both functions return NULLs immediately without doing any
comparison.
If functions are used in the INT or REAL contexts, or all arguments are integer-valued or REAL-
valued, they are compared as INT and REAL respectively.
If arguments consists of both numbers and strings, the functions will compare them as numbers.
If a least an argument is a non-binary (character) string, the functions will compare the arguments
as non-binary strings.
The following examples demonstrates how the GREATEST and LEAST function work.
The revenues table consists of company_id as the primary key and four columns to store revenues of
the company in each quarter.
133 of 142
The following statement inserts two rows into the revenues table.
To get the highest and lowest revenues for each company, you use the GREATEST and LOWEST functions
as follows:
1 SELECT
2 company_id,
3 LEAST(q1, q2, q3, q4) low,
4 GREATEST(q1, q2, q3, q4) high
5 FROM
6 revenues;
Both GREATEST and LEAST functions return NULLs if any argument is NULL which may not what you
expected. To avoid this, you can use the IFNULL function to treat NULL as zero to perform the numeric
comparison.
The following statement inserts a new row into the revenues table with a NULL value in the q4 column.
If you use the GREATEST and LEAST functions to query data, you get the result as designed.
1 SELECT
2 company_id,
3 LEAST(q1, q2, q3, q4) low,
4 GREATEST(q1, q2, q3, q4) high
5 FROM
6 revenues;
As you can see, the low and high values of the company id 3 are NULLs.
134 of 142
To avoid this, you can use the IFNULL function as follows:
1 SELECT
2 company_id,
3 LEAST(IFNULL(q1, 0),
4 IFNULL(q2, 0),
5 IFNULL(q3, 0),
6 IFNULL(q4, 0)) low,
7 GREATEST(IFNULL(q1, 0),
8 IFNULL(q2, 0),
9 IFNULL(q3, 0),
10 IFNULL(q4, 0)) high
11 FROM
12 revenues;
In this tutorial, you have learned how to use the MySQL GREATEST and LEAST functions to find the
greatest and least values in a list of values.
1 ISNULL(expr)
135 of 142
Notice that if you are trying to find the MySQL alternative to Microsoft SQL Server’s ISNULL function, you
should use MySQL’s IFNULL function instead. Because the ISNULL function is MySQL is different from
the Microsoft SQL Server’s ISNULL function.
1 SELECT
2 *
3 FROM
4 table_name
5 WHERE
6 ISNULL(date);
Note that MySQL purposely implemented this feature to support ODBC applications because ODBC does
not support special date value '0000-00-00' .
Third, query data from the special_isnull table using the ISNULL function:
1 SELECT
2 *
3 FROM
4 special_isnull
5 WHERE
6 ISNULL(start_date);
The query returned one row while you may expected it will return an empty result set.
When you want to negate the IS NULL operator, you use the NOT operator i.e., IS NOT NULL . However,
for the ISNULL function, you use !ISNULL .
136 of 142
In this tutorial, you have learned how to use the MySQL ISNULL function and its special behavior to
handle NULL values.
It means when you insert a new row into the table that has an AUTO_INCREMENT column, MySQL
automatically generates a unique integer and use it for the column.
For more information on how to set the AUTO_INCREMENT attribute for a column, check it out the MySQL
sequence tutorial.
You can obtain the generated sequence number using the MySQL LAST_INSERT_ID function and use the
number for the next statements e.g., inserting a new row into a correlated table.
First, create a new table named tbl for testing. In the tbl table, you set the AUTO_INCREMENT attribute
for the id column.
137 of 142
2 VALUES('MySQL last_insert_id');
Third, use the MySQL LAST_INSERT_ID function to get the last insert id that MySQL has been generated.
1 SELECT LAST_INSERT_ID();
It’s important to note that if you insert multiple rows into a table using a single INSERT statement,
the LAST_INSERT_ID function returns the last insert id of the first row.
Suppose the AUTO_INCREMENT column has current value as 1 and you insert 3 rows into the table. When
you use the LAST_INSERT_ID function to get the last insert id, you will get 2 instead of 4.
The following statement inserts 3 rows into the tbl table and gets the last insert id using
the LAST_INSERT_ID function.
The LAST_INSERT_ID function works based on client-independent principle. It means the value returned
by the LAST_INSERT_ID function for a specific client is the value generated by that client only. This
ensures that each client can obtain its own unique ID.
138 of 142
In this tutorial, we have shown you how to use the MySQL LAST_INSERT_ID function to get the sequence
number of the last row that has been inserted into a table.
1 CAST(expression AS TYPE);
The CAST() function converts a value of any type into a value that has a specified type. The target type
can be any one of the following
types: BINARY , CHAR , DATE , DATETIME , TIME , DECIMAL , SIGNED , UNSIGNED .
The CAST() function is often used to return a value with a specified type for comparison in
the WHERE, JOIN, and HAVING clauses.
1 SELECT (1 + '1')/2;
To explicitly convert a string into an integer, you use the CAST() function as the following statement:
The following statement explicitly converts an integer into a string and concatenates the string with
another string:
139 of 142
Let’s take a look at the orders table in the sample database.
1 SELECT orderNumber,
2 requiredDate
3 FROM orders
4 WHERE requiredDate BETWEEN '2003-01-01' AND '2003-01-31';
The query selects orders whose required dates are in January 2003. The data type of
the requireDate column is DATE , therefore, MySQL has to convert the literal strings: '2003-01-
01' and '2003-01-31' into TIMESTAMP values before evaluating the WHERE condition.
However, to be safe, you can use CAST() function to explicitly convert a string into a TIMESTAMP value as
follows:
1 SELECT orderNumber,
2 requiredDate
3 FROM orders
4 WHERE requiredDate BETWEEN CAST('2003-01-01' AS DATETIME)
5 AND CAST('2003-01-31' AS DATETIME);
The following statement converts DOUBLE values into CHAR values and uses the results as the arguments
of the CONCAT function:
1 SELECT productName,
140 of 142
2 CONCAT('Prices(',
3 CAST(buyprice AS CHAR),
4 ',',
5 CAST(msrp AS CHAR),
6 ')') prices
7 FROM products;
In this tutorial, you have learned how to use the MySQL CAST() function to convert a value with any type
into a value with a specified type.
141 of 142