0% found this document useful (0 votes)
127 views141 pages

Mysql Functions

The document discusses several MySQL aggregate functions including AVG, COUNT, SUM, MAX, MIN and GROUP_CONCAT. It provides examples and explanations of how to use each function, including with clauses like DISTINCT, GROUP BY, HAVING, LIMIT and JOIN. It also covers standard deviation and other statistical concepts.

Uploaded by

xy za
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views141 pages

Mysql Functions

The document discusses several MySQL aggregate functions including AVG, COUNT, SUM, MAX, MIN and GROUP_CONCAT. It provides examples and explanations of how to use each function, including with clauses like DISTINCT, GROUP BY, HAVING, LIMIT and JOIN. It also covers standard deviation and other statistical concepts.

Uploaded by

xy za
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 141

Table of Contents

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

 AVG – calculate the average value of a set of values or an expression.

 COUNT – count the number rows in a table.

6 of 142
 INSTR – return the position of the first occurrence of a substring in a string.

 SUM – calculate the sum of a set of values or an expression.

 MIN – find the minimum value in a set of values

 MAX – find the maximum value in a set of values

 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.

MySQL Aggregate Functions


Summary: in this tutorial, you will learn how to use the MySQL aggregate functions including
AVGCOUNT , SUM , MAX and MIN.

Introduction to MySQL aggregate functions

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:

1 SELECT AVG(buyPrice) average_buy_price


2 FROM products

The AVG function in detail.

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:

1 SELECT COUNT(*) AS Total


2 FROM products

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:

1 SELECT productCode,sum(priceEach * quantityOrdered) total


2 FROM orderdetails
3 GROUP by productCode
To see the result in more detail, you can join the orderdetails table to the products table as the
following query:
1 SELECT P.productCode,
2 P.productName,
3 SUM(priceEach * quantityOrdered) total
4 FROM orderdetails O
5 INNER JOIN products P ON O.productCode = P.productCode
6 GROUP by productCode
7 ORDER BY total

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:

1 SELECT MAX(buyPrice) highest_price,


2 FROM Products

How the MAX function works in detail.

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:

1 SELECT MIN(buyPrice) lowest_price,


2 FROM Products

Explains the MIN function in detail.

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.

Introduction to MySQL AVG function


The MySQL AVG function is an aggregate function that allows you to calculate the average value of a set
of values or an expression.

The syntax of the AVG function is as follows:

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 .

MySQL AVG examples


We are going to use the products table in the sample database for the demonstration. The following
diagram illustrates the products table.

To calculate average buy price of all products in the products table, you use the AVG function as the
following query:

1 SELECT AVG(buyprice)'Avarage Price'


2 FROM products;

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:

1 SELECT AVG(buyprice) 'Avarage Classic Cars Price'


2 FROM products
3 WHERE productline = 'Classic Cars';

MySQL AVG with DISTINCT


Some products have the same price. You can check it by using the following query:
10 of 142
1 SELECT COUNT(buyprice) - COUNT(DISTINCT buyprice)
2 FROM products;

You can use AVG function to calculate the average of distinct buy prices by adding the DISTINCT operator
as follows:

1 SELECT AVG(DISTINCT buyprice)


2 FROM products;

The result is slightly different from the average buy price without using the DISTINCT operator.

MySQL AVG with GROUP BY clause


We often use the AVG function in conjunction with the GROUP BY clause to calculate the average value
for each group of rows in a table.

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;

MySQL AVG with HAVING clause


You can use the AVG function in the HAVING clause to set conditions for the average values of groups.

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;

MySQL AVG function with subquery


You can use the AVG function in SQL statement multiple times to calculate the average value of a set of
average values. For example, you can calculate the average buy price of the average buy prices of
product lines as the following query:

1 SELECT AVG(pl_avg) 'Average Product'


2 FROM (
3 SELECT AVG(buyprice) pl_avg
4 FROM products
5 GROUP BY productline
6 ) avgs;

How it works.

 The subquery calculates the average buy price by product lines.


 The outer query calculates the average buy price of the average buy prices of product lines returned
from the subquery.

MySQL AVG function with NULL values


The AVG function ignores NULL values in the calculation. See the following example:
First, create a new table named t with two columns id and val . The val column can
contain NULL values.

1 CREATE TABLE IF NOT EXISTS t(


2 id int auto_increment primary key,
3 val int
4 );
12 of 142
Second, insert some rows into the t table, including NULL value.

1 INSERT INTO t(val)


2 VALUES(1),(2),(nulL),(3);

Third, calculate the average value of the values in the val column by using the AVG function:

1 SELECT AVG(val) FROM t;

The statement returns 2 as expected because the NULL value is not included in the calculation of
the AVG function.

MySQL AVG with control flow function


To calculate the average value of a column and calculate the average value of the same column
conditionally in a single statement, you use AVG function with control flow functions
e.g., IF, CASE, IFNULL, NULLIF, etc.

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:

1 SELECT AVG(IF(productline='Classic Cars',buyprice,NULL)) / AVG(buyprice) 'Classic Cars/ Products'


2 FROM products;

The IF(productline='Classic Cars',buyprice,NULL) expression returns buy price if the product


line is Classic Cars , otherwise it returns NULL .

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.

The syntax of the COUNT function is as follows.

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 can retrieve it very quickly.

MySQL COUNT(expression)
The COUNT(expression) returns the number of rows that do not contain NULL values.

MySQL COUNT(DISTINCT expression)


The COUNT(DISTINCT expression) returns the number of unique rows that dot not contain NULL values.

MySQL COUNT examples


Let’s create a new table named demos and insert some sample data for the demonstration.

1 -- create a demos table


2 CREATE TABLE IF NOT EXISTS demos(
3 id int auto_increment primary key,
4 val int
5 );
6 -- insert some sample data
7 INSERT INTO demos(val)

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;

Two NULL values in the val column are ignored.

15 of 142
To count unique rows in the demos table, you add the DISTINCT operator to the COUNT function as the
following query:

1 SELECT COUNT(DISTINCT val)


2 FROM demos;

Two duplicate values 1,2 and two NULL values are ignored in the counting.

MySQL COUNT with GROUP BY


We often use the COUNT function in conjunction with GROUP BY clause to characterize the data in various
groups. See the following products table.

For example, to find how many products in each product line, you use the COUNT function with the GROUP
BY clause as follows:

1 SELECT productline, count(*)


2 FROM products
3 GROUP BY productline;

16 of 142
To find the number of products supplied by vendors, you use the following query:

1 SELECT productvendor, count(*)


2 FROM products
3 GROUP BY productvendor;

To find which vendor supplies at least 9 products, you use the COUNT function in the HAVING clause as
the following query:

1 SELECT productvendor, count(*)


2 FROM products
3 GROUP BY productvendor
4 HAVING count(*) >= 9;

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:

1 SELECT COUNT(IF(status='Cancelled',1, NULL)) 'Cancelled',


2 COUNT(IF(status='On Hold',1, NULL)) 'On Hold',
3 COUNT(IF(status='Disputed',1, NULL)) 'Disputed'
17 of 142
4 FROM orders;

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.

MySQL INSTR Function


Summary: this tutorial shows you how to use the MySQL INSTR function to return the position of the first
occurrence of a string.

Introduction to the MySQL INSTR function


Sometimes, you want to locate a substring in a string or to check if a substring exists in a string. In this
case, you can use a string built-in function called INSTR .

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).

The following illustrates the syntax of the INSTR function.

1 INSTR(str,substr);

The INSTR function accepts two arguments:

 The str is the string that you want to search in.

 The substr is the substring that you want to search for.

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.

The MySQL INSTR function examples


The following statement returns the position of the substring MySQL in the MySQL INSTR string.

1 SELECT INSTR('MySQL INSTR', 'MySQL');

18 of 142
The following statement returns the same result because the INSTR function is case-insensitive.

1 SELECT INSTR('MySQL INSTR', 'mysql');

To force INSTR function to search based on case-sensitive fashion, you use the BINARY operator as
follows:

1 SELECT INSTR('MySQL INSTR', BINARY 'mysql');

The result is different because mysql vs. MySQL now with the BINARY operator.

The INSTR function vs. LIKE operator


We will use the products table in the sample database.

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.

Let’s create an index on the productname column.

1 CREATE INDEX idx_products_name ON products(productname);

If you use the LIKE operator with the prefix search, on this indexed column, the LIKE operator will
perform faster than the INSTR function.

See the following statement.

1 SELECT
2 productname
3 FROM
4 products
5 WHERE
6 productname LIKE '1900%';

You can check it using the EXPLAIN statement:

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.

Introduction to MySQL SUM function


The SUM function allows you to calculate the sum of a set of values or an expression. The syntax of
the SUM function is as follows:

1 SUM(DISTINCT expression)

How the SUM function works.

 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.

 The SUM function ignores the NULL values in the calculation.

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:

1 SELECT FORMAT(SUM(quantityOrdered * priceEach),2) total


2 FROM orderdetails
3 WHERE orderNumber = 10100;

Notice that the FORMAT function is used for formatting the returned value of the SUM function.

MySQL SUM with GROUP BY


When combining with the GROUP BY clause, the SUM function calculates the sum for every group
specified in the GROUP BY clause.

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);

MySQL SUM with LIMIT


Suppose you want to calculate the sum of the top 10 most expensive products in the products table, you
may come up with the following query:

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.

To fix this problem, you use a subquery as follows:

1 SELECT FORMAT(SUM(buyprice),2) FROM


2 (SELECT buyprice

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.

MySQL SUM with NULL


The SUM function returns NULL if there is no matching row. Sometimes, you want the SUM function to
return zero instead of NULL . In this case, you can use the COALESCE function. The COALESCE function
accepts two arguments and returns the second argument if the first argument is NULL , otherwise, it
returns the first argument; see the following query:

1 SELECT COALESCE(SUM(quantityOrdered * priceEach),0)


2 FROM orderdetails
3 WHERE productCode = 'S1_20';

MySQL SUM with JOIN


You can use the SUM function in a SELECT JOIN statement to calculate the sum of values in a table
based on a condition specified by the values in another table.

For example, to calculate the sum of amount of the cancelled orders, you use the following statement:

1 SELECT FORMAT(SUM(quantityOrdered * priceEach),2) loss


2 FROM orderdetails
3 INNER JOIN orders USING(orderNumber)
4 WHERE status = 'Cancelled'

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.

MySQL MIN Function


Summary: in this tutorial, you will learn how to use the MySQL MIN function to find the minimum value in
a set of values.

Introduction to MySQL MIN function


The MIN function returns the minimum value in a set of values. The MIN function is very useful in some
scenarios such as finding the smallest number, selecting the least expensive product, getting the lowest
credit limit, etc.

The following illustrates the syntax of the MIN function:

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.

MySQL MIN function examples


Let’s take a look at the products table in the sample database.

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;

MySQL MIN with subquery


To select not only the price but also other product’s information such as product code and product name,
you use the MIN function in a subquery as follows:

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.

MySQL MIN with GROUP BY


When you combine the MIN function with the GROUP BY clause in a SELECT statement, you can get the
minimum values for every group.
For example, to get the lowest buy price product for each product line, you use the following statement:

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.

MySQL MIN with correlated subquery


The following query selects the lowest price product in every product line by combining the MIN function
with 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.

MySQL MAX Function


Summary: in this tutorial, you will learn how to use the MySQL MAX function to get the maximum value
in a set of values.

Introduction to MySQL MAX function


The MySQL MAX function returns the maximum value in a set of values. The MAX function is handy in
many queries such as finding the greatest number, the most expensive product, and the largest payment
from customers.

The syntax of the MAX function is as follows:

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.

MySQL MAX function examples


Let’s take a look at the payments table in the sample database.

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;

MySQL MAX function in subquery


To get not only the largest payment’s amount but also other payment’s information such as customer
number, check number and payment date, you use the MAX function in a subquery as follows:

1 SELECT
2 *
3 FROM
4 payments
5 WHERE
6 amount = (
7 SELECT
8 MAX(amount)
9 FROM
10 payments);

How it works.

 The subquery returns the largest amount of all payments.

 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.

MySQL MAX with GROUP BY clause


To find the maximum value for every group, you use the MAX function with the GROUP BY clause in
a SELECT statement.
For each customer, get the largest payment that the customer has been paid, you use the following query:

1 SELECT
2 customerNumber, MAX(amount)
3 FROM
4 payments
5 GROUP BY customerNumber
6 ORDER BY MAX(amount);

MySQL MAX with HAVING clause


You use the MAX function in a HAVING clause with the GROUP BY clause to add a filter for groups based
on a specified condition.

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.

MySQL GROUP_CONCAT Function


Summary: in this tutorial, you will learn how to use the MySQL GROUP_CONCAT function to
concatenate strings from a group with various options.

Introduction to MySQL GROUP_CONCAT function


The MySQL GROUP_CONCAT function concatenates strings from a group into a single string with various
options.
The following illustrates the GROUP_CONCAT function:

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.

MySQL GROUP_CONCAT examples


Let’s take a look at the customers table in the sample database.

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.

MySQL GROUP_CONCAT with CONCAT_WS function example


Sometimes, the GROUP_CONCAT function can be combined with the CONCAT_WS function to make a
result of query more useful.

For example, to make a list of semicolon-separated values of customers:

 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.

 Then, you use the GROUP_CONCAT function to make the list.

The following query makes a list of semicolon-separated values of customers.

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.

MySQL GROUP_CONCAT function: common mistakes


The GROUP_CONCAT function returns a single string, not a list of values. It means you cannot use the result
of the GROUP_CONCAT function for IN operator e.g., within a subquery.

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.

MySQL GROUP_CONCAT applications


There are many cases where you can apply the GROUP_CONCAT function to produce useful results. The
following list is some common examples of the using the GROUP_CONCAT function.

 Make a comma-separated user’s roles such as ‘admin,author, editor’.

 Produce the comma-separated user’s hobbies e.g., ‘design, programming, reading’.

 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.

MySQL Standard Deviation


Summary: in this tutorial, you will learn how to use MySQL standard deviation functions to calculate
populate standard deviation and sample standard deviation.

Introduction to standard deviation


Standard deviation is a measure of how spread out the values in a data set are. The standard deviation
shows how much variation exists from the average (mean).

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

Population standard deviation vs. sample standard deviation


If all values in the data set are taken into the calculation, this standard deviation is called population
standard deviation. However, if a subset of values or a sample is taken into the calculation, this standard
deviation is called sample standard deviation.

A sigma letter (σ) represents the standard deviation. The following equations illustrate how to calculate
population standard deviation and sample standard deviation:

Population standard deviation:

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.

MySQL standard deviation functions


MySQL makes it easy for you to calculate the population standard deviation and sample standard
deviation.

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.

 STDDEV(expression) – is equivalent to the STD function. It is provided to be compatible with Oracle


Database only.

 STDEV_POP(expression) – is equivalent to the STD function.

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:

 VAR_POP(expression) – calculates the population standard variance of the expression.

 VARIANCE(expression) – is equivalent to the VAR_POP function.

 VAR_SAMP(expression) – calculates the sample standard variance of the expression.

Examples of MySQL standard deviation functions


Let’s take a look at the orders table in the sample database.

Examples of population standard deviation functions


First, the following query returns the customer numbers and their number of orders from the orders table:

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.

Examples of sample standard deviation functions


Suppose you only want to evaluate only shipped orders in the orders table.

First, the following query returns the customer numbers and their number of the shipped orders:

1 SELECT customerNumber, count(*) orderCount


2 FROM orders
3 WHERE status = 'Shipped'
4 GROUP BY customerNumber;

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.

 LEFT – get the left part of a string with a specified length.

 REPLACE – search and replaces a substring in a string.

 SUBSTRING – extract a substring starting from a position with a specific length.

 TRIM – remove unwanted characters from a string.

 FIND_IN_SET – find a string within a comma-separated list of strings.

 FORMAT – format a number with a specific locale, rounded to the number of decimals

MySQL CONCAT Function


Summary: in this tutorial, you will learn various ways to concatenate two or more strings together by
using the MySQL CONCAT and CONCAT_WS functions.

To concatenate two or more quoted string values, you place the string next to each other as the following
syntax:

1 SELECT 'MySQL ' 'String ' 'Concatenation';

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 .

MySQL CONCAT function


The MySQL CONCAT function takes one or more string arguments and concatenates them into a single
string. The CONCAT function requires a minimum of one parameter otherwise it raises an error.

The following illustrates the syntax of the CONCAT function.

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');

See the following customers table in the sample database.

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.

The following illustrates the syntax of the CONCAT_WS function:

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:

1 SELECT CONCAT_WS(NULL ,'Jonathan', 'Smith');

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.

1 SELECT CONCAT_WS(',','Jonathan', 'Smith',NULL);

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;

Here is the output result:


1 Customer_Address
2 ---------------------------------------------------
3 Schmitt Carine
4 54, rue Royale
5 44000 Nantes
6 France
7
8 King Jean
9 8489 Strong St.
10 83030 Las Vegas
11 USA
12
13 ...

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 String Length


Summary: in this tutorial, you will learn about MySQL string length functions that allow you to get the
length of strings measured in bytes and in characters.

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);

Examples of LENGTH and CHAR_LENGTH functions


Let’s take a look at the following statements:

1 SET @s = CONVERT('MySQL String Length' USING ucs2);


2 SELECT CHAR_LENGTH(@s), LENGTH(@s);

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:

1 SET @s = CONVERT('MySQL string length' USING latin1);


2 SELECT LENGTH(@s), CHAR_LENGTH(@s);

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:

1 SET @s = CONVERT('MySQL String Length' USING utf8);


2 SELECT CHAR_LENGTH(@s), LENGTH(@s);

The CHAR_LENGTH and LENGTH returns the same result. However, if a string has special characters, the
result is different. See the following example:

1 SET @s = CONVERT('á' USING utf8);


2 SELECT CHAR_LENGTH(@s), LENGTH(@s);

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:

1 CREATE TABLE posts(


2 postid int auto_increment primary key,
3 title varchar(255) NOT NULL,
4 excerpt varchar(255) NOT NULL,
5 content text,
6 pubdate datetime
7 )Engine=InnoDB;

Second, we insert some blog posts into the posts table by using the INSERT statement:

1 INSERT INTO posts(title,excerpt,content)


2 VALUES('MySQL Length','MySQL string length function tutorial','dummy'),
3 ('Second blog post','Second blog post','dummy');

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

MySQL LEFT Function


Summary: in this tutorial, you will learn how to use the MySQL LEFT function to return the left part of a
string with a specified length.

Introduction to MySQL LEFT function


The LEFT function is a string function that returns the left part of a string with a specified length.
The following shows the syntax of the LEFT function.

1 LEFT(str,length);

The LEFT function accepts two arguments:

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.

MySQL LEFT function examples


Using MySQL LEFT function with literal strings example
The following statement uses the LEFT function to return the 5 leftmost characters of the string MySQL
LEFT .

1 SELECT LEFT('MySQL LEFT', 5);

48 of 142
The following statement returns the entire string because the length exceeds the length of the string.

1 SELECT LEFT('MySQL LEFT', 9999);

The following statements return an empty string because the length is zero or negative.

1 SELECT LEFT('MySQL LEFT', 0);


2 SELECT LEFT('MySQL LEFT', -2);

The following statement returns a NULL value because the length is NULL

1 SELECT LEFT('MySQL LEFT', NULL);

Using MySQL LEFT function with a column example


Let’s take a look at the products table in the sample database.

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) Take the leftmost 50 characters of the productDescription column.

1 SELECT
2 LEFT(productdescription, 50)
3 FROM
4 products;

2) Reverse the substring using the REVERSE function.

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;

6) Take the leftmost last_space_pos characters of the product description.

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.

MySQL Replace String Function


Summary: in this tutorial, we will show you how to use MySQL REPLACE string function to replace a
substring by another in a string.

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.

The syntax of the REPLACE function is as follows:

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.

The syntax of using the REPLACE function in an UPDATE statement is as follows:

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.

MySQL REPLACE string function example


For example, if you want to correct the spelling mistake in the products table in the sample database,
you use the REPLACE function as follows:

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

MySQL SUBSTRING Function


Summary: in this tutorial, we will introduce you to the MySQL SUBSTRING function that extracts a
substring from a string.

The SUBSTRING function returns a substring with a given length from a string starting at a specific position.

MySQL provides various forms of the substring function.

We will examine each form of the SUBSTRING function in the following sections.

MySQL SUBSTRING with position parameter


The following illustrates the first form the SUBSTRING function.

1 SUBSTRING(string,position);
2 SUBSTRING(string FROM position);

There are two arguments:

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:

1 SELECT SUBSTRING('MYSQL SUBSTRING', 7);

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:

1 SELECT SUBSTRING('MySQL SUBSTRING',-10);

Notice that if the position is zero, the SUBSTRING function returns an empty string:

1 SELECT SUBSTRING('MYSQL SUBSTRING', 0);

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 SELECT SUBSTRING('MySQL SUBSTRING' FROM -10);

MySQL SUBSTRING with position and length


If you want to specify the length of the substring that you want to extract from a string, you can use the
following form of the SUBSTRING function:

1 SUBSTRING(string,position,length);

The following is the SQL-standard version of above statement, which is longer but more expressive.

1 SUBSTRING(string FROM position FOR length);

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

1 SELECT SUBSTRING('MySQL SUBSTRING' FROM 1 FOR 5);

In case you want to use the negative position, you use the following statement:

1 SELECT SUBSTRING('MySQL SUBSTRING',-15,5);

Or with the FROM FOR syntax:

1 SELECT SUBSTRING('MySQL SUBSTRING' FROM -15 FOR 5);

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.

MySQL TRIM Function


Summary: in this tutorial, we will show you how to use the MySQL TRIM function to remove the unwanted
leading and trailing characters from a string.

Introduction to the MySQL TRIM function


The data from user’s input is typically not what we expected. Sometimes, it is not well-formed, for
example, wrong cases, or some even contain leading and trailing spaces and also other unwanted
characters.

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.

1 TRIM([{BOTH|LEADING|TRAILING} [removed_str]] FROM str);

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 st r is the string that you want to remove the removed_str.

The TRIM function returns a string that has unwanted characters removed.

MySQL TRIM function examples


The following statement removes both leading and trailing spaces from a string.
1 SELECT TRIM(' MySQL TRIM Function ');

The following statement removes only leading spaces.


1 SELECT TRIM(LEADING FROM ' MySQL TRIM Function ');

The following statement removes only trailing spaces.


1 SELECT TRIM(TRAILING FROM ' MySQL TRIM Function ');

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.

MySQL LTRIM and RTRIM function


If you want to remove only leading or trailing spaces, you can use other string
functions: LTRIM and RTRIM .

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.

1 SELECT RTRIM('MySQL RTRIM function ');

In this tutorial, you have learned how to use the TRIM function to remove the unwanted leading and
trailing characters from a string.

MySQL FIND_IN_SET Function


Summary: in this tutorial, you will learn how to use the MySQL FIND_IN_SET function to return the
position of a string in a comma-separated list of strings.

Introduction to MySQL FIND_IN_SET function


MySQL provides a built-in string function called FIND_IN_SET that allows you to find the position of a
string within a comma-separated list of strings.
The following illustrates the syntax of the FIND_IN_SET function.

1 FIND_IN_SET(needle,haystack);

The FIND_IN_SET function accepts two parameters:

 The first parameter needle is the string that you want to find.

 The second parameter haystack is a list of comma-separated strings that to be searched.

The FIND_IN_SET function returns an integer or a NULL value depending on the value of the arguments:

 Return a NULL value if either needle or haystack is NULL.

 Return zero if the needle is not in the haystack or the haystack is an empty string.

 Return a positive integer if the needle is in the haystack .

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.

The MySQL FIND_IN_SET examples


Let’s take some examples to see how the MySQL FIND_IN_SET works.

MySQL FIND_IN_SET: simple examples


The following statement returns 2 because it is the second position of ‘x,y,z’ string.

1 SELECT FIND_IN_SET('y','x,y,z'); -- 2

The following statement returns 0 because a is not in the ‘x,y,z’ list.

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);

MySQL FIND_IN_SET: querying data from table example.


We will create a new table named divisions for the demonstration purpose.

First, create the divisions table using the following statement.

1 CREATE TABLE IF NOT EXISTS divisions (


2 id INT AUTO_INCREMENT PRIMARY KEY,
3 name VARCHAR(25) NOT NULL,
4 belts VARCHAR(200) NOT NULL
5 );

Second, insert some rows into the divisions table.


59 of 142
1 INSERT INTO divisions(name,belts)
2 VALUES ('O-1','white,yellow,orange'),
3 ('O-2','purple,green,blue'),
4 ('O-3','brown,red,black'),
5 ('O-4','white,yellow,orange'),
6 ('O-5','purple,green,blue'),
7 ('O-6','brown,red'),
8 ('O-7','black'),
9 ('O-8','white,yellow,orange'),
10 ('O-9','purple,green,blue'),
11 ('O-10','brown,red');

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);

MySQL NOT FIND_IN_SET example


Because the FIND_IN_SET function returns zero, which is FALSE in MySQL, when the first argument is
not found in the second argument. Therefore, you can use the NOT operator to negate
the FIND_IN_SET function.

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');

So the column IN (x, y, z) expression is the same as FIND_IN_SET(column, 'x,y,z') .


The IN operator can take any number of arguments, each separated by a comma. However,
the FIND_IN_SET function takes only two arguments.

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.

Introduction to the MySQL FORMAT function


Sometimes, you use an expression or an aggregate function such as AVG to calculate values in the
databases such as inventory turnover, the average net price of products, the average invoice value, etc.

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 FORMAT function accepts three arguments:

 The N is the number that you want to format.


 The D is the number of decimal places that you want to round.
 The locale is an optional argument that determines the thousand separators and grouping between
separators. If you omit the locale operator, MySQL will use en_US by default. The following link
provides all locale names supported by MySQL.

MySQL FORMAT function examples


See the following examples of using the FORMAT function.

1 SELECT FORMAT(12500.2015, 2);

The following statement uses the FORMAT function with the second argument zero, therefore, the result
does not have any decimal places.

1 SELECT FORMAT(12500.2015, 0);

62 of 142
The following statement uses the de_DE locale instead of the en_US locale:

1 SELECT FORMAT(12500.2015, 2,'de_DE');

As you see in the result, the de_DE locale use dot (.) for grouping thousand and comma (,) for decimal
mark.

Let’s take a look at the products table in the sample database.

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.

C. MySQL control flow functions


 CASE – return the corresponding result in THEN branch if the condition in the WHEN branch is
satisfied, otherwise return the result in the ELSE branch.

 IF – return a value based on a given condition.

 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.

MySQL CASE Expression


Summary: in this tutorial, we will show you how to use MySQL CASE expression to construct conditional
queries.

Introduction to MySQL CASE expression


MySQL CASE expression is a flow control structure that allows you to construct conditions inside a query
such as SELECT or WHERE clause. MySQL provides you with two forms of the CASE expressions.

The following illustrates the first form of the CASE expression.

1 CASE value
2 WHEN compare_value_1 THEN result_1
3 WHEN compare_value_2 THEN result_2
4…
5 ELSE result END

If the value is equal to compare_value e.g., compare_value_1 , compare_value_2 , etc., then


the CASE expression returns the corresponding result i.e., result_1 , result_2 . In case the value does
not match any compare_value , the CASE expression returns the result specified in the ELSE clause.

The second form of the CASE expression is as follows:

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.

MySQL CASE function examples


Let’s take a look at the customers table in the sample database.

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;

The result of the query is as follows:

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.

MySQL IF statement syntax


The following illustrates the syntax of the IF statement:
1 IF expression THEN
2 statements;
3 END IF;

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 .

The following flowchart demonstrates the IF statement:

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;

The following flowchart illustrates the IF ELSE statement:

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;

If the expression evaluates to TRUE , the statements in the IF branch executes. If


the expression evaluates to FALSE , MySQL will check the elseif-expression and execute the elseif-
statements in the ELSEIF branch if the elseif_expression evaluates to TRUE .

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.

MySQL IF statement examples


The following example illustrates how to use the IF ESLEIF ELSE statement.
The GetCustomerLevel() stored procedure accepts two parameters customer number and customer
level.

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$$

The following flowchart demonstrates the logic of determining customer level.

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.

Introduction to MySQL IFNULL function


MySQL IFNULL function is one of the MySQL control flow functions that accepts two arguments and
returns the first argument if it is not NULL . Otherwise, the IFNULL function returns the second argument.
The two arguments can be literal values or expressions.

The following illustrates the syntax of the IFNULL function:

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.

MySQL IFNULL function examples


See the following IFNULL function examples:

1 SELECT IFNULL(1,0); -- returns 1

1 SELECT IFNULL('',1); -- returns ''

1 SELECT IFNULL(NULL,'IFNULL function'); -- returns IFNULL function

How it works.

 IFNULL(1,0) returns 1 because 1 is not NULL .

 IFNULL(' ',1) returns ' ' because the ' ' string is not NULL .

 IFNULL(NULL,'IFNULL function') returns IFNULL function string because the first argument

is NULL .

Let’s take a practical example of using the IFNULL function.

First, create a new table named contacts using the following statement:

1 CREATE TABLE IF NOT EXISTS contacts (


2 contactid INT AUTO_INCREMENT PRIMARY KEY,
3 contactname VARCHAR(20) NOT NULL,
4 bizphone VARCHAR(15),
5 homephone VARCHAR(15)
6 );

Each contact has a name, business phone and home phone.

Second, insert data into the contacts table:

1 INSERT INTO contacts(contactname,bizphone,homephone)


2 VALUES('John Doe','(541) 754-3009',NULL),

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.

Introduction to MySQL NULLIF function


The NULLIF function is one of the control flow functions that accepts 2 arguments. The NULLIF function
returns NULL if the first argument is equal to the second argument, otherwise it returns the first argument.

The syntax of the NULLIF function is as follows:

1 NULLIF(expression_1,expression_2);

The NULLIF function returns NULL if expression_1 = expression_2 is true , otherwise it


returns expression_1

Notice that the NULLIF function is similar to the following expression that uses the CASE expression:

1 CASE WHEN expression_1 = expression_2


2 THEN NULL
3 ELSE
4 expression_1
5 END;

Note that you should not confuse the NULLIF function a similar function called IFNULL function.

MySQL NULLIF examples


Let’s take a look at some examples of using the NULLIF function to understand how it works.

1 SELECT NULLIF(1,1); -- return NULL


1 SELECT NULLIF(1,2); -- return 1
1 SELECT NULLIF('MySQL NULLIF','MySQL NULLIF'); -- return NULL
1 SELECT NULLIF('MySQL NULLIF','MySQL IFNULL'); -- return MySQL NULLIF
1 SELECT NULLIF(1,NULL); -- return 1 because 1 <=> NULL
1 SELECT NULLIF(NULL,1); -- return NULL the first argument

How the statements work.

76 of 142
 NULIF(1,1) returns NULL because 1 is equal 1.

 NULLIF(1,2) returns 1, which is the first argument, because 1 is not equal 2.


 NULLIF('MySQL NULLIF','MySQL NULLIF') returns NULL because two arguments are the same

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.

Using NULLIF function to prevent division by zero error


We often use the NULLIF function to prevent the division by zero error in a query. If the MySQL server
has ERROR_FOR_DIVISION_BY_ZERO mode enabled, it will issue an error when a division by zero
occurred.

See the following statement:

1 SELECT 1/0; -- cause error

In this case, you can use the NULLIF function to prevent the division by zero as follows:

1 SELECT 1/NULLIF(0,0); -- return NULL

Because zero is equal to zero, the expression NULLIF(0,0) returns NULL. As the result, the statement
returns NULL.

Let’s take a look at the orders table in the sample database.

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.

1 SELECT SUM(IF(status = 'Shipped',1,0)) /


2 SUM(IF(status = 'Cancelled',1,0))
3 FROM orders
4 WHERE orderDate BETWEEN '2003-06-01' and '2003-06-30';

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.

D. MySQL date and time functions


 CURDATE – return the current date.
 DATEDIFF – calculate the number of days between two DATE values.

 DAY – get the day of the month of a specified date.


 DATE_ADD – add a time value to date value.
 DATE_SUB – subtract a time value from a date value.
 DATE_FORMAT – format a date value based on a specified date format.
 DAYNAME – get the name of a weekday for a specified date.
 DAYOFWEEK – return the weekday index for a date.
 EXTRACT – extract part of a date.
 NOW – return the current date and time at which the statement executed.
 MONTH – return an integer that represents a month of a specified date.
 STR_TO_DATE – convert a string into a date and time value based on a specified format.
 SYSDATE – return the current date.
 TIMEDIFF – calculate the difference between two TIME or DATETIME values.

 TIMESTAMPDIFF – calculate the difference between two DATE or DATETIME values..

 WEEK – return a week number of a date.


 WEEKDAY – return a weekday index for a date.
 YEAR – return the year part of a date value.

MySQL CURDATE Function


Summary: in this tutorial, you will learn how to use the MySQL CURDATE() function to get the current
date.

Introduction to MySQL CURDATE function


The CURDATE() function returns the current date as a value in the 'YYYY-MM-DD' format if it is used in a
string context or YYYMMDD format if it is used in a numeric context.

79 of 142
The following example shows how the CURDATE() function is used in the string context.

1 mysql> SELECT CURDATE();


2 +------------+
3 | CURDATE() |
4 +------------+
5 | 2017-07-13 |
6 +------------+
7 1 row in set (0.00 sec)

And the following example illustrates how the CURDATE() function is used in a numeric context:

1 mysql> SELECT CURDATE() + 0;


2 +---------------+
3 | CURDATE() + 0 |
4 +---------------+
5| 20170713 |
6 +---------------+
7 1 row in set (0.04 sec)

The CURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE() .


1 mysql> SELECT CURRENT_DATE(),
2 CURRENT_DATE,
3 CURDATE();
4 +----------------+--------------+------------+
5 | CURRENT_DATE() | CURRENT_DATE | CURDATE() |
6 +----------------+--------------+------------+
7 | 2017-07-13 | 2017-07-13 | 2017-07-13 |
8 +----------------+--------------+------------+
9 1 row in set (0.00 sec)

CURDATE vs. NOW


The CURDATE() function returns the current date with date part only while the NOW() function returns both
date and time parts of the current time.

The result of the CURDATE() function is equivalent to the following expression:

1 mysql> SELECT DATE(NOW());


2 +-------------+
3 | DATE(NOW()) |
4 +-------------+
5 | 2017-07-13 |
6 +-------------+
7 1 row in set (0.00 sec)

In this tutorial, you have learned how to use the MySQL CURDATE() function to get the current date value.

MySQL DATEDIFF Function


Summary: in this tutorial, you will learn how to use the MySQL DATEDIFF function to calculate the
number of days between two date values.

80 of 142
Introduction to MySQL DATEDIFF function
The MySQL DATEDIFF function calculates the number of days between two DATE , DATETIME , or
TIMESTAMP values.

The syntax of the MySQL DATEDIFF function is as follows:

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.

MySQL DATEDIFF examples


Let’s take a look at some examples of using the DATEDIFF function.

1 SELECT DATEDIFF('2011-08-17','2011-08-17'); -- 0 day

1 SELECT DATEDIFF('2011-08-17','2011-08-08'); -- 9 days

1 SELECT DATEDIFF('2011-08-08','2011-08-17'); -- -9 days

See the following orders table in the sample database.

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.

MySQL DAY Function


Summary: in this tutorial, you will learn how to use the MySQL DAY function to get the day of the month of
a specified date.

Introduction to MySQL DAY function


The DAY function returns the day of the month of a given date. The following shows the syntax of
the DAY function:

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 .

Note that DAY function is the synonym of the DAYOFMONTH function.

MySQL DAY function examples


The following example returns the day of the month of 2010-01-15 :

1 mysql> SELECT DAY('2010-01-15');


2 +-------------------+
3 | DAY('2010-01-15') |
4 +-------------------+
5| 15 |
6 +-------------------+
7 1 row in set (0.00 sec)

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:

1 mysql> SELECT DAY(LAST_DAY('2016-02-03'));


2 +-----------------------------+
3 | DAY(LAST_DAY('2016-02-03')) |

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.

MySQL DATE_ADD Function


Summary: in this tutorial, you will learn how to use MySQL DATE_ADD function to add a time value to
a DATE or DATETIME value.

Introduction to MySQL DATE_ADD function


The DATE_ADD function adds an interval to a DATE or DATETIME value. The following illustrates the syntax
of the DATE_ADD function:

1 DATE_ADD(start_date, INTERVAL expr unit);

The DATE_ADD function takes two arguments:

 start_date is a starting DATE or DATETIME value

 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.

MySQL DATE_ADD function examples


Let’s take a look few examples to understand how DATE_ADD function works.
Add 1 second to 1999-12-31 23:59:59 :

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)

Add 1 day to 1999-12-31 00:00:01 :

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)

Add 1 minute and 1 second to 1999-12-31 23:59:59 .

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 DATE_ADD('2000-01-01 00:00:00',


2 INTERVAL '-1 5' DAY_HOUR) result;
3
4 +---------------------+
5 | result |
6 +---------------------+
7 | 1999-12-30 19:00:00 |
8 +---------------------+
9 1 row in set (0.00 sec)

Add 1 second and 999999 microseconds to 1999-12-31 23:59:59.000002 :

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)

MySQL DATE_ADD function usage notes

Interval Handling
In the interval:

1 INTERVAL expr unit

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)

Automatic DATETIME conversion


If you add a time value to a date value, the result is a DATETIME value as shown in the following example:

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)

Invalid starting date


The DATE_ADD function returns NULL if you use an invalid date for the first argument, for example:

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)

Adjusted day, month, or year


If you add an interval of MONTH , YEAR , or YEAR_MONTH to a date that results in a date which has a day
larger than the maximum day for the new month, the day will be adjusted to the maximum day in the new
month.

Consider the following example:

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.

MySQL DATE_SUB Function


Summary: in this tutorial, you will learn how to subtract a time value from a date using the
MySQL DATE_SUB() function.

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:

1 DATE_SUB(start_date,INTERVAL expr unit)

The DATE_SUB() function accepts two arguments:

 start_date is the starting DATE or DATETIME value.

 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 :

1 SELECT DATE_SUB('2017-07-04',INTERVAL 1 DAY) result;


2 +------------+
3 | result |
4 +------------+
5 | 2017-07-03 |
6 +------------+
7 1 row in set (0.00 sec)

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.

See the following example:

1 SELECT DATE_SUB('2017-07-04',INTERVAL 3 HOUR) result;


2
3 +---------------------+
4 | result |
5 +---------------------+
6 | 2017-07-03 21:00:00 |
7 +---------------------+
8 1 row in set (0.00 sec)

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:

1 SELECT DATE_SUB('2017-07-03',INTERVAL -1 DAY) result;


2 +------------+
3 | result |
4 +------------+
5 | 2017-07-04 |
6 +------------+
7 1 row in set (0.00 sec)

MySQL DATE_SUB : Invalid or malformed date


If the first argument of the DATE_SUB() function is malformed, invalid date, or NULL ,
the DATE_SUB() function returns NULL .

1 SELECT DATE_SUB('2017-02-29', INTERVAL - 1 DAY) result;


2 +--------+
3 | result |
4 +--------+
5 | NULL |
6 +--------+
7 1 row in set, 1 warning (0.00 sec)

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:

1 SELECT DATE_SUB('03/07/2017', INTERVAL 1 DAY) result;


2 +--------+
3 | result |
4 +--------+
5 | NULL |
6 +--------+
7 1 row in set, 1 warning (0.00 sec)
8
9
10 SELECT DATE_SUB(NULL, INTERVAL 1 DAY) result;

91 of 142
11 +--------+
12 | result |
13 +--------+
14 | NULL |
15 +--------+
16 1 row in set (0.00 sec)

MySQL DATE_SUB : automatic adjusted day


If you subtract an interval of MONTH , YEAR , or YEAR_MONTH from a date which results in a date that has a
day bigger than the maximum day for the new month, the day will be adjusted to the maximum day in the
new month.

Consider the following statement:

1 SELECT DATE_SUB('2017-03-30', INTERVAL 1 MONTH) result;


2 +------------+
3 | result |
4 +------------+
5 | 2017-02-28 |
6 +------------+
7 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.

MySQL DATE_FORMAT Function


Summary: in this tutorial, you will learn how to use the MySQL DATE_FORMAT function to format a date
value based on a specific format.

Introduction to MySQL DATE_FORMAT function


To format a date value to a specific format, you use the DATE_FORMAT function. The syntax of
the DATE_FORMAT function is as follows:

1 DATE_FORMAT(date,format)

The DATE_FORMAT function accepts two arguments:

 date : is a valid date value that you want to 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

%a Three-characters abbreviated weekday name e.g., Mon, Tue, Wed, etc.

%b Three-characters abbreviated month name e.g., Jan, Feb, Mar, etc.

%c Month in numeric e.g., 1, 2, 3…12

%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

%e Day of the month without leading zero e.g., 1,2,…31

%f Microseconds in the range of 000000..999999

%H Hour in 24-hour format with leading zero e.g., 00..23

%h Hour in 12-hour format with leading zero e.g., 01, 02…12

%I Same as %h

%i Minutes with leading zero e.g., 00, 01,…59

%j Day of year with leading zero e.g., 001,002,…366

%k Hour in 24-hour format without leading zero e.g., 0,1,2…23

%l Hour in 12-hour format without leading zero e.g., 1,2…12

%M Full month name e.g., January, February,…December

%m Month name with leading zero e.g., 00,01,02,…12

%p AM or PM, depending on other time specifiers

%r Time in 12-hour format hh:mm:ss AM or PM

%S Seconds with leading zero 00,01,…59

%s Same as %S

%T Time in 24-hour format hh:mm:ss


93 of 142
Specifier Meaning

%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

%V Same as %U; it is used with %X

%v Same as %u; it is used with %x

%W Full name of weekday e.g., Sunday, Monday,…, Saturday

%w Weekday in number (0=Sunday, 1= Monday,etc.)

%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 Four digits year e.g., 2000, 2001,…etc.

%y Two digits year e.g., 10,11,12, etc.

%% Add percentage (%) character to the output

The following are some commonly used date format strings:

DATE_FORMAT string Formatted date

%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

%e/%c/%Y %H:%i 4/7/2013 11:20

%c/%e/%Y %H:%i 7/4/2013 11:20

%d/%m/%Y %H:%i 4/7/2013 11:20

94 of 142
DATE_FORMAT string Formatted date

%m/%d/%Y %H:%i 7/4/2013 11:20

%e/%c/%Y %T 4/7/2013 11:20

%c/%e/%Y %T 7/4/2013 11:20

%d/%m/%Y %T 4/7/2013 11:20

%m/%d/%Y %T 7/4/2013 11:20

%a %D %b %Y Thu 4th Jul 2013

%a %D %b %Y %H:%i Thu 4th Jul 2013 11:20

%a %D %b %Y %T Thu 4th Jul 2013 11:20:05

%a %b %e %Y Thu Jul 4 2013

%a %b %e %Y %H:%i Thu Jul 4 2013 11:20

%a %b %e %Y %T Thu Jul 4 2013 11:20:05

%W %D %M %Y Thursday 4th July 2013

%W %D %M %Y %H:%i Thursday 4th July 2013 11:20

%W %D %M %Y %T Thursday 4th July 2013 11:20:05

%l:%i %p %b %e, %Y 7/4/2013 11:20

%M %e, %Y 4-Jul-13

%a, %d %b %Y %T Thu, 04 Jul 2013 11:20:05

MySQL DATE_FORMAT examples


Let’s take a look at the orders table in the sample database.

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.

MySQL DATE_FORMAT with ORDER BY


See the following example:

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.

MySQL DAYNAME Function


Summary: in this tutorial, you will learn how to use the MySQL DAYNAME function to get the name of a
weekday for a given date.

Introduction to MySQL DAYNAME function


MySQL DAYNAME function returns the name of a weekday for a specified date. The following illustrates the
syntax of the DAYNAME function:

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 .

MySQL DAYNAME function examples


The following example returns the name of a weekday for January 1st, 2000 .

1 mysql> SELECT DAYNAME('2000-01-01') dayname;


2 +----------+
3 | dayname |
4 +----------+
5 | Saturday |
6 +----------+
7 1 row in set (0.00 sec)

By default, MySQL returns the name of a weekday in the language controlled by


the lc_time_names system variable.

1 mysql> SELECT @@lc_time_names;


2 +-----------------+
3 | @@lc_time_names |
4 +-----------------+
5 | en_US |
6 +-----------------+
7 1 row in set (0.00 sec)

As you can see, currently, the locale is set to en_US .

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:

1 mysql> SET @@lc_time_names = 'fr_FR';


2 Query OK, 0 rows affected (0.00 sec)

Now, let’s query the name of weekday for January 1st, 2000 :

1 mysql> SELECT DAYNAME('2000-01-01') dayname;


2 +---------+
3 | dayname |
4 +---------+
5 | samedi |
6 +---------+
7 1 row in set (0.00 sec)

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:

Albanian – Albania sq_AL Gujarati – India gu_IN


Arabic – Algeria ar_DZ Hebrew – Israel he_IL
Arabic – Bahrain ar_BH Hindi – India hi_IN
Arabic – Egypt ar_EG Hungarian – Hungary hu_HU

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

See the following orders table in the sample database:

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.

MySQL DAYOFWEEK Function


The DAYOFWEEK function returns the weekday index for a date i.e., 1 for Sunday, 2 for Monday, … 7 for
Saturday. These index values correspond to the ODBC standard.

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.

The following example returns weekday index of December 1st, 2010

1 mysql> SELECT DAYNAME('2012-12-01'), DAYOFWEEK('2012-12-01');


2 +-----------------------+-------------------------+
3 | DAYNAME('2012-12-01') | DAYOFWEEK('2012-12-01') |
4 +-----------------------+-------------------------+
5 | Saturday | 7|
6 +-----------------------+-------------------------+
7 1 row in set (0.00 sec)

In this query, the DAYNAME function returns weekday’s name while DAYOFWEEK function returns the
weekday index of December 1st, 2011 .

MySQL EXTRACT Function


Summary: in this tutorial, you will learn how to use the MySQL EXTRACT() function to extract part of
a DATE or DATETIME value.

Introduction to the MySQL EXTRACT function


The EXTRACT() function extracts part of a date. The following illustrates the syntax of
the EXTRACT() function.

1 EXTRACT(unit FROM date)

The EXTRACT() function requires two arguments unit and date .

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.

MySQL EXTRACT function examples


Extract day from a datetime:

1 mysql> SELECT EXTRACT(DAY FROM '2017-07-14 09:04:44') DAY;


2 +------+
3 | DAY |
4 +------+
5 | 14 |
6 +------+
7 1 row in set (0.00 sec)

Extract day_hour from a datetime:

1 mysql> SELECT EXTRACT(DAY_HOUR FROM '2017-07-14 09:04:44') DAYHOUR;


2 +---------+
3 | DAYHOUR |
4 +---------+
5 | 1409 |
6 +---------+
7 1 row in set (0.00 sec)

Extract day_microsecond from a datetime:

1 mysql> SELECT EXTRACT(DAY_MICROSECOND FROM '2017-07-14 09:04:44') DAY_MS;


2 +----------------+
3 | DAY_MS |
4 +----------------+
5 | 14090444000000 |
6 +----------------+
7 1 row in set (0.00 sec)

Extract day_minute from a datetime:

1 mysql> SELECT EXTRACT(DAY_MINUTE FROM '2017-07-14 09:04:44') DAY_M;


2 +--------+
3 | DAY_M |
4 +--------+
5 | 140904 |
102 of 142
6 +--------+
7 1 row in set (0.00 sec)

Extract day_second from a datetime

1 mysql> SELECT EXTRACT(DAY_SECOND FROM '2017-07-14 09:04:44') DAY_S;


2 +----------+
3 | DAY_S |
4 +----------+
5 | 14090444 |
6 +----------+
7 1 row in set (0.00 sec)

Extract hour from a datetime:

1 mysql> SELECT EXTRACT(HOUR FROM '2017-07-14 09:04:44') HOUR;


2 +------+
3 | HOUR |
4 +------+
5| 9|
6 +------+
7 1 row in set (0.00 sec)

Extract hour_microsecond from a datetime:

1 mysql> SELECT EXTRACT(HOUR_MICROSECOND FROM '2017-07-14 09:04:44') HOUR_MS;


2 +-------------+
3 | HOUR_MS |
4 +-------------+
5 | 90444000000 |
6 +-------------+
7 1 row in set (0.00 sec)

Extract hour_minute from a datetime:

1 mysql> SELECT EXTRACT(HOUR_MINUTE FROM '2017-07-14 09:04:44') HOUR_M;


2 +--------+
3 | HOUR_M |
4 +--------+
5 | 904 |
6 +--------+
7 1 row in set (0.00 sec)

103 of 142
Extract hour_second from a datetime:

1 mysql> SELECT EXTRACT(HOUR_SECOND FROM '2017-07-14 09:04:44') HOUR_S;


2 +--------+
3 | HOUR_S |
4 +--------+
5 | 90444 |
6 +--------+
7 1 row in set (0.00 sec)

Extract microsecond from a datetime:

1 mysql> SELECT EXTRACT(MICROSECOND FROM '2017-07-14 09:04:44') MICROSECOND;


2 +-------------+
3 | MICROSECOND |
4 +-------------+
5| 0|
6 +-------------+
7 1 row in set (0.00 sec)

Extract minute from a datetime:

1 mysql> SELECT EXTRACT(MINUTE FROM '2017-07-14 09:04:44') MINUTE;


2 +--------+
3 | MINUTE |
4 +--------+
5| 4|
6 +--------+
7 1 row in set (0.00 sec)

Extract minute_microsecond from a datetime:

1 mysql> SELECT EXTRACT(MINUTE_MICROSECOND FROM '2017-07-14 09:04:44') MINUTE_MS;


2 +-----------+
3 | MINUTE_MS |
4 +-----------+
5 | 444000000 |
6 +-----------+
7 1 row in set (0.00 sec)

Extract minute_second from a datetime:

1 mysql> SELECT EXTRACT(MINUTE_SECOND FROM '2017-07-14 09:04:44') MINUTE_S;


2 +----------+
3 | MINUTE_S |
4 +----------+
5| 444 |
6 +----------+
7 1 row in set (0.00 sec)

104 of 142
Extract month from a datetime:

1 mysql> SELECT EXTRACT(MONTH FROM '2017-07-14 09:04:44') MONTH;


2 +-------+
3 | MONTH |
4 +-------+
5| 7|
6 +-------+
7 1 row in set (0.00 sec)

Extract quarter from a datetime:

1 mysql> SELECT EXTRACT(QUARTER FROM '2017-07-14 09:04:44') QUARTER;


2 +---------+
3 | QUARTER |
4 +---------+
5| 3|
6 +---------+
7 1 row in set (0.00 sec)

Extract second from a datetime:

1 mysql> SELECT EXTRACT(SECOND FROM '2017-07-14 09:04:44') SECOND;


2 +--------+
3 | SECOND |
4 +--------+
5 | 44 |
6 +--------+
7 1 row in set (0.00 sec)

Extract second_microsecond from a datetime:

1 mysql> SELECT EXTRACT(SECOND_MICROSECOND FROM '2017-07-14 09:04:44') SECOND_MS;


2 +-----------+
3 | SECOND_MS |
4 +-----------+
5 | 44000000 |
6 +-----------+
7 1 row in set (0.00 sec)

Extract week from a datetime:

1 mysql> SELECT EXTRACT(WEEK FROM '2017-07-14 09:04:44') WEEK;


2 +------+
3 | WEEK |
4 +------+
5 | 28 |

105 of 142
6 +------+
7 1 row in set (0.00 sec)

Extract year from a datetime:

1 mysql> SELECT EXTRACT(YEAR FROM '2017-07-14 09:04:44') YEAR;


2 +------+
3 | YEAR |
4 +------+
5 | 2017 |
6 +------+
7 1 row in set (0.00 sec)

Extract year_month from a datetime

1 mysql> SELECT EXTRACT(YEAR_MONTH FROM '2017-07-14 09:04:44') YEARMONTH;


2 +-----------+
3 | YEARMONTH |
4 +-----------+
5 | 201707 |
6 +-----------+
7 1 row in set (0.00 sec)
I
n this tutorial, you have learned how to use the MySQL EXTRACT() function to extract part of
a DATE or DATETIME value.

MySQL NOW() Function


Summary: in this tutorial, you will learn about the MySQL NOW() function and apply the NOW function in
various contexts.

Introduction to MySQL NOW() function


The MySQL NOW() function returns the current date and time in the configured time zone as a string or a
number in the 'YYYY-MM-DD HH:MM:DD' or 'YYYYMMDDHHMMSS.uuuuuu' format.

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:

1 SELECT NOW(), SLEEP(5), NOW();

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:

1 SET time_zone = your_time_zone;

MySQL NOW() function calculations


Because the NOW() function returns a number when it is used in a numeric context, you can use it in
calculations e.g., now plus 1 hour, now minus 1 hour, now plus 1 day and now minus in day, etc.
The following statement returns the current date and time, now minus 1 hour and now plus 1 hour:
1 -- mysql now minus 1 hour
2 SELECT (NOW() - INTERVAL 1 HOUR) 'NOW - 1 hour',
3 NOW(),
4 -- mysql now plus 1 hour
5 NOW() + INTERVAL 1 HOUR 'NOW + 1 hour';

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';

MySQL NOW() as a default value for a column


You can use the NOW() function as a default value for a DATETIME or TIMESTAMP column. When you omit
the date or time value in the INSERT statement, MySQL inserts the current date and time into the column
whose default value is NOW() .

Let’s take a look at the following example.

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.

1 CREATE TABLE tmp(


2 id INT PRIMARY KEY AUTO_INCREMENT,
3 title VARCHAR(255) NOT NULL,
4 created_on DATETIME NOT NULL DEFAULT NOW() -- or CURRENT_TIMESTAMP
5 );

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:

1 INSERT INTO tmp(title)


2 VALUES('Test NOW() function');

Third, query the data from the tmp table:

1 SELECT * FROM tmp;

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.

MySQL MONTH Function


Summary: in this tutorial, you will learn how to use the MySQL MONTH function to get the month of a given
date.

Introduction to MySQL MONTH function

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 .

MySQL MONTH function examples

The following example shows how to get the month of 2010-01-01 :

1 mysql> SELECT MONTH('2010-01-01');


2 +---------------------+
3 | MONTH('2010-01-01') |
4 +---------------------+
5| 1|
6 +---------------------+
7 1 row in set (0.00 sec)

To get the current month, you use the following statement:

1 mysql> SELECT MONTH(NOW()) CURRENT_MONTH;


2 +---------------+
3 | CURRENT_MONTH |
4 +---------------+
5| 7|
6 +---------------+
7 1 row in set (0.00 sec)

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:

1 mysql> SELECT MONTH('0000-00-00');


2 +---------------------+
3 | MONTH('0000-00-00') |
4 +---------------------+
5| 0|
6 +---------------------+
7 1 row in set (0.00 sec)

The MONTH function returns NULL if the input date value is NULL :

1 mysql> SELECT MONTH(NULL);


2 +-------------+
3 | MONTH(NULL) |
4 +-------------+
5| NULL |
6 +-------------+
7 1 row in set (0.00 sec)

Practical usages of MySQL MONTH function


See the following orders and orderdetails tables in the sample database:

The following statement gets the order’s volume by month in 2004:

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.

5. The GROUP BY clause groups the subtotal by month.

In this tutorial, you have learned how to use the MySQL MONTH function to get a month of a specified date.

MySQL STR_TO_DATE() Function


Summary: in this tutorial, we will show you how to use the MySQL STR_TO_DATE() function to convert a
string into a date time value.

Introduction to MySQL STR_TO_DATE function


The following illustrates the syntax of the STR_TO_DATE() function:

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.

MySQL STR_TO_DATE examples


Let’s look at some examples of using STR_TO_DATE() function to convert strings into a date and/or time
values

The following statement converts a string into a DATE value.

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:

1 SELECT STR_TO_DATE('21,5,2013 extra characters','%d,%m,%Y');

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.

The following example converts a time string into a TIME value:

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.

1 SELECT STR_TO_DATE('20130101 1130','%Y%m%d %h%i') ;

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.

MySQL SYSDATE Function


Summary: in this tutorial, you will learn about the MySQL SYSDATE() function and its caveat.

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.

See the following example.


1 mysql> SELECT SYSDATE();
2 +---------------------+
3 | SYSDATE() |
4 +---------------------+
5 | 2017-07-13 17:42:37 |
6 +---------------------+
7 1 row in set (0.00 sec)

If you pass the fsp argument, the result will include the fractional seconds precision as shown in the
following example:

1 mysql> SELECT SYSDATE(3);


2 +-------------------------+
3 | SYSDATE(3) |
4 +-------------------------+
5 | 2017-07-13 17:42:55.875 |
6 +-------------------------+
7 1 row in set (0.00 sec)

SYSDATE vs. NOW


Consider the following example.
1 mysql> SELECT SYSDATE(),
2 NOW();
3 +---------------------+---------------------+
4 | SYSDATE() | NOW() |
5 +---------------------+---------------------+
6 | 2017-07-13 17:46:30 | 2017-07-13 17:46:30 |
7 +---------------------+---------------------+
8 1 row in set (0.00 sec)

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.

Let’s change the NOW() function to SYSDATE() function:

1 mysql> SELECT SYSDATE(), SLEEP(5), SYSDATE();


2 +---------------------+----------+---------------------+
3 | SYSDATE() | SLEEP(5) | SYSDATE() |
4 +---------------------+----------+---------------------+
5 | 2017-07-13 17:50:57 | 0 | 2017-07-13 17:51:02 |
6 +---------------------+----------+---------------------+
7 1 row in set (5.00 sec)

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.

1 CREATE TABLE tests (


2 id INT AUTO_INCREMENT PRIMARY KEY,
3 t DATETIME UNIQUE
4 );
5
6
7 INSERT INTO tests(t)
8 WITH RECURSIVE times(t) AS
9 (
10 SELECT now() - interval 1 YEAR t
11 UNION ALL
12 SELECT t + interval 1 hour
13 FROM times
14 WHERE t < now()
15 )
16 SELECT t
17 FROM times;

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.

If you change the SYSDATE() to NOW() function in the query:

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.

MySQL TIMEDIFF Function


Summary: this tutorial shows you how to use the MySQL TIMEDIFF function and provides you with some
important usage notes of the function.

Introduction to MySQL TIMEDIFF function

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.

MySQL TIMEDIFF function examples


Let’s take an example that calculates the difference between two time values.
1 mysql> SELECT TIMEDIFF('12:00:00','10:00:00') diff;
2 +----------+
3 | diff |
4 +----------+
5 | 02:00:00 |
6 +----------+
7 1 row in set (0.00 sec)

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)

The TIMEDIFF function returns NULL if either argument is NULL .

1 mysql> SELECT TIMEDIFF('2010-01-01',NULL) diff;


2 +------+
3 | diff |
4 +------+
5 | NULL |
6 +------+
7 1 row in set, 1 warning (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.

1 mysql> SELECT TIMEDIFF(


2 '2010-01-01 10:00:00',
3 '10:00:00') diff;
4 +------+
5 | diff |
6 +------+
7 | NULL |
8 +------+
9 1 row in set (0.00 sec)

MySQL TIMEDIFF function and truncated incorrect time value

Consider the following example.


1 SELECT
2 TIMEDIFF('2009-03-01 00:00:00',
3 '2009-01-01 00:00:00') diff;

It returns the following result:


1 +------------+
2 | diff |
3 +------------+
4 | 838:59:59 |
5 +------------+
6 1 row in set, 1 warning (0.00 sec)

As you can see, we got one warning. Let’s see what it is by using the SHOW WARNINGS statement.

1 mysql> SHOW WARNINGS;


2 +---------+------+-----------------------------------------------+
3 | Level | Code | Message |
4 +---------+------+-----------------------------------------------+
5 | Warning | 1292 | Truncated incorrect time value: '1416:00:00' |
6 +---------+------+-----------------------------------------------+
7 1 row in set (0.00 sec)

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.

MySQL TIMESTAMPDIFF Function


Summary: in this tutorial, you will learn how to use the MySQL TIMESTAMPDIFF function to calculate the
difference between two DATE or DATETIME values.

Introduction to MySQL TIMESTAMPDIFF function

The following illustrates the syntax of the TIMESTAMPDIFF function.

1 TIMESTAMPDIFF(unit,begin,end);

The TIMESTAMPDIFF function returns the result of begin - end ,


where begin and end are DATE or DATETIME expressions.

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)

The following statement returns a difference of two DATETIME values in minutes:

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:

1 SELECT TIMESTAMPDIFF(MINUTE, '2010-01-01 10:00:00', '2010-01-01 10:45:59') result;


2 +--------+
3 | result |
4 +--------+
5 | 45 |
6 +--------+
7 1 row in set (0.00 sec)

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)

45 minutes 59 second = 45 x 60 + 59 (seconds) = 2759 seconds

Calculating ages using MySQL TIMESTAMPDIFF function


First, we create a new table named persons for the demonstration.

1 CREATE TABLE persons (


2 id INT AUTO_INCREMENT PRIMARY KEY,
3 full_name VARCHAR(255) NOT NULL,
4 date_of_birth DATE NOT NULL
5 );

Second, we insert some rows into the persons table:

1 INSERT INTO persons(full_name, date_of_birth)


2 VALUES('John Doe', '1990-01-01'),
3 ('David Taylor', '1989-06-06'),
4 ('Peter Drucker', '1985-03-02'),
5 ('Lily Smith', '1992-05-05'),
6 ('Mary William', '1995-12-01');

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.

MySQL WEEK Function


Summary: in this tutorial, you will learn how to use the MySQL WEEK function to get the week number for
a date.

Introduction to MySQL WEEK function

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);

The WEEK function accepts two arguments:

 date is the date that you want to get a week number.

 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:

1 mysql> SHOW VARIABLES LIKE 'default_week_format';


2 +---------------------+-------+
3 | Variable_name | Value |
4 +---------------------+-------+
5 | default_week_format | 0 |
6 +---------------------+-------+
7 1 row in set (0.01 sec)

In our server, the default value of default_week_format is 0. The following table illustrates how
the mode argument influcences the WEEK function:

Mode First day of week Range Week 1 is the first week …


0 Sunday 0-53 with a Sunday in this year
1 Monday 0-53 with 4 or more days this year
2 Sunday 1-53 with a Sunday in this year
3 Monday 1-53 with 4 or more days this year
4 Sunday 0-53 with 4 or more days this year
5 Monday 0-53 with a Monday in this year
6 Sunday 1-53 with 4 or more days this year
7 Monday 1-53 with a Monday in this year

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

MySQL WEEK function example


See the following orders table in the sample database.

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.

MySQL WEEKDAY Function


The WEEKDAY function returns a weekday index for a date i.e., 0 for Monday, 1 for Tuesday, … 6 for
Sunday.

The following illustrates the WEEKDAY function:

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 .

MySQL YEAR Function


Summary: in this tutorial, you will learn how to use the MySQL YEAR function to get the year out of a
date value.

Introduction to MySQL YEAR function


The YEAR() function takes a date argument and returns the year of the date. See the syntax of
the YEAR() function:

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)

The following statement returns the current year:


1 SELECT YEAR(NOW());
2 +-------------+
3 | YEAR(NOW()) |
4 +-------------+
5| 2017 |
6 +-------------+
7 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)

As mentioned earlier, the YEAR() of zero date is zero:


1 SELECT YEAR('0000-00-00');
2 +--------------------+
3 | YEAR('0000-00-00') |
4 +--------------------+
5| 0|
6 +--------------------+
7 1 row in set (0.00 sec)

Let’s see the orders table in the sample database.

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.

MySQL YEAR function and indexes


Currently, MySQL does no support function index. It means that the expression YEAR(column) will not
leverage index if the index is available for the column .

We will create a new table named dates for demonstration purpose:

1 CREATE TABLE dates (


2 id INT PRIMARY KEY AUTO_INCREMENT,
3 dt DATE
4 );

The dt column will store the date data. The following statement creates an index on the dt column of
the dates table.

1 CREATE INDEX idx_td ON dates(dt);

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' :

1 WITH RECURSIVE dates (dt) AS


2(
3 SELECT '1800-01-01'
4 UNION ALL
5 SELECT dt + INTERVAL 1 DAY FROM dates
6 WHERE dt + INTERVAL 1 DAY <= '2020-12-31'
7)
8 SELECT dt FROM dates;

To insert this date series into the dates table, you use the following INSERT statement:

1 INSERT INTO dates(dt)


2 WITH RECURSIVE dates (dt) AS
3(
4 SELECT '1800-01-01'
5 UNION ALL
6 SELECT dt + INTERVAL 1 DAY FROM dates
7 WHERE dt + INTERVAL 1 DAY <= '2020-01-01'
8)
9 SELECT dt FROM dates;

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';

Both queries return 365 rows, which is correct.

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.

See the EXPLAIN of both queries:

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.

E. MySQL comparison functions


 COALESCE – return the first non-NULL arguments, which is very handy for substitution of NULL .

 GREATEST & LEAST – take n arguments and return the greatest and least values of the n arguments
respectively.

 ISNULL – return 1 if the argument is NULL , otherwise return zero.

MySQL COALESCE Function


Summary: this tutorial introduces you to the MySQL COALESCE function that allows you to substitute
NULL values.

Introduction to MySQL COALESCE function


The following illustrates the COALESCE function syntax:

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:

1 SELECT COALESCE(NULL, 0); -- 0


2 SELECT COALESCE(NULL, NULL); -- NULL;

MySQL COALESCE function examples


See the following customers table in the sample database.

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.

Suppose you have an articles table with the following structure:

CREATE TABLE articles (


1
id INT PRIMARY KEY AUTO_INCREMENT,
2
title VARCHAR(255) NOT NULL,
3
excerpt TEXT,
4
body TEXT NOT NULL,
5
published_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
6
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
7
CURRENT_TIMESTAMP
8
);

Let’s insert some data into the articles table.

INSERT INTO articles(title,excerpt,body)


1
VALUES('MySQL COALESCE Tutorial','This tutorial is about MySQL COALESCE function', 'all about COALESCE
2
function'),
3
('MySQL 8.0 New Features',null, 'The following is a list of new features in MySQL 8.0');

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.

MySQL COALESCE and CASE expression


Besides using the COALESCE function, you can use the CASE expression to achieve the same effect.
The following query uses the CASE expression to achieve the same result as the example above:

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.

MySQL COALESCE vs. IFNULL


The IFNULL function takes two arguments and returns the first argument if it is not NULL, otherwise, it
returns the second argument.

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.

MySQL GREATEST And LEAST, Max and Min of Two


or More Fields

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.

Introduction to MySQL GREATEST and LEAST functions


Both GREATEST and LEAST functions take N arguments and return the greatest and smallest values
respectively. The following illustrates the syntax of the GREATEST and LEAST function:

1 GREATEST(value1, value2, ...);


2 LEAST(value1,value2,...);

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.

 In all other cases, the functions compare arguments as binary strings.

The following examples demonstrates how the GREATEST and LEAST function work.

1 SELECT GREATEST(10, 20, 30), -- 30


2 LEAST(10, 20, 30); -- 10
3
4
5 SELECT GREATEST(10, null, 30), -- null
6 LEAST(10, null , 30); -- null

MySQL GREATEST and LEAST examples


Let’s create a new table for the demonstration.

1 CREATE TABLE IF NOT EXISTS revenues (


2 company_id INT PRIMARY KEY,
3 q1 DECIMAL(19 , 2 ),
4 q2 DECIMAL(19 , 2 ),
5 q3 DECIMAL(19 , 2 ),
6 q4 DECIMAL(19 , 2 )
7 );

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.

1 INSERT INTO revenues(company_id,q1,q2,q3,q4)


2 VALUES (1,100,120,110,130),
3 (2,250,260,300,310);

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.

1 INSERT INTO revenues(company_id,q1,q2,q3,q4)


2 VALUES (3,100,120,110,null);

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.

The Essential Guide To MySQL ISNULL Function


Summary: this tutorial introduces you to the MySQL ISNULL function and how to use it to handle NULL
values.

Introduction to MySQL ISNULL function


The ISNULL function takes one argument and tests whether that argument is NULL or not.

The ISNULL function returns 1 if the argument is NULL , otherwise, it returns 0.

The following illustrates the syntax of the ISNULL function:

1 ISNULL(expr)

Consider the following examples:


1 SELECT ISNULL(NULL); -- 1
2 SELECT ISNULL(1); -- 0
3 SELECT ISNULL(1 + NULL); -- 1;
4 SELECT ISNULL(1 / 0 ); -- 1;

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.

MySQL ISNULL function & IS NULL operator


The ISNULL function shares some behaviors with the IS NULL operator. For example, if you have
a DATE column declared as NOT NULL , you can find the special date '0000-00-00' by using the following
statement:

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' .

Let’s take a look at an example.

First, create a new table named special_isnull as follows:

1 CREATE TABLE special_isnull (


2 start_date DATE NOT NULL
3 );

Second, insert some data into the special_isnull table:

1 INSERT INTO special_isnull(start_date)


2 VALUES('2000-01-01'),
3 ('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.

F. Other MySQL functions


 LAST_INSERT_ID – obtain the last generated sequence number of the last inserted record.
 CAST – convert a value of any type into a value with a specified type.

MySQL LAST_INSERT_ID Function


Summary: in this tutorial, you will learn how to use the MySQL LAST_INSERT_ID function to obtain the
generated sequence number of the last insert row.

Introduction to MySQL LAST_INSERT_ID function


In database design, you often use a surrogate key to generate unique integer values for the primary
key column using the AUTO_INCREMENT attribute.

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.

MySQL LAST_INSERT_ID example


Let’s take a look at an example of using MySQL LAST_INSERT_ID function.

First, create a new table named tbl for testing. In the tbl table, you set the AUTO_INCREMENT attribute
for the id column.

1 CREATE TABLE tbl (


2 id INT AUTO_INCREMENT PRIMARY KEY,
3 description VARCHAR(250) NOT NULL
4 );

Second, insert a new row into the tbl table.

1 INSERT INTO tbl(description)

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.

1 INSERT INTO tbl(description)


2 VALUES('record 1'),
3 ('record 2'),
4 ('record 3');
5
6 SELECT LAST_INSERT_ID();

Check the data of the tbl table:

1 SELECT * FROM tbl;

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.

MySQL CAST Function


Summary: in this tutorial, we will show you how to use MySQL CAST function to convert a value of any
type into a value with a specified type.

Introduction to MySQL CAST function


The syntax of the MySQL CAST() function is as follows:

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.

Let’s take a look at some examples of using the CAST() function.

MySQL CAST function examples


In the following example, MySQL converts a string into an integer implicitly before doing calculation:

1 SELECT (1 + '1')/2;

To explicitly convert a string into an integer, you use the CAST() function as the following statement:

1 SELECT (1 + CAST('1' AS UNSIGNED))/2;

The following statement explicitly converts an integer into a string and concatenates the string with
another string:

1 SELECT CONCAT('MySQL CAST example #',CAST(2 AS CHAR));

139 of 142
Let’s take a look at the orders table in the sample database.

See the following query:

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

You might also like