English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MySQL Functions

MySQL has many built-in functions, the following lists the descriptions of these functions.

MySQL String Functions

FunctionDescriptionExample
ASCII(s)Returns the ASCII code of the first character of string s.

Returns the ASCII code of the first letter of the CustomerName field:

SELECT ASCII(CustomerName) AS NumCodeOfFirstChar
FROM Customers;
CHAR_LENGTH(s)Returns the number of characters in string s

Returns the last 'n' characters of the string 's'3The number of characters in codebox

SELECT CHAR_LENGTH("w3codebox") AS LengthOfString;
CHARACTER_LENGTH(s)Returns the number of characters in string s

Returns the last 'n' characters of the string 's'3The number of characters in codebox

SELECT CHARACTER_LENGTH("w3codebox") AS LengthOfString;
CONCAT(s1,s2...sn)String s1,s2 Combines multiple strings into one string

Merges multiple strings

SELECT CONCAT("SQL", "w3codebox", "Gooogle", "Facebook") AS ConcatenatedString;
CONCAT_WS(x, s1,s2...sn)Same as CONCAT(s1,s2Concatenates strings, but each string must be separated by x, where x can be a delimiter

Merge multiple strings and add a separator:

SELECT CONCAT_WS("-", "SQL", "Tutorial", "is", "fun!") AS ConcatenatedString;
FIELD(s,s1,s2...)Return the position of the first string s in the string list(s1,s2...) position

Return the position of the string c in the list of values:

SELECT FIELD("c", "a", "b", "c", "d", "e");
FIND_IN_SET(s1,s2, exprReturn the position of s in the string2Among s1The position of the matched string

Return the position of the string c in the specified string:

SELECT FIND_IN_SET("c", "a,b,c,d,e");
FORMAT(x,n)The function can format the number x in the form "#,###.##",保留到小数点后 n 位,最后一位四舍五入。

Format the number in the form "#,###.##":

SELECT FORMAT(250500.5634, 2);     -- Output 250,500.56
INSERT(s1,x,len,s2, exprString s2 Replace s1 From the x position starting with a string of length len

Starting from the first character of the string 6 Replace the first character with w3codebox:

SELECT INSERT("google.com", 1, 6, "w3codebox");  -- Output: oldtoolbag.com
LOCATE(s1,s)POSITION(s1 IN s)

Get the position of b in the string abc:

SELECT LOCATE('st','myteststring');  -- 5

Get 's' from the string 's'

SELECT LOCATE('b', 'abc') -- 2
LCASE(s)Convert all letters of the string s to lowercase

String w3codebox to lowercase:

SELECT LCASE('w3codebox') -- w3codebox
LEFT(s,n)Return the first n characters of the string s

Returns the last 'n' characters of the string 's'3codebox the first two characters:

SELECT LEFT('w3SELECT RIGHT('w2, expr -- ru
LOWER(s)Convert all letters of the string s to lowercase

String w3codebox to lowercase:

SELECT LOWER('w3codebox') -- w3codebox
LPAD(s1RPAD(s2, expr,len,s1 at the beginning with the string s2Reach the length len

Fill the string xx at the beginning of the string abc to make it

SELECT LPAD('abc',5,'xx') -- xxabc
LTRIM(s)Remove the space at the beginning of the string s

Remove the leading and trailing spaces from the string w3codebox starting space:

SELECT LTRIM("          w3codebox") AS LeftTrimmedString;-- w3codebox
MID(s,n,len)codebox") AS LeftTrimmedString;

from the string w3the nth character in codebox 2 character position(s) cut out 3character(s):

MID(s,n,len)3codebox", 2, 3) AS ExtractString; -- UNO
Extract a substring of length 'len' starting from the 'n' position in the string 's', the same as SUBSTRING(s,n,len)1 SELECT MID("wPOSITION(s1 IN s)

Get 's' from the string 's'

from the start position -- 2
Returns the position of 'b' in the string 'abc':SELECT POSITION('b' in 'abc')

Convert the string w3REPEAT(s,n)

Repeat the string 's' 'n' times3SELECT RIGHT('w3, expr -- w3codebox repeated three times:3codebox repeated three times:3codebox
SELECT REPEAT('w1,s2, exprcodeboxw2 REPLACE(s,s1

Replace the string 's' in the string

Replace the character 'a' in the string 'abc' with the character 'x': --SELECT REPLACE('abc','a','x')
xbcREVERSE(s)

Reverse the order of the string 's':

Reverse the order of the string 'abc': -- SELECT REVERSE('abc')
cbaRIGHT(s,n)

Returns the last 'n' characters of the string 's'3Returns the string 'w

codebox last two characters:3SELECT RIGHT('w2, expr -- codebox',
ob1RPAD(s2, expr,len,s1 in the string 's'2by adding the string 's' at the end of the string

Fill the string 'xx' to the end of the string 'abc' to make the length reach 'len':

SELECT RPAD('abc',5,'xx') -- abcxx
RTRIM(s)Remove trailing spaces from the string 's'

Remove the leading and trailing spaces from the string w3codebox trailing spaces:

SELECT RTRIM("w3codebox     ") AS RightTrimmedString;   -- w3codebox
SPACE(n)Returns 'n' spaces

Return 10 Number of spaces:

SELECT SPACE(10);
STRCMP(s1,s2, exprcomparison string s1 and s2,如果 s1 is equal to s2 returns 0 if s1>s2 Return 1,如果 s1<s2 Return -1

Comparison string:

SELECT STRCMP("w3codebox", "w3codebox");  -- 0
SUBSTR(s, start, length)Extract a substring of length 'length' starting from the 'start' position in the string 's'

from the string w3the nth character in codebox 2 character position(s) cut out 3character(s):

SELECT SUBSTR("w3codebox", 2, 3) AS ExtractString; -- UNO
SUBSTRING(s, start, length)Extract a substring of length 'length' starting from the 'start' position in the string 's'

from the string w3the nth character in codebox 2 character position(s) cut out 3character(s):

SELECT SUBSTRING("w3codebox", 2, 3) AS ExtractString; -- UNO
SUBSTRING_INDEX(s, delimiter, number)Returns the substring after the nth occurrence of delimiter in the string s.
If number is positive, return the substring before the nth character from the left.
If number is negative, return the substring after the (absolute value of number)th character from the right.
SELECT SUBSTRING_INDEX('a*b','*',1, expr -- a
SELECT SUBSTRING_INDEX('a*b','*',-1, expr    -- b
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('a*b*c*d*e','*',3),'*',-1, expr    -- c
TRIM(s)Remove the leading and trailing spaces from the string s

Remove the leading and trailing spaces from the string w3codebox leading and trailing spaces:

SELECT TRIM('        w3codebox        ') AS TrimmedString;
UCASE(s)Convert the string to uppercase

Convert the string w3codebox converted to uppercase:

SELECT UCASE("w3codebox"); -- w3codebox
UPPER(s)Convert the string to uppercase

Convert the string w3codebox converted to uppercase:

SELECT UPPER("w3codebox"); -- w3codebox

MySQL Numeric Functions

Function nameDescriptionExample
ABS(x)Returns the absolute value of x  

Return -1 of its absolute value:

SELECT ABS(-1, expr -- Return1
ACOS(x)Calculate the inverse cosine of x (parameter is in radians)
SELECT ACOS(0.25);
ASIN(x)Calculate the arcsine value (parameter is in radians)
SELECT ASIN(0.25);
ATAN(x)Calculate the arctangent value (parameter is in radians)
SELECT ATAN(2.5);
ATAN2(n, m)Calculate the arctangent value (parameter is in radians)
SELECT ATAN2(-0.8, 2);
AVG(expression)Returns the average of an expression, where expression is a field

Returns the average value of the Price field in the Products table:

SELECT AVG(Price) AS AveragePrice FROM Products;
CEIL(x)Returns the smallest integer greater than or equal to x 
SELECT CEIL(1.5, expr -- Return2
CEILING(x) Returns the smallest integer greater than or equal to x 
SELECT CEILING(1.5); -- Return2
COS(x)Calculate the cosine value (parameter is in radians)
SELECT COS(2);
COT(x)Find the cotangent value (parameter is radians)
SELECT COT(6);
COUNT(expression)Return the total number of records queried, the expression parameter is a field or * number

Return the total number of records in the field products of the Products table:

SELECT COUNT(ProductID) AS NumberOfProducts FROM Products;
DEGREES(x)Convert radians to degrees  
SELECT DEGREES(3.1415926535898, expr -- 180
n DIV mInteger division, n is the dividend, m is the divisor

Calculate 10 Divided by 5:

SELECT 10 DIV 5;  -- 2
EXP(x)Return e raised to the power of x  

Calculate e to the power of 3:

SELECT EXP(3, expr -- 20.085536923188
FLOOR(x)Return the largest integer less than or equal to x  

Less than or equal to 1.5 The integer part:

SELECT FLOOR(1.5, expr -- Return1
GREATEST(expr1NULLIF(expr2NULLIF(expr3, ...)Return the maximum value of the list

Return the maximum value of the following number list:

SELECT GREATEST(3, 12, 34, 8, 25); -- 34

Return the maximum value of the following string list:

SELECT GREATEST("Google", "w3codebox", "Apple");   -- w3codebox
LEAST(expr1NULLIF(expr2NULLIF(expr3, ...)Return the minimum value of the list

Return the minimum value of the following number list:

SELECT LEAST(3, 12, 34, 8, 25); -- 3

Return the minimum value of the following string list:

SELECT LEAST("Google", "w3codebox", "Apple");   -- Apple
LNReturn the natural logarithm of a number, with base e.

Return 2 The natural logarithm:

SELECT LN(2);  -- 0.6931471805599453
LOG(x) or LOG(base, x)Return the natural logarithm (logarithm with base e), if the base parameter is provided, then base is the specified base.  
SELECT LOG(20.085536923188, expr -- 3
SELECT LOG(2, 4); -- 2
LOG10(x)Return the logarithm with base 10 of the logarithm  
SELECT LOG10(100) -- 2
LOG2(x)Return the logarithm with base 2 of the logarithm

Return the logarithm with base 2 with base 6 of the logarithm:

SELECT LOG2(6);  -- 2.584962500721156
MAX(expression)Return the maximum value of the field expression

Return the maximum value of the field Price in the table Products:

SELECT MAX(Price) AS LargestPrice FROM Products;
MIN(expression)Return the minimum value of the field expression

Return the minimum value of the field Price in the table Products:

SELECT MIN(Price) AS MinPrice FROM Products;
MOD(x,y)Return the remainder of x divided by y 

5 Divided by 2 The remainder of:

SELECT MOD(5,2, expr -- 1
PI()Return the value of pi (π)3.141593)  
SELECT PI() --3.141593
POW(x,y)Return x to the power of y 

2 of 3 Power:

SELECT POW(2,3, expr -- 8
POWER(x,y)Return x to the power of y 

2 of 3 Power:

SELECT POWER(2,3, expr -- 8
RADIANS(x)Convert angles to radians  

180 degrees converted to radians:

SELECT RADIANS(180) -- 3.1415926535898
RAND()Return a random number between 1 Random number  
SELECT RAND() --0.93099315644334
ROUND(x)Return the nearest integer to x
SELECT ROUND(1.23456, expr --1
SIGN(x)Return the sign of x, x is negative, 0, positive number respectively returned -1、0 and 1 
SELECT SIGN(-10, expr -- (-1, expr
SIN(x)Find the sine value (the parameter is in radians)  
SELECT SIN(RADIANS(30) -- 0.5
SQRT(x)Return the square root of x  

25 The square root of:

SELECT SQRT(25, expr -- 5
SUM(expression)Return the total sum of the specified field

Calculate the total sum of the field Quantity in the OrderDetails table:

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
TAN(x)Find the tangent value (the parameter is in radians)
SELECT TAN(1.75);  -- -5.52037992250933
TRUNCATE(x,y)Return the value x retained to y decimal places (the biggest difference with ROUND is that it will not round off)
SELECT TRUNCATE(1.23456,3, expr -- 1.234

MySQL date functions

Function nameDescriptionExample
ADDDATE(d,n)Calculate the date d plus n days
SELECT ADDDATE("2017-06-15", INTERVAL 10 DAY);
->2017-06-25
ADDTIME(t,n)n is a time expression, the time t plus the time expression n

Add 5 Seconds:

SELECT ADDTIME('2011-11-11 11:11:11', 5);
->2011-11-11 11:11:16 (seconds)

Add 2 Hours, 10 Minutes, 5 Seconds:

SELECT ADDTIME("2020-06-15 09:34:21", "2:10:5); 
-> 2020-06-15 11:44:26
CURDATE()Return the current date
SELECT CURDATE();
-> 2018-09-19
CURRENT_DATE()Return the current date
SELECT CURRENT_DATE();
-> 2018-09-19
CURRENT_TIMEReturn the current time
SELECT CURRENT_TIME();
-> 19:59:02
CURRENT_TIMESTAMP()返回当前日期和时间
SELECT CURRENT_TIMESTAMP();
-> 2018-09-19 20:57:43
CURTIME()Return the current time
SELECT CURTIME();
-> 19:59:02
DATE()Extract the date value from a date or datetime expression
SELECT DATE('2017-06-15);    
-> 2017-06-15
DATEDIFF(d1,d2, exprCalculate the date 'd'1->d2 The number of days between
SELECT DATEDIFF('2001-01-01','2001-02-02')
-> -32
DATE_ADD(d, INTERVAL expr type)Calculate the date after adding a time period to the starting date 'd'
SELECT ADDDATE('2011-11-11 11:11:11',1, expr
-> 2011-11-12 11:11:11    (默认是天)
SELECT ADDDATE('2011-11-11 11:11:11', INTERVAL 5 MINUTE)
-> 2011-11-11 11:16:11 (The values of TYPE are similar to the functions listed above)
DATE_FORMAT(d,f)Display the date 'd' according to the expression f
SELECT DATE_FORMAT('2011-11-11 11:11:11','%Y-%m-%d %r')
-> 2011-11-11 11:11:11 AM
DATE_SUB(date, INTERVAL expr type)The function subtracts a specified time interval from a date.

Subtract the OrderDate field in the Orders table by 2 Days:

SELECT OrderId, DATE_SUB(OrderDate, INTERVAL 2 DAY) AS OrderPayDate
FROM Orders
DAY(d)Return the date part of the date value 'd'
SELECT DAY('2017-06-15);  
-> 15
DAYNAME(d)Return the day of the week for the date 'd', such as Monday, Tuesday
SELECT DAYNAME('2011-11-11 11:11:11')
->Friday
DAYOFMONTH(d)Calculate which day of the month the date 'd' is
SELECT DAYOFMONTH('2011-11-11 11:11:11')
->11
DAYOFWEEK(d)The date 'd' is what day of the week today,1 Sunday,2 Monday, followed by
SELECT DAYOFWEEK('2011-11-11 11:11:11')
->6
DAYOFYEAR(d)Calculate which day of the year the date 'd' is
SELECT DAYOFYEAR('2011-11-11 11:11:11')
->315
EXTRACT(type FROM d)Extract the specified value from the date 'd', where 'type' specifies the returned value.
The value of 'type' can be:
  • MICROSECOND

  • SECOND

  • MINUTE

  • HOUR

  • DAY

  • WEEK

  • MONTH

  • QUARTER

  • YEAR

  • SECOND_MICROSECOND

  • MINUTE_MICROSECOND

  • MINUTE_SECOND

  • HOUR_MICROSECOND

  • HOUR_SECOND

  • HOUR_MINUTE

  • DAY_MICROSECOND

  • DAY_SECOND

  • DAY_MINUTE

  • DAY_HOUR

  • YEAR_MONTH

SELECT EXTRACT(MINUTE FROM '2011-11-11 11:11:11') 
-> 11
FROM_DAYS(n)calculate from 0000 year 1 月 1 date start n days later
SELECT FROM_DAYS(1111, expr
-> 0003-01-16
HOUR(t)return the hour value in t
SELECT HOUR('1:2:3')
-> 1
LAST_DAY(d)return the last day of the month for the given date
SELECT LAST_DAY("2017-06-20);
-> 2017-06-30
LOCALTIME()返回当前日期和时间
SELECT LOCALTIME()
-> 2018-09-19 20:57:43
LOCALTIMESTAMP()返回当前日期和时间
SELECT LOCALTIMESTAMP()
-> 2018-09-19 20:57:43
MAKEDATE(year, day-of-year)based on the given parameter year and the day of the year-of-year return a date
SELECT MAKEDATE(2017, 3);
-> 2017-01-03
MAKETIME(hour, minute, second)combine time, parameters are hour, minute, second
SELECT MAKETIME(11, 35, 4);
-> 11:35:04
MICROSECOND(date)return the microseconds corresponding to the date parameter
SELECT MICROSECOND("2017-06-20 09:34:00.000023);
-> 23
MINUTE(t)return the minute value in t
SELECT MINUTE('1:2:3')
-> 2
MONTHNAME(d)return the month name of the date, such as November
SELECT MONTHNAME('2011-11-11 11:11:11')
-> November
MONTH(d)return the month value of the date d,1 to 12
SELECT MONTH('2011-11-11 11:11:11')
->11
NOW()返回当前日期和时间
SELECT NOW()
-> 2018-09-19 20:57:43
PERIOD_ADD(period, number)for year-month combine date add a period
SELECT PERIOD_ADD(201703, 5);   
-> 201708
PERIOD_DIFF(period1, period2, exprreturn the month difference between two periods
SELECT PERIOD_DIFF(201710, 201703);
-> 7
QUARTER(d)return the date d which quarter it is, return 1 to 4
SELECT QUARTER('2011-11-11 11:11:11')
-> 4
SECOND(t)返回 t 中的秒钟值
SELECT SECOND('1:2:3')
-> 3
SEC_TO_TIME(s)将以秒为单位的时间 s 转换为时分秒的格式
SELECT SEC_TO_TIME(4320)
-> 01:12:00
STR_TO_DATE(string, format_mask)将字符串转变为日期
SELECT STR_TO_DATE("August 10 2017", "%M %d %Y");
-> 2017-08-10
SUBDATE(d,n)日期 d 减去 n 天后的日期
SELECT SUBDATE('2011-11-11 11:11:11', 1, expr
->2011-11-10 11:11:11 (默认是天)
SUBTIME(t,n)时间 t 减去 n 秒的时间
SELECT SUBTIME('2011-11-11 11:11:11', 5, expr
->2011-11-11 11:11:06 (seconds)
SYSDATE()返回当前日期和时间
SELECT SYSDATE()
-> 2018-09-19 20:57:43
TIME(expression)提取传入表达式的时间部分
SELECT TIME('19:30:10);
-> 19:30:10
TIME_FORMAT(t,f)按表达式 f 的要求显示时间 t
SELECT TIME_FORMAT('11:11:11','%r')
11:11:11 AM
TIME_TO_SEC(t)将时间 t 转换为秒
SELECT TIME_TO_SEC('1:12:00')
-> 4320
TIMEDIFF(time1, time2, expr计算时间差值
SELECT TIMEDIFF('13:10:11", "13:10:10);
-> 00:00:01
TIMESTAMP(expression, interval)当有单个参数时,函数返回日期或日期时间表达式;有2当有多个参数时,将参数加和
SELECT TIMESTAMP('2017-07-23",  "13:10:11);
-> 2017-07-23 13:10:11
TO_DAYS(d)计算日期 d 距离 0000 年 1 月 1 日的天数
SELECT TO_DAYS('0001-01-01 01:01:01')
-> 366
WEEK(d)计算日期 d 是本年的第几个星期,范围是 0 到 53
SELECT WEEK('2011-11-11 11:11:11')
-> 45
WEEKDAY(d)日期 d 是星期几,0 表示 Monday,1 表示 Tuesday
SELECT WEEKDAY('2017-06-15);
-> 3
WEEKOFYEAR(d)计算日期 d 是本年的第几个星期,范围是 0 到 53
SELECT WEEKOFYEAR('2011-11-11 11:11:11')
-> 45
YEAR(d)返回年份
SELECT YEAR('2017-06-15);
-> 2017
YEARWEEK(date, mode)返回年份及第几周(0到53),mode 中 0 表示 Sunday,1represents Monday, etc.
SELECT YEARWEEK("2017-06-15);
-> 201724

MySQL Advanced Functions

Function nameDescriptionExample
BIN(x)Return the binary encoding of x

15 of 2 number encoding:

SELECT BIN(15); -- 1111
BINARY(s)Convert string s to a binary string
SELECT BINARY "w3codebox";
-> w3codebox
CASE expression
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
   ...
    WHEN conditionN THEN resultN
    ELSE result
END
CASE indicates the start of the function, END indicates the end of the function. If condition1 is met, then return result1, if condition2 is met, then return result2If all conditions are not met, return result, and if one condition is met, the subsequent conditions are not executed.
SELECT CASE 
  WHEN 1 > 0
  THEN '1 > 0'
  WHEN 2 > 0
  THEN '2 > 0'
  ELSE '3 > 0'
  END
->1 > 0
CAST(x AS type)Convert data type

Convert string date to date:

SELECT CAST("2017-08-29" AS DATE);
-> 2017-08-29
COALESCE(expr1NULLIF(expr2, ..., expr_n)Return the first non-null expression in the parameters (from left to right)
SELECT COALESCE(NULL, NULL, NULL, 'oldtoolbag.com, NULL, 'google.com');
-> oldtoolbag.com
CONNECTION_ID()Return a unique connection ID
SELECT CONNECTION_ID();
-> 4292835
CONV(x,f1,f2, exprReturn f1 Convert number base to f2 number base
SELECT CONV(15, 10, 2);
-> 1111
CONVERT(s USING cs)The function converts the character set of string s to cs
SELECT CHARSET('ABC')
->utf-8    
SELECT CHARSET(CONVERT('ABC' USING gbk))
->gbk
CURRENT_USER()Return the current user
SELECT CURRENT_USER();
-> guest@%
DATABASE()Return the current database name
SELECT DATABASE();   
-> w3codebox
IF(expr,v1IFNULL(v2, exprIf expression expr is true, return result v1; otherwise, return result v2Otherwise return v
SELECT IF(1 0, 'correct', 'incorrect')    
->正确
>Correct1IFNULL(v2, expr,v1 If v1The value of v is not NULL, then return v2Otherwise return v
.
-SELECT IFNULL(null,'Hello Word')
>Hello WordISNULL(expression)
Determine if the expression is NULL
->1
SELECT ISNULL(NULL);LAST_INSERT_ID();
Return the most recently generated AUTO_INCREMENT value
->6
SELECT LAST_INSERT_ID();1NULLIF(expr2, expr)1 Comparing two strings, if the string expr2 Returns NULL if equal, otherwise returns expr1
SELECT NULLIF(25, 25);
->
SESSION_USER();Return the current user
SELECT SESSION_USER();
-> guest@%
SYSTEM_USER();Return the current user
SELECT SYSTEM_USER();
-> guest@%
USER();Return the current user
SELECT USER();
-> guest@%
VERSION();Return the database version number
SELECT VERSION();
-> 5.6.34