SQL Functions

 

Overview

Expressions can be used at several points in SQL statements, such as in the ORDER BY or HAVING clauses of SELECT statements, in the WHERE clause of a SELECT, DELETE, or UPDATE statement, or in SET statements. Expressions can be written using literal values, column values, NULL, built-in functions, stored functions, user-defined functions, and operators. This chapter describes the functions and operators that are allowed for writing expressions in MySQL.

An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for a particular function or operator.

Note: By default, there must be no whitespace between a function name and the parenthesis following it. This helps the MySQL parser distinguish between function calls and references to tables or columns that happen to have the same name as a function. However, spaces around function arguments are permitted.

You can tell the MySQL server to accept spaces after function names by starting it with the --sql-mode=IGNORE_SPACE option. Individual client programs can request this behavior by using the CLIENT_IGNORE_SPACE option for mysql_real_connect(). In either case, all function names become reserved words.

For the sake of brevity, most examples in this chapter display the output from the mysql program in abbreviated form. Rather than showing examples in this format:

(sql sqlHandle {SELECT MOD(29,9)}) Returns
+-----------+
| mod(29,9) |
+-----------+
|         2 |
+-----------+

This format is used instead:

(sql sqlHandle {SELECT MOD(29,9)}) Returns 2

Operator and Function Reference

NameDescription
ABS()Return the absolute value
ACOS()Return the arc cosine
ADDDATE()Add dates
ADDTIME()Add time
AES_DECRYPT()Decrypt using AES
AES_ENCRYPT()Encrypt using AES
AND, &&Logical AND
ASCII()Return numeric value of left-most character
ASIN()Return the arc sine
ATAN2(), ATAN()Return the arc tangent of the two arguments
ATAN()Return the arc tangent
AVG()Return the average value of the argument
BENCHMARK()Repeatedly execute an expression
BETWEEN ... AND ... Check whether a value is within a range of values
BIN()Return a string representation of the argument
BINARYCast a string to a binary string
BIT_AND()Return bitwise and
BIT_COUNT()Return the number of bits that are set
BIT_LENGTH()Return length of argument in bits
BIT_OR()Return bitwise or
BIT_XOR()Return bitwise xor
&Bitwise AND
~Invert bits
|Bitwise OR
^Bitwise XOR
CASECase operator
CAST()Cast a value as a certain type
CEIL()Return the smallest integer value not less than the argument
CEILING()Return the smallest integer value not less than the argument
CHAR_LENGTH()Return number of characters in argument
CHAR()Return the character for each integer passed
CHARACTER_LENGTH()A synonym for CHAR_LENGTH()
CHARSET()Return the character set of the argument
COALESCE()Return the first non-NULL argument
COERCIBILITY()Return the collation coercibility value of the string argument
COLLATION()Return the collation of the string argument
COMPRESS()Return result as a binary string
CONCAT_WS()Return concatenate with separator
CONCAT()Return concatenated string
CONNECTION_ID()Return the connection ID (thread ID) for the connection
CONV()Convert numbers between different number bases
CONVERT_TZ()Convert from one timezone to another
Convert()Cast a value as a certain type
COS()Return the cosine
COT()Return the cotangent
COUNT(DISTINCT)Return the count of a number of different values
COUNT()Return a count of the number of rows returned
CRC32()Compute a cyclic redundancy check value
CURDATE()Return the current date
CURRENT_DATE(), CURRENT_DATESynonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIMESynonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMPSynonyms for NOW()
CURRENT_USER(), CURRENT_USERReturn the username and hostname combination
CURTIME()Return the current time
DATABASE()Return the default (current) database name
DATE_ADD()Add two dates
DATE_FORMAT()Format date as specified
DATE_SUB()Subtract two dates
DATE()Extract the date part of a date or datetime expression
DATEDIFF()Subtract two dates
DAY()Synonym for DAYOFMONTH()
DAYNAME()Return the name of the weekday
DAYOFMONTH()Return the day of the month (0-31)
DAYOFWEEK()Return the weekday index of the argument
DAYOFYEAR()Return the day of the year (1-366)
DECODE()Decodes a string encrypted using ENCODE()
DEFAULT()Return the default value for a table column
DEGREES()Convert radians to degrees
DES_DECRYPT()Decrypt a string
DES_ENCRYPT()Encrypt a string
DIVInteger division
/Division operator
ELT()Return string at index number
ENCODE()Encode a string
ENCRYPT()Encrypt a string
<=>NULL-safe equal to operator
=Equal operator
EXP()Raise to the power of
EXPORT_SET()Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string
EXTRACTExtract part of a date
ExtractValue()Extracts a value from an XML string using XPath notation
FIELD()Return the index (position) of the first argument in the subsequent arguments
FIND_IN_SET()Return the index position of the first argument within the second argument
FLOOR()Return the largest integer value not greater than the argument
FORMAT()Return a number formatted to specified number of decimal places
FOUND_ROWS()For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
FROM_DAYS()Convert a day number to a date
FROM_UNIXTIME()Format UNIX timestamp as a date
GET_FORMAT()Return a date format string
GET_LOCK()Get a named lock
>=Greater than or equal operator
>Greater than operator
GREATEST()Return the largest argument
GROUP_CONCAT()Return a concatenated string
HEX()Return a hexadecimal representation of a decimal or string value
HOUR()Extract the hour
IF()If/else construct
IFNULL()Null if/else construct
IN()Check whether a value is within a set of values
INET_ATON()Return the numeric value of an IP address
INET_NTOA()Return the IP address from a numeric value
INSERT()Insert a substring at the specified position up to the specified number of characters
INSTR()Return the index of the first occurrence of substring
INTERVAL()Return the index of the argument that is less than the first argument
IS_FREE_LOCK()Checks whether the named lock is free
IS NOT NULLNOT NULL value test
IS NOTTest a value against a boolean
IS NULLNULL value test
IS_USED_LOCK()Checks whether the named lock is in use. Return connection identifier if true.
ISTest a value against a boolean
ISNULL()Test whether the argument is NULL
LAST_DAYReturn the last day of the month for the argument
LAST_INSERT_ID()Value of the AUTOINCREMENT column for the last INSERT
LCASE()Synonym for LOWER()
LEAST()Return the smallest argument
<<Left shift
LEFT()Return the leftmost number of characters as specified
LENGTH()Return the length of a string in bytes
<=Less than or equal operator
<Less than operator
LIKESimple pattern matching
LN()Return the natural logarithm of the argument
LOAD_FILE()Load the named file
LOCALTIME(), LOCALTIMESynonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()(v4.0.6)Synonym for NOW()
LOCATE()Return the position of the first occurrence of substring
LOG10()Return the base-10 logarithm of the argument
LOG2()Return the base-2 logarithm of the argument
LOG() Return the natural logarithm of the first argument
LOWER()Return the argument in lowercase
LPAD()Return the string argument, left-padded with the specified string
LTRIM()Remove leading spaces
MAKE_SET()Return a set of comma-separated strings that have the corresponding bit in bits set
MAKEDATE()Create a date from the year and day of year
MAKETIMEMAKETIME()
MASTER_POS_WAIT()Block until the slave has read and applied all updates up to the specified position
MATCHPerform full-text search
MAX()Return the maximum value
MD5()Calculate MD5 checksum
MICROSECOND()Return the microseconds from argument
MID()Return a substring starting from the specified position
MIN()Return the minimum value
-Minus operator
MINUTE()Return the minute from the argument
MOD()Return the remainder
%Modulo operator
MONTH()Return the month from the date passed
MONTHNAME()Return the name of the month
NAME_CONST()Causes the column to have the given name
NOT BETWEEN ... AND ...Check whether a value is not within a range of values
!=, <>Not equal operator
NOT IN()Check whether a value is not within a set of values
NOT LIKENegation of simple pattern matching
NOT REGEXPNegation of REGEXP
NOT, !Negates value
NOW()Return the current date and time
NULLIF()Return NULL if expr1 = expr2
OCT()Return an octal representation of a decimal number
OCTET_LENGTH()A synonym for LENGTH()
OLD_PASSWORD()Return the value of the old (pre-4.1) implementation of PASSWORD
||, ORLogical OR
ORD()Return character code for leftmost character of the argument
PASSWORD()Calculate and return a password string
PERIOD_ADD()Add a period to a year-month
PERIOD_DIFF()Return the number of months between periods
PI()Return the value of pi
+Addition operator
POSITION()A synonym for LOCATE()
POW()Return the argument raised to the specified power
POWER()Return the argument raised to the specified power
PROCEDURE ANALYSE()Analyze the results of a query
QUARTER()Return the quarter from a date argument
QUOTE()Escape the argument for use in an SQL statement
RADIANS()Return argument converted to radians
RAND()Return a random floating-point value
REGEXPPattern matching using regular expressions
RELEASE_LOCK()Releases the named lock
REPEAT()Repeat a string the specified number of times
REPLACE()Replace occurrences of a specified string
REVERSE()Reverse the characters in a string
>>Right shift
RIGHT()Return the specified rightmost number of characters
RLIKESynonym for REGEXP
ROUND()Round the argument
ROW_COUNT()The number of rows updated
RPAD()Append string the specified number of times
RTRIM()Remove trailing spaces
SCHEMA()A synonym for DATABASE()
SEC_TO_TIME()Converts seconds to 'HH:MM:SS' format
SECOND()Return the second (0-59)
SESSION_USER()Synonym for USER()
SHA1(), SHA()Calculate an SHA-1 160-bit checksum
SIGN()Return the sign of the argument
SIN()Return the sine of the argument
SLEEP()Sleep for a number of seconds
SOUNDEX()Return a soundex string
SOUNDS LIKECompare sounds
SPACE()Return a string of the specified number of spaces
SQRT()Return the square root of the argument
STD()Return the population standard deviation
STDDEV_POP()Return the population standard deviation
STDDEV_SAMP()Return the sample standard deviation
STDDEV()Return the population standard deviation
STR_TO_DATE()Convert a string to a date
STRCMP()Compare two strings
SUBDATE()A synonym for DATE_SUB() when invoked with three arguments
SUBSTR()Return the substring as specified
SUBSTRING_INDEX()Return a substring from a string before the specified number of occurrences of the delimiter
SUBSTRING()Return the substring as specified
SUBTIME()Subtract times
SUM()Return the sum
SYSDATE()Return the time at which the function executes
SYSTEM_USER()Synonym for USER()
TAN()Return the tangent of the argument
TIME_FORMAT()Format as time
TIME_TO_SEC()Return the argument converted to seconds
TIME()Extract the time portion of the expression passed
TIMEDIFF()Subtract time
*Times operator
TIMESTAMP()With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments
TIMESTAMPADD()Add an interval to a datetime expression
TIMESTAMPDIFF()Subtract an interval from a datetime expression
TO_DAYS()Return the date argument converted to days
TRIM()Remove leading and trailing spaces
TRUNCATE()Truncate to specified number of decimal places
UCASE()Synonym for UPPER()
-Change the sign of the argument
UNCOMPRESS()Uncompress a string compressed
UNCOMPRESSED_LENGTH()Return the length of a string before compression
UNHEX()Convert each pair of hexadecimal digits to a character
UNIX_TIMESTAMP()Return a UNIX timestamp
UpdateXML()Return replaced XML fragment
UPPER()Convert to uppercase
USER()Return the current username and hostname
UTC_DATE()Return the current UTC date
UTC_TIME()Return the current UTC time
UTC_TIMESTAMP()Return the current UTC date and time
UUID_SHORT()Return an integer-valued universal identifier
UUID()Return a Universal Unique Identifier (UUID)
VALUES()Defines the values to be used during an INSERT
VAR_POP()Return the population standard variance
VAR_SAMP()Return the sample variance
VARIANCE()Return the population standard variance
VERSION()Returns a string that indicates the MySQL server version
WEEK()Return the week number
WEEKDAY()Return the weekday index
WEEKOFYEAR()Return the calendar week of the date (0-53)
XORLogical XOR
YEAR()Return the year
YEARWEEK()Return the year and week

Operators

NameDescription
AND, &&Logical AND
BETWEEN ... AND ... Check whether a value is within a range of values
BINARYCast a string to a binary string
&Bitwise AND
~Invert bits
|Bitwise OR
^Bitwise XOR
CASECase operator
DIVInteger division
/Division operator
<=>NULL-safe equal to operator
=Equal operator
>=Greater than or equal operator
>Greater than operator
IS NOT NULLNOT NULL value test
IS NOTTest a value against a boolean
IS NULLNULL value test
ISTest a value against a boolean
<<Left shift
<=Less than or equal operator
<Less than operator
LIKESimple pattern matching
-Minus operator
%Modulo operator
NOT BETWEEN ... AND ...Check whether a value is not within a range of values
!=, <>Not equal operator
NOT LIKENegation of simple pattern matching
NOT REGEXPNegation of REGEXP
NOT, !Negates value
||, ORLogical OR
+Addition operator
REGEXPPattern matching using regular expressions
>>Right shift
RLIKESynonym for REGEXP
SOUNDS LIKECompare sounds
*Times operator
-Change the sign of the argument
XORLogical XOR

Operator Precedence

Operator precedences are shown in the following list, from highest precedence to the lowest. Operators that are shown together on a line have the same precedence.

INTERVAL
BINARY, COLLATE
!
- (unary minus), ~ (unary bit inversion)
^
*, /, DIV, %, MOD
-, +
<<, >>
&
|
=, <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
BETWEEN, CASE, WHEN, THEN, ELSE
NOT
&&, AND
XOR
||, OR
:=

The || operator has a precedence between ^ and the unary operators if the PIPES_AS_CONCAT SQL mode is enabled.

Note: If the HIGH_NOT_PRECEDENCE SQL mode is enabled, the precedence of NOT is the same as that of the ! operator.

The precedence of operators determines the order of evaluation of terms in an expression. To override this order and group terms explicitly, use parentheses. For example:

(sql sqlHandle {SELECT 1+2*3}) Returns 7
(sql sqlHandle {SELECT (1+2)*3}) Returns 9

Type Conversion in Expression Evaluation

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

(sql sqlHandle {SELECT 1+'1'}) Returns 2
(sql sqlHandle {SELECT CONCAT(2,' test')}) Returns '2 test'

It is also possible to perform explicit conversions. If you want to convert a number to a string explicitly, use the CAST() or CONCAT() function (CAST() is preferable):

(sql sqlHandle {SELECT 38.8, CAST(38.8 AS CHAR)}) Returns 38.8, '38.8'
(sql sqlHandle {SELECT 38.8, CONCAT(38.8)}) Returns 38.8, '38.8'

The following rules describe how conversion occurs for comparison operations:

If one or both arguments are NULL, the result of the comparison is NULL, except for the NULL-safe <=> equality comparison operator. For NULL <=> NULL, the result is true.

If both arguments in a comparison operation are strings, they are compared as strings.

If both arguments are integers, they are compared as integers.

Hexadecimal values are treated as binary strings if not compared to a number.

If one of the arguments is a TIMESTAMP or DATETIME column and the other argument is a constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. Note that this is not done for the arguments to IN()! To be safe, always use complete datetime, date, or time strings when doing comparisons.

In all other cases, the arguments are compared as floating-point (real) numbers.

The following examples illustrate conversion of strings to numbers for comparison operations:

(sql sqlHandle {SELECT 1 > '6x'}) Returns 0
(sql sqlHandle {SELECT 7 > '6x'}) Returns 1
(sql sqlHandle {SELECT 0 > 'x6'}) Returns 0
(sql sqlHandle {SELECT 0 = 'x6'}) Returns 1

Note that when you are comparing a string column with a number, MySQL cannot use an index on the column to look up the value quickly. If str_col is an indexed string column, the index cannot be used when performing the lookup in the following statement:

(sql sqlHandle {SELECT * FROM tbl_name WHERE str_col=1})

The reason for this is that there are many different strings that may convert to the value 1, such as '1', ' 1', or '1a'.

Comparisons that use floating-point numbers (or values that are converted to floating-point numbers) are approximate because such numbers are inexact. This might lead to results that appear inconsistent:

(sql sqlHandle {SELECT '18015376320243458' = 18015376320243458}) Returns 1
(sql sqlHandle {SELECT '18015376320243459' = 18015376320243459}) Returns 0

Such results can occur because the values are converted to floating-point numbers, which have only 53 bits of precision and are subject to rounding:

(sql sqlHandle {SELECT '18015376320243459'+0.0}) Returns 1.8015376320243e+16

Furthermore, the conversion from string to floating-point and from integer to floating-point do not necessarily occur the same way. The integer may be converted to floating-point by the CPU, whereas the string is converted digit by digit in an operation that involves floating-point multiplications.

The results shown will vary on different systems, and can be affected by factors such as computer architecture or the compiler version or optimization level. One way to avoid such problems is to use CAST() so that a value will not be converted implicitly to a float-point number:

(sql sqlHandle {SELECT CAST('18015376320243459' AS UNSIGNED) = 18015376320243459}) Returns 1

Comparison Functions and Operators

NameDescription
BETWEEN ... AND ... Check whether a value is within a range of values
COALESCE()Return the first non-NULL argument
<=>NULL-safe equal to operator
=Equal operator
>=Greater than or equal operator
>Greater than operator
GREATEST()Return the largest argument
IN()Check whether a value is within a set of values
INTERVAL()Return the index of the argument that is less than the first argument
IS NOT NULLNOT NULL value test
IS NOTTest a value against a boolean
IS NULLNULL value test
ISTest a value against a boolean
ISNULL()Test whether the argument is NULL
LEAST()Return the smallest argument
<=Less than or equal operator
<Less than operator
LIKESimple pattern matching
NOT BETWEEN ... AND ...Check whether a value is not within a range of values
!=, <>Not equal operator
NOT IN()Check whether a value is not within a set of values
NOT LIKENegation of simple pattern matching
SOUNDS LIKECompare sounds

Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These operations work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as necessary.

Some of the functions in this section return values other than 1 (TRUE), 0 (FALSE), or NULL. For example, LEAST() and GREATEST(). However, the value they return is based on comparison operations performed.

To convert a value to a specific type for comparison purposes, you can use the CAST() function. String values can be converted to a different character set using CONVERT().

By default, string comparisons are not case sensitive and use the current character set. The default is latin1 (cp1252 West European), which also works well for English.

Logical Operators

Name Description
AND, && Logical AND
NOT, ! Negates value
||, OR Logical OR
XOR Logical XOR

In SQL, all logical operators evaluate to TRUE, FALSE, or NULL (UNKNOWN). In MySQL, these are implemented as 1 (TRUE), 0 (FALSE), and NULL. Most of this is common to different SQL database servers, although some servers may return any non-zero value for TRUE.

Note that MySQL evaluates any non-zero or non-NULL value to TRUE. For example, the following statements all assess to TRUE:

(sql sqlHandle {SELECT 10 IS TRUE}) Returns 1
(sql sqlHandle {SELECT -10 IS TRUE}) Returns 1
(sql sqlHandle {SELECT 'string' IS NOT NULL}) Returns 1

Control Flow Functions

If/else construct
NameDescription
CASECase operator
IF()
IFNULL()Null if/else construct
NULLIF()Return NULL if expr1 = expr2

String Functions

NameDescription
ASCII()Return numeric value of left-most character
BIN()Return a string representation of the argument
BIT_LENGTH()Return length of argument in bits
CHAR_LENGTH()Return number of characters in argument
CHAR()Return the character for each integer passed
CHARACTER_LENGTH()A synonym for CHAR_LENGTH()
CONCAT_WS()Return concatenate with separator
CONCAT()Return concatenated string
ELT()Return string at index number
EXPORT_SET()Return a string such that for every bit set in the value bits, you get an on string and for every unset bit, you get an off string
FIELD()Return the index (position) of the first argument in the subsequent arguments
FIND_IN_SET()Return the index position of the first argument within the second argument
FORMAT()Return a number formatted to specified number of decimal places
HEX()Return a hexadecimal representation of a decimal or string value
INSERT()Insert a substring at the specified position up to the specified number of characters
INSTR()Return the index of the first occurrence of substring
LCASE()Synonym for LOWER()
LEFT()Return the leftmost number of characters as specified
LENGTH()Return the length of a string in bytes
LIKESimple pattern matching
LOAD_FILE()Load the named file
LOCATE()Return the position of the first occurrence of substring
LOWER()Return the argument in lowercase
LPAD()Return the string argument, left-padded with the specified string
LTRIM()Remove leading spaces
MAKE_SET()Return a set of comma-separated strings that have the corresponding bit in bits set
MATCHPerform full-text search
MID()Return a substring starting from the specified position
NOT LIKENegation of simple pattern matching
NOT REGEXPNegation of REGEXP
OCTET_LENGTH()A synonym for LENGTH()
ORD()Return character code for leftmost character of the argument
POSITION()A synonym for LOCATE()
QUOTE()Escape the argument for use in an SQL statement
REGEXPPattern matching using regular expressions
REPEAT()Repeat a string the specified number of times
REPLACE()Replace occurrences of a specified string
REVERSE()Reverse the characters in a string
RIGHT()Return the specified rightmost number of characters
RLIKESynonym for REGEXP
RPAD()Append string the specified number of times
RTRIM()Remove trailing spaces
SOUNDEX()Return a soundex string
SOUNDS LIKECompare sounds
SPACE()Return a string of the specified number of spaces
STRCMP()Compare two strings
SUBSTR()Return the substring as specified
SUBSTRING_INDEX()Return a substring from a string before the specified number of occurrences of the delimiter
SUBSTRING()Return the substring as specified
TRIM()Remove leading and trailing spaces
UCASE()Synonym for UPPER()
UNHEX()Convert each pair of hexadecimal digits to a character
UPPER()Convert to uppercase

String-valued functions return NULL if the length of the result would be greater than the value of the max_allowed_packet system variable.

For functions that operate on string positions, the first position is numbered 1.

For functions that take length arguments, non-integer arguments are rounded to the nearest integer.

String Comparison Functions

NameDescription
LIKESimple pattern matching
NOT LIKENegation of simple pattern matching
SOUNDS LIKECompare sounds

If a string function is given a binary string as an argument, the resulting string is also a binary string. A number converted to a string is treated as a binary string. This affects only comparisons.

Normally, if any expression in a string comparison is case sensitive, the comparison is performed in case-sensitive fashion.

Regular Expressions

NameDescription
NOT REGEXPNegation of REGEXP
REGEXPPattern matching using regular expressions
RLIKESynonym for REGEXP

A regular expression is a powerful way of specifying a pattern for a complex search.

MySQL uses Henry Spencer's implementation of regular expressions, which is aimed at conformance with POSIX 1003.2. MySQL uses the extended version to support pattern-matching operations performed with the REGEXP operator in SQL statements.

This section is a summary, with examples, of the special characters and constructs that can be used in MySQL for REGEXP operations. It does not contain all the details that can be found in Henry Spencer's regex(7) manual page.

A regular expression describes a set of strings. The simplest regular expression is one that has no special characters in it. For example, the regular expression hello matches hello and nothing else.

Non-trivial regular expressions use certain special constructs so that they can match more than one string. For example, the regular expression hello|word matches either the string hello or the string word.

As a more complex example, the regular expression B[an]*s matches any of the strings Bananas, Baaaaas, Bs, and any other string starting with a B, ending with an s, and containing any number of a or n characters in between.

A regular expression for the REGEXP operator may use any of the following special characters and constructs:

Numeric Functions

NameDescription
ABS()Return the absolute value
ACOS()Return the arc cosine
ASIN()Return the arc sine
ATAN2(), ATAN()Return the arc tangent of the two arguments
ATAN()Return the arc tangent
CEIL()Return the smallest integer value not less than the argument
CEILING()Return the smallest integer value not less than the argument
CONV()Convert numbers between different number bases
COS()Return the cosine
COT()Return the cotangent
CRC32()Compute a cyclic redundancy check value
DEGREES()Convert radians to degrees
DIVInteger division
/Division operator
EXP()Raise to the power of
FLOOR()Return the largest integer value not greater than the argument
LN()Return the natural logarithm of the argument
LOG10()Return the base-10 logarithm of the argument
LOG2()Return the base-2 logarithm of the argument
LOG() Return the natural logarithm of the first argument
-Minus operator
MOD()Return the remainder
%Modulo operator
OCT()Return an octal representation of a decimal number
PI()Return the value of pi
+Addition operator
POW()Return the argument raised to the specified power
POWER()Return the argument raised to the specified power
RADIANS()Return argument converted to radians
RAND()Return a random floating-point value
ROUND()Round the argument
SIGN()Return the sign of the argument
SIN()Return the sine of the argument
SQRT()Return the square root of the argument
TAN()Return the tangent of the argument
*Times operator
TRUNCATE()Truncate to specified number of decimal places
-Change the sign of the argument

Arithmetic Operators

NameDescription
DIVInteger division
/Division operator
-Minus operator
%Modulo operator
+Addition operator
*Times operator
-Change the sign of the argument

The usual arithmetic operators are available. The result is determined according to the following rules:

These rules are applied for each operation, such that nested calculations imply the precision of each component. Hence, (14620 / 9432456) / (24250 / 9432456), would resolve first to (0.0014) / (0.0026), with the final result having 8 decimal places (0.60288653).

Because of these rules and the way they are applied, care should be taken to ensure that components and sub-components of a calculation use the appropriate level of precision.

Mathematical Functions

NameDescription
ABS()Return the absolute value
ACOS()Return the arc cosine
ASIN()Return the arc sine
ATAN2(), ATAN()Return the arc tangent of the two arguments
ATAN()Return the arc tangent
CEIL()Return the smallest integer value not less than the argument
CEILING()Return the smallest integer value not less than the argument
CONV()Convert numbers between different number bases
COS()Return the cosine
COT()Return the cotangent
CRC32()Compute a cyclic redundancy check value
DEGREES()Convert radians to degrees
EXP()Raise to the power of
FLOOR()Return the largest integer value not greater than the argument
LN()Return the natural logarithm of the argument
LOG10()Return the base-10 logarithm of the argument
LOG2()Return the base-2 logarithm of the argument
LOG() Return the natural logarithm of the first argument
MOD()Return the remainder
OCT()Return an octal representation of a decimal number
PI()Return the value of pi
POW()Return the argument raised to the specified power
POWER()Return the argument raised to the specified power
RADIANS()Return argument converted to radians
RAND()Return a random floating-point value
ROUND()Round the argument
SIGN()Return the sign of the argument
SIN()Return the sine of the argument
SQRT()Return the square root of the argument
TAN()Return the tangent of the argument
TRUNCATE()Truncate to specified number of decimal places

All mathematical functions return NULL in the event of an error.

Date and Time Functions

This section describes the functions that can be used to manipulate temporal values.

NameDescription
ADDDATE())Add dates
ADDTIME())Add time
CONVERT_TZ()Convert from one timezone to another
CURDATE()Return the current date
CURRENT_DATE(), CURRENT_DATESynonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIMESynonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMPSynonyms for NOW()
CURTIME()Return the current time
DATE_ADD()Add two dates
DATE_FORMAT()Format date as specified
DATE_SUB()Subtract two dates
DATE()Extract the date part of a date or datetime expression
DATEDIFF()Subtract two dates
DAY()Synonym for DAYOFMONTH()
DAYNAME()Return the name of the weekday
DAYOFMONTH()Return the day of the month (0-31)
DAYOFWEEK()Return the weekday index of the argument
DAYOFYEAR()Return the day of the year (1-366)
EXTRACTExtract part of a date
FROM_DAYS()Convert a day number to a date
FROM_UNIXTIME()Format UNIX timestamp as a date
GET_FORMAT()Return a date format string
HOUR()Extract the hour
LAST_DAYReturn the last day of the month for the argument
LOCALTIME(), LOCALTIMESynonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()(v4.0.6)Synonym for NOW()
MAKEDATE()Create a date from the year and day of year
MAKETIMEMAKETIME()
MICROSECOND()Return the microseconds from argument
MINUTE()Return the minute from the argument
MONTH()Return the month from the date passed
MONTHNAME()Return the name of the month
NOW()Return the current date and time
PERIOD_ADD()Add a period to a year-month
PERIOD_DIFF()Return the number of months between periods
QUARTER()Return the quarter from a date argument
SEC_TO_TIME()Converts seconds to 'HH:MM:SS' format
SECOND()Return the second (0-59)
STR_TO_DATE()Convert a string to a date
SUBDATE()A synonym for DATE_SUB() when invoked with three arguments
SUBTIME()Subtract times
SYSDATE()Return the time at which the function executes
TIME_FORMAT()Format as time
TIME_TO_SEC()Return the argument converted to seconds
TIME()Extract the time portion of the expression passed
TIMEDIFF()Subtract time
TIMESTAMP()With a single argument, this function returns the date or datetime expression; with two arguments, the sum of the arguments
TIMESTAMPADD()Add an interval to a datetime expression
TIMESTAMPDIFF()Subtract an interval from a datetime expression
TO_DAYS()Return the date argument converted to days
UNIX_TIMESTAMP()Return a UNIX timestamp
UTC_DATE()Return the current UTC date
UTC_TIME()Return the current UTC time
UTC_TIMESTAMP()Return the current UTC date and time
WEEK()Return the week number
WEEKDAY()Return the weekday index
WEEKOFYEAR()Return the calendar week of the date (0-53)
YEAR()Return the year
YEARWEEK()Return the year and week

Here is an example that uses date functions. The following query selects all rows with a date_col value from within the last 30 days:

(sql sqlHandle {SELECT something FROM tbl_name WHERE DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= date_col})

The query also selects rows with dates that lie in the future.

Functions that expect date values usually accept datetime values and ignore the time part. Functions that expect time values usually accept datetime values and ignore the date part.

Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result. (For our purposes, a single query also includes a call to a stored program (stored routine, trigger, or event) and all sub-programs called by that program.) This principle also applies to CURDATE(), CURTIME(), UTC_DATE(), UTC_TIME(), UTC_TIMESTAMP(), and to any of their synonyms.

The CURRENT_TIMESTAMP(), CURRENT_TIME(), CURRENT_DATE(), and FROM_UNIXTIME() functions return values in the connection's current time zone, which is available as the value of the time_zone system variable. In addition, UNIX_TIMESTAMP() assumes that its argument is a datetime value in the current time zone.

Some date functions can be used with "zero" dates or incomplete dates such as '2001-11-00', whereas others cannot. Functions that extract parts of dates typically work with incomplete dates and thus can return 0 when you might otherwise expect a non-zero value. For example:

(sql sqlHandle {SELECT DAYOFMONTH('2001-11-00'), MONTH('2005-00-00')}) Returns 0, 0

Other functions expect complete dates and return NULL for incomplete dates. These include functions that perform date arithmetic or that map parts of dates to names. For example:

(sql sqlHandle {SELECT DATE_ADD('2006-05-00',INTERVAL 1 DAY)}) Returns NULL
(sql sqlHandle {SELECT DAYNAME('2006-05-00')}) Returns NULL

Cast Functions and Operators

NameDescription
BINARYCast a string to a binary string
CAST()Cast a value as a certain type
Convert()Cast a value as a certain type

Normally, you cannot compare a BLOB value or other binary string in case-insensitive fashion because binary strings have no character set, and thus no concept of lettercase. To perform a case-insensitive comparison, use the CONVERT() function to convert the value to a non-binary string. If the character set of the result has a case-insensitive collation, the LIKE operation is not case sensitive:

(sql sqlHandle {SELECT 'A' LIKE CONVERT(blob_col USING latin1) FROM tbl_name})

To use a different character set, substitute its name for latin1 in the preceding statement. To ensure that a case-insensitive collation is used, specify a COLLATE clause following the CONVERT() call.

CONVERT() can be used more generally for comparing strings that are represented in different character sets.

The cast functions are useful when you want to create a column with a specific type in a CREATE ... SELECT statement:

(sql sqlHandle {CREATE TABLE new_table SELECT CAST('2000-01-01' AS DATE)})

The functions also can be useful for sorting ENUM columns in lexical order. Normally, sorting of ENUM columns occurs using the internal numeric values. Casting the values to CHAR results in a lexical sort:

(sql sqlHandle {SELECT enum_col FROM tbl_name ORDER BY CAST(enum_col AS CHAR)})

CAST(str AS BINARY) is the same thing as BINARY str. CAST(expr AS CHAR) treats the expression as a string with the default character set.

CAST() also changes the result if you use it as part of a more complex expression such as CONCAT('Date: ',CAST(NOW() AS DATE)).

You should not use CAST() to extract data in different formats but instead use string functions like LEFT() or EXTRACT().

To cast a string to a numeric value in numeric context, you normally do not have to do anything other than to use the string value as though it were a number:

(sql sqlHandle {SELECT 1+'1'}) Returns 2

If you use a number in string context, the number automatically is converted to a BINARY string.

(sql sqlHandle {SELECT CONCAT('hello you ',2)}) Returns 'hello you 2'

MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using numeric operators (such as + or -) and one of the operands is an unsigned integer, the result is unsigned. You can override this by using the SIGNED and UNSIGNED cast operators to cast the operation to a signed or unsigned 64-bit integer, respectively.

(sql sqlHandle {SELECT CAST(1-2 AS UNSIGNED)}) Returns 18446744073709551615
(sql sqlHandle {SELECT CAST(CAST(1-2 AS UNSIGNED) AS SIGNED)}) Returns -1

Note that if either operand is a floating-point value, the result is a floating-point value and is not affected by the preceding rule. (In this context, DECIMAL column values are regarded as floating-point values.)

(sql sqlHandle {SELECT CAST(1 AS UNSIGNED) - 2.0}) Returns -1.0

If you are using a string in an arithmetic operation, this is converted to a floating-point number.

If you convert a "zero" date string to a date, CONVERT() and CAST() return NULL and produce a warning when the NO_ZERO_DATE SQL mode is enabled.

Other Functions

NameDescription
AES_DECRYPT()Decrypt using AES
AES_ENCRYPT()Encrypt using AES
BENCHMARK()Repeatedly execute an expression
BIT_COUNT()Return the number of bits that are set
&Bitwise AND
~Invert bits
|Bitwise OR
^Bitwise XOR
CHARSET()Return the character set of the argument
COERCIBILITY()Return the collation coercibility value of the string argument
COLLATION()Return the collation of the string argument
COMPRESS()Return result as a binary string
CONNECTION_ID()Return the connection ID (thread ID) for the connection
CURRENT_USER(), CURRENT_USERReturn the username and hostname combination
DATABASE()Return the default (current) database name
DECODE()Decodes a string encrypted using ENCODE()
DEFAULT()Return the default value for a table column
DES_DECRYPT()Decrypt a string
DES_ENCRYPT()Encrypt a string
ENCODE()Encode a string
ENCRYPT()Encrypt a string
FOUND_ROWS()For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
GET_LOCK()Get a named lock
INET_ATON()Return the numeric value of an IP address
INET_NTOA()Return the IP address from a numeric value
IS_FREE_LOCK()Checks whether the named lock is free
IS_USED_LOCK()Checks whether the named lock is in use. Return connection identifier if true.
LAST_INSERT_ID()Value of the AUTOINCREMENT column for the last INSERT
<<Left shift
MASTER_POS_WAIT()Block until the slave has read and applied all updates up to the specified position
MD5()Calculate MD5 checksum
NAME_CONST()Causes the column to have the given name
OLD_PASSWORD()Return the value of the old implementation of PASSWORD
PASSWORD()Calculate and return a password string
RAND()Return a random floating-point value
RELEASE_LOCK()Releases the named lock
>>Right shift
ROW_COUNT()The number of rows updated
SCHEMA()A synonym for DATABASE()
SESSION_USER()Synonym for USER()
SHA1(), SHA()Calculate an SHA-1 160-bit checksum
SLEEP()Sleep for a number of seconds
SYSTEM_USER()Synonym for USER()
UNCOMPRESS()Uncompress a string compressed
UNCOMPRESSED_LENGTH()Return the length of a string before compression
USER()Return the current username and hostname
UUID_SHORT()Return an integer-valued universal identifier
UUID()Return a Universal Unique Identifier (UUID)
VALUES()Defines the values to be used during an INSERT
VERSION()Returns a string that indicates the MySQL server version

Bit Functions

NameDescription
BIT_COUNT()Return the number of bits that are set
&Bitwise AND
~Invert bits
|Bitwise OR
^Bitwise XOR
<<Left shift
>>Right shift

MySQL uses BIGINT (64-bit) arithmetic for bit operations, so these operators have a maximum range of 64 bits.

Encryption and Compression Functions

NameDescription
AES_DECRYPT()Decrypt using AES
AES_ENCRYPT()Encrypt using AES
COMPRESS()Return result as a binary string
DECODE()Decodes a string encrypted using ENCODE()
DES_DECRYPT()Decrypt a string
DES_ENCRYPT()Encrypt a string
ENCODE()Encode a string
ENCRYPT()Encrypt a string
MD5()Calculate MD5 checksum
OLD_PASSWORD()Return the value of the old implementation of PASSWORD
PASSWORD()Calculate and return a password string
SHA1(), SHA()Calculate an SHA-1 160-bit checksum
UNCOMPRESS()Uncompress a string compressed
UNCOMPRESSED_LENGTH()Return the length of a string before compression

Note: The encryption and compression functions return binary strings. For many of these functions, the result might contain arbitrary byte values. If you want to store these results, use a column with a VARBINARY or BLOB binary string data type. This will avoid potential problems with trailing space removal or character set conversion that would change data values, such as may occur if you use a non-binary string data type (CHAR, VARCHAR, TEXT).

Note: Exploits for the MD5 and SHA-1 algorithms have become known. You may wish to consider using one of the other encryption functions described in this section instead.

Information Functions

NameDescription
BENCHMARK()Repeatedly execute an expression
CHARSET()Return the character set of the argument
COERCIBILITY()Return the collation coercibility value of the string argument
COLLATION()Return the collation of the string argument
CONNECTION_ID()Return the connection ID (thread ID) for the connection
CURRENT_USER(), CURRENT_USERReturn the username and hostname combination
DATABASE()Return the default (current) database name
FOUND_ROWS()For a SELECT with a LIMIT clause, the number of rows that would be returned were there no LIMIT clause
LAST_INSERT_ID()Value of the AUTOINCREMENT column for the last INSERT
ROW_COUNT()The number of rows updated
SCHEMA()A synonym for DATABASE()
SESSION_USER()Synonym for USER()
SYSTEM_USER()Synonym for USER()
USER()Return the current username and hostname
VERSION()Returns a string that indicates the MySQL server version

Miscellaneous Functions

Name
DEFAULT()Return the default value for a table column
GET_LOCK()Get a named lock
INET_ATON()Return the numeric value of an IP address
INET_NTOA()Return the IP address from a numeric value
IS_FREE_LOCK()Checks whether the named lock is free
IS_USED_LOCK()Checks whether the named lock is in use. Return connection identifier if true.
MASTER_POS_WAIT()Block until the slave has read and applied all updates up to the specified position
NAME_CONST()Causes the column to have the given name
RAND()Return a random floating-point value
RELEASE_LOCK()Releases the named lock
SLEEP()Sleep for a number of seconds
UUID_SHORT()Return an integer-valued universal identifier
UUID()Return a Universal Unique Identifier (UUID)
VALUES()Defines the values to be used during an INSERT

GROUP BY (Aggregate) Functions

NameDescription
AVG()Return the average value of the argument
BIT_AND()Return bitwise and
BIT_OR()Return bitwise or
BIT_XOR()Return bitwise xor
COUNT(DISTINCT)Return the count of a number of different values
COUNT()Return a count of the number of rows returned
GROUP_CONCAT()Return a concatenated string
MAX()Return the maximum value
MIN()Return the minimum value
STD()Return the population standard deviation
STDDEV_POP()Return the population standard deviation
STDDEV_SAMP()Return the sample standard deviation
STDDEV()Return the population standard deviation
SUM()Return the sum
VAR_POP()Return the population standard variance
VAR_SAMP()Return the sample variance
VARIANCE()Return the population standard variance

This section describes group (aggregate) functions that operate on sets of values. Unless otherwise stated, group functions ignore NULL values.

If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows.

For numeric arguments, the variance and standard deviation functions return a DOUBLE value. The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE).

The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the values to numbers, losing everything after the first non-numeric character.) To work around this problem, you can convert to numeric units, perform the aggregate operation, and convert back to a temporal value. Examples:

SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name
SELECT FROM_DAYS(SUM(TO_DAYS(date_col))) FROM tbl_name

Functions such as SUM() or AVG() that expect a numeric argument cast the argument to a number if necessary. For SET or ENUM values, the cast operation causes the underlying numeric value to be used.