Chapter 12. Functions and Operators

MySQL 5.0

Chapter 12. Functions and Operators

Expressions can be used at several points in SQL statements, such as in the or clauses of statements, in the clause of a , , or statement, or in statements. Expressions can be written using literal values, column values, , 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. Instructions for writing stored functions and user-defined functions are given in Chapter 17, Stored Procedures and Functions, and Section 24.2, “Adding New Functions to MySQL”.

An expression that contains always produces a 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 option. (See Section 5.2.5, “The Server SQL Mode”.) Individual client programs can request this behavior by using the option for . 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:

mysql> 
+-----------+
| mod(29,9) |
+-----------+
|         2 |
+-----------+
1 rows in set (0.00 sec)

This format is used instead:

mysql> 
        -> 2

12.1. Operators

12.1.1. Operator Precedence

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

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

The precedence shown for is as of MySQL 5.0.2. For earlier versions, or from 5.0.2 on if the SQL mode is enabled, the precedence of is the same as that of the operator. See Section 5.2.5, “The Server SQL Mode”.

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:

mysql> 
        -> 7
mysql> 
        -> 9

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

mysql> 
        -> 2
mysql> 
        -> '2 test'

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

mysql> 
        -> 38.8, '38.8'
mysql> 
        -> 38.8, '38.8'

The following rules describe how conversion occurs for comparison operations:

  • If one or both arguments are , the result of the comparison is , except for the -safe equality comparison operator. For , 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 or 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 ! 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:

mysql> 
        -> 0
mysql> 
        -> 1
mysql> 
        -> 0
mysql> 
        -> 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 is an indexed string column, the index cannot be used when performing the lookup in the following statement:

SELECT * FROM  WHERE =1;

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

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:

mysql> 
        -> 1
mysql> 
        -> 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:

mysql> 
        -> 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 so that a value will not be converted implicitly to a float-point number:

mysql> 
        -> 1

For more information about floating-point comparisons, see Section A.5.8, “Problems with Floating-Point Comparisons”.

12.1.3. Comparison Functions and Operators

Comparison operations result in a value of (), (), or . 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 (such as and ) return values other than (), (), or . However, the value they return is based on comparison operations performed according to the rules described in Section 12.1.2, “Type Conversion in Expression Evaluation”.

To convert a value to a specific type for comparison purposes, you can use the function. String values can be converted to a different character set using . See Section 12.8, “Cast Functions and Operators”.

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

  • Equal:

    mysql> 
            -> 0
    mysql> 
            -> 1
    mysql> 
            -> 1
    mysql> 
            -> 0
    mysql> 
            -> 1
    
  • -safe equal. This operator performs an equality comparison like the operator, but returns rather than if both operands are , and rather than if one operand is .

    mysql> 
            -> 1, 1, 0
    mysql> 
            -> 1, NULL, NULL
    
  • ,

    Not equal:

    mysql> 
            -> 1
    mysql> 
            -> 0
    mysql> 
            -> 1
    
  • Less than or equal:

    mysql> 
            -> 1
    
  • Less than:

    mysql> 
            -> 0
    
  • Greater than or equal:

    mysql> 
            -> 1
    
  • Greater than:

    mysql> 
            -> 0
    
  • ,

    Tests a value against a boolean value, where can be , , or .

    mysql> 
            -> 1, 1, 1
    mysql> 
            -> 1, 1, 0
    

    syntax was added in MySQL 5.0.2.

  • ,

    Tests whether a value is or is not .

    mysql> 
            -> 0, 0, 1
    mysql> 
            -> 1, 1, 0
    

    To work well with ODBC programs, MySQL supports the following extra features when using :

    • You can find the row that contains the most recent value by issuing a statement of the following form immediately after generating the value:

      SELECT * FROM  WHERE  IS NULL
      

      This behavior can be disabled by setting . See Section 13.5.3, “ Syntax”.

    • For and columns that are declared as , you can find the special date by using a statement like this:

      SELECT * FROM  WHERE  IS NULL
      

      This is needed to get some ODBC applications to work because ODBC does not support a date value.

  • BETWEEN AND

    If is greater than or equal to and is less than or equal to , returns , otherwise it returns . This is equivalent to the expression <= AND <= ) if all the arguments are of the same type. Otherwise type conversion takes place according to the rules described in Section 12.1.2, “Type Conversion in Expression Evaluation”, but applied to all the three arguments.

    mysql> 
            -> 0
    mysql> 
            -> 1
    mysql> 
            -> 1
    mysql> 
            -> 0
    
  • NOT BETWEEN AND

    This is the same as BETWEEN AND ).

  • ,...)

    Returns the first non- value in the list, or if there are no non- values.

    mysql> 
            -> 1
    mysql> 
            -> NULL
    
  • ,,...)

    With two or more arguments, returns the largest (maximum-valued) argument. The arguments are compared using the same rules as for .

    mysql> 
            -> 2
    mysql> 
            -> 767.0
    mysql> 
            -> 'C'
    

    Before MySQL 5.0.13, returns only if all arguments are . As of 5.0.13, it returns if any argument is .

  • IN (,...)

    Returns if is equal to any of the values in the list, else returns . If all values are constants, they are evaluated according to the type of and sorted. The search for the item then is done using a binary search. This means is very quick if the value list consists entirely of constants. Otherwise, type conversion takes place according to the rules described in Section 12.1.2, “Type Conversion in Expression Evaluation”, but applied to all the arguments.

    mysql> 
            -> 0
    mysql> 
            -> 1
    

    You should never mix quoted and unquoted values in an list because the comparison rules for quoted values (such as strings) and unquoted values (such as numbers) differ. Mixing types may therefore lead to inconsistent results. For example, do not write an expression like this:

    SELECT val1 FROM tbl1 WHERE val1 IN (1,2,'a');
    

    Instead, write it like this:

    SELECT val1 FROM tbl1 WHERE val1 IN ('1','2','a');
    

    The number of values in the list is only limited by the value.

    To comply with the SQL standard, returns not only if the expression on the left hand side is , but also if no match is found in the list and one of the expressions in the list is .

    syntax can also be used to write certain types of subqueries. See Section 13.2.8.3, “Subqueries with , , and .

  • NOT IN (,...)

    This is the same as IN (,...)).

  • )

    If is , returns , otherwise it returns .

    mysql> 
            -> 0
    mysql> 
            -> 1
    

    can be used instead of to test whether a value is . (Comparing a value to using always yields false.)

    The function shares some special behaviors with the comparison operator. See the description of .

  • ,,,,...)

    Returns if < , if < and so on or if is . All arguments are treated as integers. It is required that < < < < for this function to work correctly. This is because a binary search is used (very fast).

    mysql> 
            -> 3
    mysql> 
            -> 2
    mysql> 
            -> 0
    
  • ,,...)

    With two or more arguments, returns the smallest (minimum-valued) argument. The arguments are compared using the following rules:

    • If the return value is used in an context or all arguments are integer-valued, they are compared as integers.

    • If the return value is used in a context or all arguments are real-valued, they are compared as reals.

    • If any argument is a case-sensitive string, the arguments are compared as case-sensitive strings.

    • In all other cases, the arguments are compared as case-insensitive strings.

    Before MySQL 5.0.13, returns only if all arguments are . As of 5.0.13, it returns if any argument is .

    mysql> 
            -> 0
    mysql> 
            -> 3.0
    mysql> 
            -> 'A'
    

    Note that the preceding conversion rules can produce strange results in some borderline cases:

    mysql> 
            -> -9223372036854775808
    

    This happens because MySQL reads in an integer context. The integer representation is not good enough to hold the value, so it wraps to a signed integer.

12.1.4. Logical Operators

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

  • ,

    Logical NOT. Evaluates to if the operand is , to if the operand is non-zero, and returns .

    mysql> 
            -> 0
    mysql> 
            -> 1
    mysql> 
            -> NULL
    mysql> 
            -> 0
    mysql> 
            -> 1
    

    The last example produces because the expression evaluates the same way as .

    Note that the precedence of the operator changed in MySQL 5.0.2. See Section 12.1.1, “Operator Precedence”.

  • ,

    Logical AND. Evaluates to if all operands are non-zero and not , to if one or more operands are , otherwise is returned.

    mysql> 
            -> 1
    mysql> 
            -> 0
    mysql> 
            -> NULL
    mysql> 
            -> 0
    mysql> 
            -> 0
    
  • ,

    Logical OR. When both operands are non-, the result is if any operand is non-zero, and otherwise. With a operand, the result is if the other operand is non-zero, and otherwise. If both operands are , the result is .

    mysql> 
            -> 1
    mysql> 
            -> 1
    mysql> 
            -> 0
    mysql> 
            -> NULL
    mysql> 
            -> 1
    
  • Logical XOR. Returns if either operand is . For non- operands, evaluates to if an odd number of operands is non-zero, otherwise is returned.

    mysql> 
            -> 0
    mysql> 
            -> 1
    mysql> 
            -> NULL
    mysql> 
            -> 1
    

    is mathematically equal to .