Mysql Comparsion N Condition

You might also like

Download as pdf
Download as pdf
You are on page 1of 61
svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Functions for Use in SELECT and WHERE Clauses A select_expression or where_definition in a SQL statement can consist of any expression using the functions described next. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression. Note: there must be no whitespace between a function name and the parentheses 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. Spaces around arguments are permitted, though. You can force MySQL to accept spaces after the function name by starting mysqld with —ansi or using the CLIENT_IGNORE_SPACE to mysql_conneet( ), but in this become reserved words. See Section 1.7.2. se all function names will For the sake of brevity, examples display the output from the mysql program in abbreviated form. So this: mysql> SELECT MOD (29,9); i rows in set (0.00 sec) is displayed like this: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml ‘vet svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Parentheses Use parentheses to force the order of evaluation in an expression. For example: mysql> SELECT 14243; nysq) Pr (142)*3; Comparison operators Comparison operations result in a value of 1 (TRUE), 0 (FALSE), or NULL. These functions work for both numbers and strings. Strings are automatically converted to numbers and numbers to strings as needed (as in Perl). ing the following rules © Ifone or both arguments are NULL, the result of the comparison is NULL, except for the <=> operator. © Ifboth 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. © Ifone of the arguments is a1 ‘AMP or DAT constant, the constant is converted to a timestamp before the comparison is performed. This is done to be more ODBC-friendly. TIME column and the other argument is a ° Inall other cases, the arguments are compared as floating-point (real) numbers. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 2161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysql> mysqi> SELECT '0.0' = 0; mysqi> SELECT =o LECT '.01' = 0.01; mysqi> SELECT 'zapp' <> 'zappp'; Less than or equal: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml sist svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Greater than or equal: mysql> SELECT 2 Greater than: 2>2 - NULL safe equal: mysqi> SELECT 1 <=> 1, NULL <=> NULL, 1 <=> NULL: > 110 IS NULL , IS NOT NULL Test whether a value is or is not NULL: ECT 1 IS NULL, 0 IS NULL, NULL TS NULL; > ool mysqi> SELECT 1 IS NOT NULL, 0 IS NOT NULL, NULL > 110 hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 4161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari This n be disabled by setting SQL_AUTO_IS_NULL=0. See Section 5.5.6. © For NOT NULL DATE and DATETIME columns you can find the special date 0000- 00-00 by using: SELECT * FROM tbl name WHERE date column IS Ml is is needed to get some ODBC applications to work (as ODBC doesn’t support a 0000-00-00 date). expr BETWEEN min AND max If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0. This is equivalent to the expression (min <= expr AND expr <= max) if all the arguments are of the same type. The first argument (expr) determines how the comparison is performed as follow: © Ifexprisa TIMESTAMP, DATE, or DATE IME column, MIN() and MAX() are formatted to the same format if they are constants, © Hfexprisa insitive string expression, a case-insensitive string comparison is done. © Ifexpr is a case-sensitive string expression, a case-sensitive string comparison is done. © Ifexpr is an integer expression, an integer comparison is done. © Otherwise, a floating-point (real) comparison is done. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml si6t svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari => 1 mysql> SELECT 2 BETWEEN 2 AND expr NOT BETWEEN min AND max Same as NOT (expr BETWEEN min AND max). expr IN (value,,..) Returns 1 if expr is any of the values in the IN list, otherwise returns 0. If all values are constants, all values are evaluated according to the type of expr and sorted. The search for the item is then done using a binary search. This means IN is very quick if the IN value list consists entirely of constants. If expr is a case-sensitive string expression, the string comparison is performed in case-sensitive fashion: ECT 2 IN (0,3,5,"wefwe"); mysqi> SELECT ‘wefwe’ IN (0,3,5,"wefwl"); expr NOT IN (value,...) Same as NOT (expr IN (value,...)). ISNULL(expr) If expr is NULL, ISNULL() returns 1, otherwise it returns 0: mysq2> mysql> § Note that a comparison of NULL values using = will always be false! hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari > wo INTERVAL(N.NI,N2,N3,...) Returns 0 if N < NI, 1 if N < N2, and so on. All arguments are treated as integers. It is required that NI < N2 < N3<.... < Nn for this function to work correctly. This a binary search is used (very fast) s because mysql> SELECT IW >o If you are comparing a case-sensitive string with any of the standard operators (=, <>..., but not LIKE) the end space will be ignored. Logical operators All logical functions return 1 (TRUE), 0 (FALSE), or NULL (unknown, which is in most e: same as FALSE): NOT Logical NOT. Returns 1 if the argument is 0, otherwise returns 0. Exception: NOT NULL returns NU mysql> SELECT NoT 1; mysql> SELECT NOT NULb: hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650%ct06s03.ntml 781 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari OR, || Logical OR. Returns 1 if either argument is not 0 and not NULL: AND , && Logical AND. Returns 0 if either argument is 0 or NULL, otherwise returns 1: mysqi> SELECT 1 && NULL; >o Control flow functions IFNULL(exprl,expr2) If expr is not NULL, IF NULL() returns expr, otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used: SELECT IFW 160) nysq: RECT TFNULL (NULL, 10); mysqi> SELECT IFNULL (1/0, 10) 7 mysql> 1/0, *yes"); hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml ict Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] svs0r2018 fey; t ERG Safari NULLIF (1,2) Note that expr1 is evaluated twice in MySQL if the arguments are equal. IF(exprlexpr2,expr3) If exprl is TRUE (expr > 0 and expri <> NULL), IF() returns expr2, otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used: mysql> >2,2,3)i mysql> 1<2, "yes", *n0"); mysqi> s (STRCMP("test', 'testL expri is evaluated as an integer value, which means that if you are testing floating-point or string values, you should do so using a comparison operation: mysq: mysql> In the first case, IF(0.1) returns 0 because 0.1 is converted to an integer value, resulting ina test of IF(0). This may not be what you expect. In the second case, the comparison tests the original floating-point value to see whether it is non-zero. The result of the comparison is used as an integer. ‘The default return type of IF() (which may matter when it is stored into a temporary table) is calculated in MySQL Version 3.23 as follows: hips: safarbooksontine.convibraryviewimysq/reference-manval0596002650/ch06s03.himl svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari expr2 or expr3 returns a floating-point value floating-point expr? or expr3 returns an integer integer If expr2 and exprg are strings, then the result is case-sensitive if both strings are case- sensitive. (Starting from 3.23.51) CASE value WHEN [compare-value] THEN result [WHEN [compare-value] THEN result .. [ELSE result] END , CASE WHEN [condition] THEN result [WHEN [condition] THEN result so] [ELSE result] END ‘The first version returns the result where value=compare-value. The second version returns the result for the first condition, which is true. If there was no matching result value, the result after ELSE is returned. If there is no ELSE part, NULL is returned: WHEN 2 THEN END; WHEN 1>0 THEN "true" ELSE "false" END; BINARY THEN 1 WHEN "b" THEN 2 END; The type of the return value (INTEGER, DOUBLE or STRING) is the same as the type of the first jion after the first THEN). returned value (the expres String Functions String-valued functions return NULL if the length of the result would be greater than the max_allowed_packet server parameter. See Section 5.5.2. For functions that operate on string positions, the first position is numbered 1 hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 10161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari a; See also the ORD() function. ORD(str) er, returns the code for If the leftmost character of the string str is a multi-byte char: that character, calculated from the ASCII code values of its constituent characters using ((first byte ASCIT code)*256+(second byte ASCII code))[*256+third byte ASCII code...]. If the leftmost character is not a multi-byte character, returns the same value that the ASCII() function does: this formul: CONV(N,from_base,to_base) Converts numbers between different number bases. Returns a string representation of the number N, converted from base from_base to base to_base. Returns NULL if any argument is NULL. The argument N is interpreted as an integer, but may be specified as an integer or a string. The minimum base is 2 and the maximum base is 36. If to_base isa negative number, N is regarded as a signed number. Otherwise, unsigned. CONV works with 64-bit precision: s treated as mysql> mysqi> 8 CONV (10+"10"+"10"+0xa, 10,10) 7 MySQL Reference Manual by Kaj Arno, David Axmark, Michael Widenius hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml tet svs0r20%8 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] Prev Next Column Types Data Manipulation: SELECT, INSERT, UPDATE, DELETE! —> TrnoO" ocT(N) Returns a string representation of the octal value of N, where N is a longlong number. This is equivalent to CONV(N,10,8). Returns NULL if N is NULL: ECT OCT (12); a HEX(N_or_S) IfN_OR_Sis a number, returns a string representation of the hexadecimal value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,16). IfN_OR_S is a string, returns a hexadecimal string of N_OR_S where each character in N_OR_Sis converted to 2 hexadecimal digits. This is the inverse of the Oxff strings. mysql> SELECT HEX (255); —> 'PE! mysql> SELECT HEX ("abe") ; —> 616263 mysql> SELECT 0x616263; CHAR(,... CHAR() interprets the arguments as integers and returns a string consisting of the characters given by the ASCII code values of those integers. NULL values are skipped: mysql> SELECT CHAR (77,121, 83, 81,176"); "mysoL? T CHAR(77,77.3,°77.39)5 mysql> SELE CONCAT(tr1,str2,...) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 12161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari "ay", NULL, *OL")5 CONCAT_WS(separator, str, str2,...) CONCAT_WS() stands for CONCAT With Separator and is a special form of CONCAT( ). The first argument is the separator for the rest of the arguments. The separator can be a string as well as the rest of the arguments. If the separator is NULL, the result will be NULL. The function will skip any NULLs and empty strings, after the separator argument. The separator will be added between the strings to be concatenated: ond name", ast Name"); d_name, Last Name" “First name",NULL, "Last Name"); LENGTH(str) , CHAR_LENGTH(str) , CHARACTER_LENGTH(str) Returns the length of the string str: mysqi> SELECT LENGTH ("te 4 mysql> SELECT OCTET_LENGTA(*text'); >a Note that for CHAR_LENGTH() and CHARACTER_LENGTH(), multi-byte characters are only counted once. BIT_LENGTH(str) Returns the length of the string str in bits: mysql> SELECT BIT_LENGTE('text'); hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650Vch06s03.ntml 1361 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysql> SELECT LOCATE('bar', ‘foobarbar'); *foobar"); This function is multi-byte safe. In MySQL 3.23 this function is case- insensitive, while in 4.0 it’s only case-insensitive if either argument is a binary string. LOCATE(substr,str,pos) Returns the position of the first occurrence of substring substr in string str, starting at position pos. Returns 0 if substr is not in str: mysql> SELECT LOCATE('bar', ‘foobarbar', 5); This function is multi-byte safe. In MySQL 3.23 this function is case- insensitive, while in 4.0 it’s only case-insensitive if either argument is a binary string. INSTR(str,substr) Returns the position of the first occurrence of substring substr in string str. This is the same as the two-argument form of LOCATE(), except that the arguments are swapped: mysqi> SELECT INS?R('foobarbar', ‘bar > mysql> R('xbar', foobar"): This function is multi-byte safe. In MySQL 3.23 this function is case- insensitive, while in 4.0 it’s only case-i ve if either argument is a binary string, LPAD(str;len,padstr) Returns the string str, left-padded with the string padstr until str is len characters long. If str is longer than len’ it will be shortened to len characters, hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4101 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari long. If str is longer than len! then it will be shortened to len characters. mysql> SELECT RPAD(*hi",5,'2"); LEFT(strlen) Returns the leftmost len characters from the string str: This function is multi-byte safe. RIGHT (strlen) Returns the rightmost len characters from the string str: This function is multi-byte safe. SUBSTRING(str,pos,len) , SUBSTRING(str FROM pos FOR len) , MID(str,pos,len) Returns a substring len characters long from string str, starting at position pos. The variant form that uses FROM is ANSI SQL92 syntax: ECT SUBSTRING (‘*Quadratically', 5,6); This function is multi-byte safe. SUBSTRING(str,pos) , SUBSTRING(str FROM pos) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 15161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ‘This function is multi-byte safe. SUBSTRING_INDEX(str,delim,count) Returns the substring from string str before count occurrences of the delimiter delim. If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned: mysql> SELECT SUBSTR |INDEX (werw.mysql.com', "2", 207 sTRING_IND! (Ciwww mnysgl.com', mysql> SELECT Sv: —> tmysql.com! This function is multi-byte safe. LTRIMGtr) Returns the string str with leading space characters removed: mysqi> M(! barbar'); > tbarbaz! RTRIM(str) Returns the string str with trailing space characters removed: RCT RTRTM(*barbar This function is multi-byte safe. TRIM([BOTH | LEADING | TRAILING] [remstr] FROM] str) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 16161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysql> SELECT TRIM(LEADING 'x' FROM "xxxbarxxx") 7 > tbarxxx! mysqi> SELECT TRIM(BOTH "x" FROM tiexxbarxxx') ; -> thar! mysql> TRIM(TRATLING "xyz" FROM ‘barxxyz"); —> tbarx! This function is multi-byte safe. SOUNDEX(str) Returns a soundex string from str. Two strings that sound almost the same should have identical soundex strings. A standard soundex string is 4 characters long, but the SOUNDEX() function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a standard soundex string. All non-alphanumeric characters are ignored in the given string. All international alpha characters outside the A-Z range are treated as vowels "T SOUNDEX (‘Hello") ; > +4400! mysql> SELECT OUNDEX ("Quad "936324" ically’ SPACE(N) Returns a string consisting of N space characters: mysql> SELECT REPLACE(str,from_str,to_str) Returns the string str with all occurrences of the string from_str replaced by the string to_str: mysql> Hy tw WED SEPLACE ("ww mys > tWanwite.mysql.com! hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650%ct06s03.ntml 17161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ‘an empty string. Returns If str or count are mysql> ECT REPEAT ( "My: as > 'MySOLMysoLMysoL" REVERSE(str) Returns the string str with the order of the characters reversed: mysql> SELECT REVERSE ("abe") ; This function is multi-byte safe. INSERT(str,pos,len,newstr) Returns the string str, with the substring beginning at po long replaced by the string newstr: ition pos and len characters mysqi> SELECT ‘Quamattic! This function is multi-byte safe. ELT(N,str1,str2,str3,...) Returns str] if 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments. ELT() is the complement of FIELD(): FIELD(str,str1,str2,str3,...) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 18161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari FIND_IN_SET(str,strlist) Returns a value 1 to N if the string str is in the list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET, the FIND_IN_SET() function is optimised to use bit arithmetic! Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL. This function will not work properly if the first argument contains a , mysql> SELECT FIND_IN SBT('b', tab, c/a"); >2 MAKE_SET(bits,str1,str2,...) Returns a set (a string containing substrings separated by , characters) consisting of the strings that have the corresponding bit in bits set. str corresponds to bit o, str2 to bit 1, etc. NULL strings in str, str2, ... are not appended to the result: mysql> SELECT MAKE SET(1,'a", "bi, te"); mysql> SELECT MAKE_SET(1 | 4, ‘hello', ‘nice’, 'world") ECT MAKE_SET(O,'a", "bY, 'c'); EXPORTS! its) its,on,off,[separator,[number_of_} Returns a string where for every bit set in ‘bit’, you get an ‘on’ string and for every reset bit you get an ‘off string. Each string is separated with ‘separator’ (default '") and only ‘number_of_bits' (default 64) of ‘its is used. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 19161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari n> quadraricarly” This function is multi-byte safe. UCASE(str) , UPPER(str) Returns the string str with all characters changed to uppercase according to the current character set mapping (the default is ISO-8859-1 Latin1): tHej"); This function is multi-byte safe. LOAD_FILE(file_name) Reads the file and returns the file contents as a string. The file must be on the server, you must specify the full pathname to the file, and you must have the file privilege. The file must be readable by all and be smaller than max_allowed_packet. If the file doesn’t exist or can't be read due to one of these reasons, the function returns NULL: > UPDATE thl_name blob column=LOAD FILE ("/tmp/picture") WHERE id=1; Ifyou are not using MySQL Version 3.23, you have to read the file inside your application and create an INSERT statement to update the database with the file information. One way to do this, i you are using the MySQL++ library, can be found at http://www. mysql.com/documentation/mysql++/mysql+ +-examples.html. MySQL automatically converts numbers to strings as necessary, and vice versa: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 20161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Ifa 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 only affects comparisons. String comparison functions Normally, if any expression in a string comparison i in case-sensitive fashion. nitive, the comparison is performed expr LIKE pat [ESCAPE 'escape-char'] Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). With LIKE you can use the following two wildcard characters in the pattern: Char % ‘Matches any number of characters, even zero characters . Matches exactly one character mysql> SELECT ‘David!" LIKE * mysql> SELECT "David!" LIKE 'SsDWv#"; To test for literal instances of a wildcard character, precede the character with the escape character. If you don’t specify the ESCAPE character, \ is assumed: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari \ ‘Matches one_ character mysqi> SELECT "David! ' LIKE "David\_'; T ‘David_' LIKE 'David\_'; To specify a different escape character, use the ESCAPE clause: mysql> CT ‘David_' LIKE ‘David|_' ES >1 The following two statements illustrate that string comparisons are case-insensitive unless one of the operands is a binary string: ECT ‘abe’ LIXE BINARY ‘ABC’; >o0 LIKE is allowed on numeric expressions! (This is a MySQL extension to the ANSI SQL nysq: 0 LIKE "18! Note: because MySQL uses the C escape syntax in strings (for example, \n), you must double any \ that you use in your LIKE strings. For example, to search for \n, specify it as \\n. To search for \, specify it as \\\\ (the backslashes are stripped once by the parser and another time when the pattern match is done, leaving a single backslash to be matched). hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 2261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari can be an extended regular expression. See Appendix F. Returns 1 if expr matches pat, returns 0, RLIKE is a synonym for REGEXP, provided for mSQL compatibility. Note: because MySQL uses the C escape syntax in strings (for example, \n), you must double any \ that you use in your REGEXP strings. As of MySQL Vers 3.23.4, REGEXP is case-insensitive for normal (not binary) strings: otherwis ion mysqi> SELECT 'Monty!' REGEXP 'mty$3"s *Monty!* ree ‘new*\n#Line! REGEXP ‘new\\*.\\*Line'; REGEXP and RLIKE use the current character set (ISO-8859-1 Latin1 by default) when deciding the type of a character. expr NOT REGEXP pat , expr NOT RLIKE pat Same as NOT (expr REGEXP pat). STRCMP(exprl,expr2) STRCMP() returns 0 if the strings are the same, -1 if the first argument is smaller than the second according to the current sort order, and 1 otherwise: mysqi> nysq: mysql> $ MATCH (col1,col2,...) AGAINST (expr) , MATCH (coll ,col2,...) AGAINST (expr IN BOOLEAN MODE) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Case sensitivity BINARY The BINARY operator casts the string following it to a binary string. This is an easy way to force a column comparison to be case-sensitive even if the column isn't defined as BINARY or BLOB: mysql> SELECT "a" = "A"; mysqi> SELECT BINARY "a" = "A"; BINARY string is shorthand for CAST(string AS BINARY). See Section 6.3.5. BINARY was introduced in MySQL Version 3.23.0. Note that in some context MySQL will not be able to use the index efficiently when you cast an indexed column to BINARY. Ifyou want to compare a blob case-insensitively you can always convert the blob to uppercase before doing the comparison: "AY LIKE UPPER (blob_col) FROM table_name; We plan to soon introduce casting between different character sets to make string comparison even more flexible. Numeric Functions Arithmetic operations The usual arithmetic operators are available. Note that in the case of -, +, and *, the result is calculated with BIGINT (64-bit) precision if both arguments are integers! If one of the arguments, hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 24161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysqi> SELECT 3+5; >8 Subtraction: 98509481984*18014398509481984.0; 658426726783156020576256.0 014398509481984; ‘The result of the last expression is incorrect because the result of the integer multiplication exceeds the 64-bit range of BIGINT calculations. Division: —> 0.60 Division by zero produces a NULL result: mysql> o2/a-1); hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650Vch06s03.ntml 25161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ‘All mathematical functions return NUL in case of an error. Unary minus. Changes the sign of the argument: Note that if this operator is used with a BIGINT, the return value is a BIGINT! This means that you should avoid using - on integers that may have the value of -2°63! ABS(X) Returns the absolute value of X: mysql> TABS (2); mysql> ‘This function is safe to use with BIGINT values. SIGN(X) Returns th gn of the argument as -1, 0, or 1, depending on whether X is negative, zero, or positive: mysqi> SELECT SIGN (32); “1 mysql> (os mysql> T SIGN (234) ; MOD(N.M), % hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 26161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari This function is safe to use with BIGINT values. FLOOR(X) Returns the largest integer value not greater than X: mysqi> SELECT FLOOR (1.23); RCT FLOOR(-1.23)7 > -2 Note that the return value is converted to a BIGINT! CEILING(X) Returns the smallest integer value not less than X: Note that the return value is converted to a BIGINT! ROUND(X) Returns the argument X, rounded to the nearest integer: mysql> SELECT ROUND (-1.23)7 “1 mysql> ROUND (-1.58); ECT ROUND (1.58); >2 mysql> hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ROUND(X,D) Returns the argument X, rounded to a number with D decimals. If D is 0, the result will have no decimal point or fractional part: mysql> SELECT ROUND(1.298, 1): mysql> SELECT ROUND(1.298, 0); EXP(X) Returns the value of e (the base of natural logarithms) raised to the power of X: mysql> SEURCT RXP (2); > 7.389056 LOG) Returns the natural logarithm of mysq: mysql> SELECT > NULL Ifyou want the log of a number X to some arbitary base B, use the formula LOG(XV/LOG®). LOG10(X) Returns the base-10 logarithm of X: > SELECT hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650%ct06s03.ntml 20461 svs0r2018 fey; t ERG Safari Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] Returns the value of X raised to the power of Y: SQRT(X) Returns the non-negative square root of X: mysql> BCL SORT (4); mysql> SELECT SORT (20); > 4.472136 PIO) Returns the value of PI. The default shown number of decimals is 5, but MySQL. internally uses the full double precision for PI. nysq> BIC)? => 3.141893 mysqi> SELECT PI( }+0,0000000000 > 3,141592653589793116 cosy) Returns the cosine of X, where X is given in radians: mysql> SELECT Cos(PT( }) -1. 000000 SIN(X) Returns the sine of X, where X is given in radians: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 20161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysqi> SELECT TAN(PI( ) +1); ACOS(X) Returns the arc cosine of X—that is, the value whose cosine is X. Returns NULL if X is not in the range -1 to 1: > 1.570796 ASIN() Returns the arc sine of X—that is, the value whose sine is X. Returns NULL if X is not in the range -1 to 1: mysql> ASIN (0.2); => 0.201358 mysql> SELECT ASIN(' £00" => 0.000000 ATAN(X) Returns the arc tangent of X—that is, the value whose tangent is X: ATAN (2); 07149 ATAN(-2) 7 107149 ATAN(Y,X) , ATAN2(Y,X) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 0161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari nysq: COT(X) Returns the cotangent of X: RAND() , RAND(N) Returns a random floating-point value in the range 0 to 1.0. If an integer argument N is specified, it is used as the seed value: mysql> SELECT RAND( ) => 0.9233482386203 mysql> SELECT RAND (20); > 0.1588826125104 RAND (20) ; 322612: mysql RAND( ); —> 0.63: mysqi> SELECT RAND( )+ > 0.70100469486 You can’t use a column with RAND() values in an ORDER BY clause because ORDER BY would evaluate the column multiple times. In MySQL Version 3.23, you can, however, do SELECT * FROM table_name ORDER BY RAND(). ‘This is useful to get a random sample of a set SELECT * FROM table1,table2 WHERE, AND e SELECT LEAST (2,0); mysql> SELECT LEAST (34.0,3.0,5.0,767.0) -> 3.0 mysql> SELECT LEAST("B","A","C") ; In MySQL versions prior to Version 3.22.5, you can use MIN() instead of LEAST. GREAT X,Y Returns the largest (maximum-valued) argument. The arguments are compared using the same rules as for LEAST: mysqi> SELECT GREATEST (2,0) ADEST (34.0,3.0,5.0,767.0); mysql> hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG RADIANS(X) Returns the argument X, converted from degrees to radians: mysql> RADIANS (90) 5 796 TRUNCATE(X,D) Returt decimal point or fractional part: s the number X, truncated to D decimals. If D is 0, the result will have no mysql> SELECT TRUNCATE (1,223,107 > 1.2 nysq: ‘TRUNCATE (1.999, 1)7 LECT TRUNCATE >. mysq: 999, 0); Note that as decimal numbers are normally not stored as exact numbers in computers, but as double values, you may be fooled by the following result: mysql> SELECT TRUNCATE ( 027 28*100,0); This happens because 10.28 is actually stored as something like 10.2799999999999999. Date and Time Functions See Section 6.2.2, for a description of the range of values each type has and the valid formats in which date and time values may be specified. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml aa61 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari DAYOFWEEK (date) Returns the weekday index for date (1 = Sunday, 2 = Monday, the ODBC standard: = Saturday). These index values correspond to WEEKDAY (date) Returns the weekday index for date (0 = Monday, 1 = Tuesday, ... 6 = Sunday): mysql> mysql> SELECT >2 DAYOFMONTH (date) Returns the day of the month for date, in the range I to 31: mysqi> SELECT DAYOFMONTH ('1998-02-03") >3 DAYOFYEAR(date) Returns the day of the year for date, in the range 1 to 366: mysql> SELECT DAYOFYEAR('1998-02-03") ; > 34 MONTH (date) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 34161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Returns the name of the weekday for date: mysql> SELECT DAYNAME ("1 —> "Thursday! MONTHNAME (date) Returns the name of the month for date: MONTHNAME ("1998-02-| LE > 'Pebruary! mysq2> QUARTER (date) Returns the quarter of the year for date, in the range 1 to 4: mysqi> SELECT QUARTER ("98-04-01"); >2 WEEK (date) , WEEK (date,first) With a single argument, returns the week for date, in the range 0 to 53 (yes, there may e the beginnings of a week 53), for locations where Sunday is the first day of the week. The two-argument form of WEEK( allows you to specify whether the week starts on Sunday or Monday. The week starts on Sunday if the second argument is 0, on Monday if the second argument is 1: mysql> SELECT WEEK (*1998-02-20'1; mysql> SELECT WEEK (*1998-02. WEEK (1998-02-20', 1); WEEK (11998-12-31', 1); hps:twawsafarbooksontine.con/ibraryviewimysqhreference-manval’0596002650Vct06s03.ntml 3661 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari YEARWE) eK(date), YEARWEEK (date,first) Returns year and week for a date. The second arguments works exactly like the second argument to WEEK(). Note that the year may be different from the year in the date argument for the first and the last week of the year: RWEEK (1987-01-01); 198653 HOUR(time) Returns the hour for time, in the range 0 to 23: MINUTE(time) Returns the minute for time, in the range 0 to 59: mysql> T MINUTE (' 98~( SECOND(time) Returns the second for time, in the range 0 to $9: mysql> PERIOD_ADD(P,N) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 36161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari > 199803 PERIOD_DIFF(P1,P2) Returns the number of months between periods P1 and P2. P1 and P2 should be in the format YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values: DIFF (9802, 199703) ; DATE_ADD(date, INTERVAL expr type) , DATE_SUB(date,INTERVAL expr type) , ADDDATE(date,INTERVAL expr type) , SUBDATE(date, INTERVAL expr type) ‘These functions perform date arithmetic. They are new for MySQL Version 3.22. ADDDATE() and SUBDATE( ) are synonyms for DATE_ADD() and DATE_SUB(). In MySQL Version 3.23, you can use + and - instead of DATE_ADD( ) and DATE_SUB() if the expression on the right side is a date or datetime column. (See example below.) date is a DATETIME or DATE value specifying the starting date. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a - for negative interv expression should be interpreted. . type is a keyword indicating how the The related function EXTRACT (type FROM date) returns the ‘type’ interval from the date. The following table shows how the type and expr arguments are related: type value Expected expr format hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml art t0r2078 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari MINUTE ‘MINUTES HOUR HOURS DAY DAYS MONTH MONTHS YEAR YEARS MINUTE_SECOND "MINUTES:SECONDS" HOUR_MINUTE “HOURS:MINUTES" DAY_HOUR "DAYS HOURS” YEAR_MONTH "YEARS-MONTHS" HOUR_SE! “HOURS:MINUTES:SECONDS" hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 61 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari DAY_SECOND "DAYS HOURS:MINUTES:SECONDS" MySQL allows any punctuation delimiter in the expr format. Those shown in the table are the suggested delimiters. If the date argument is a DATE value and your calculations involve only YEAR, MONTH, and DAY parts (that is, no time parts), the IME value: result is a DATE value. Otherwise, the result is a DAT mysql> SELECT "1997-12-31 23: 159" + INTERVAL 1 SECOND; 00:00 DAY + "1997-: 2 "1998-01 1997-12-31 2: ECT DATS_ADD ("1997-12-31 23:59 INTERVAL 1 SECOND); > 1998-01-01 90:00 mysql> SELECT DATE ADD("1997-12-31 23:59:59) z INTE > 1998-01-01 23:59:59 ECT DATE_ADD("1 INTERVAL "1:1" 01 00:01 ECT DATE_SUB("1998-01-01 0 VAL 1 DAY); 12-31 23:59 98 > INTERVAL 22:58:59 mysqi> SELECT DATE_ADD ("1998-01-01 > INTERVAL > 1997-12-30 14:00 mysql> SELECT DATS _SUB("1998-01-02", INTERVAL 31 DAY); > 1997-12-02 If you specify an interval value that is too short (does not include all the interval parts that would be expected from the type keyword), MySQL assumes you have left out the leftmost parts of the interval value. For example, if you specify a type of DAY_SECOND, the value of expr is expected to have days, hours, minutes, and seconds parts. If you specify a value like "1:10", MySQL assumes that the days and hours parts are missing hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 3061 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari part, the date value will be automatically converted to a datetime value: mysqi> SELECT DATE_ADD("1999-01-01", INTERVAL 1 DAY) > 1999-01 T DAT; > 1999-01-0: mysql> ("1998-01-01", Ifyou use really incorrect dates, the result is NULL. If you add MONTH, YEAR_MONTH, or YEAR and the resulting date has a day that is larger than the maximum day for the new month, the day is adjusted to the maximum days in the new month: mysq2> T DATE._Al 1998-02-28 (91998-01-30", INTERVAL 1 Note from the preceding example that the word INTERVAL and the type keyword are not case-sensitive. EXTRACT(type FROM date) The EXTRACT( ) function uses the same kinds of interval type specifiers as DATE_ADD() or DATE_SUB(), but extracts parts from the date rather than performing date arithmetic: TO_DAYS(date) Given a date date, returns a daynumber (the number of days since year 0): hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 40161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Gregorian calendar (1582) because it doesn’t take into 2 when the calendar was changed. ‘count the days that were lost FROM_DAYS(N) Given a daynumber N, returns a DATE value: AYS (729669) 7 FROM_DAYS() is not intended for use with values that precede the advent of the Gregorian calendar (1582) because it doesn't take into account the days that were lost when the calendar was changed. DATE_FORMAT(date,format) Formats the date value according to the format ring. The following s used in the format string: Specifier Description %M. Month name (January..December) “Ww Weekday name (Sunday..Saturday) “> Day of the month with English suffix (Ist, 2nd, 3rd, ete.) %Y Year, numeric, 4 digits hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml ave t0r2078 fey; t ERG Safari Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] %X Year for the week where Sunday is the first day of the week, numeric, 4 digits, used with '%6V" %x Year for the week, where Monday is the first day of the week, numeric, 4 digits, used with "%6v’ %a Abbreviated weekday name (Sun..Sat) %d Day of the month, numeric (00.31) %e Day of the month, numeric (0..31) %m Month, numeric (01..12) %e Month, numeric (1..12) %~b Abbreviated month name (Jan..Dec) %j Day of year (001..366) %H Hour (00..23) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 4261 t0r2078 fey; t ERG Safari %k Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] Hour (0..23) %h Hour (01..12) %l Hour (01.12) %l Hour (1..12) %i Minutes, numeric (00..59) %r Time, 12-hour (hh:mm:ss [AP]M) %T Time, 24-hour (hh:mm:ss) %S Seconds (00..59) %s Seconds (00.59) op AM or PM hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4361 svs0r2018 fey; t ERG Safari Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] %U Week (0.53), where Sunday is the first day of the week %u Week (0..53), where Monday is the first day of the week %~Y Week (1..53), where Sunday is the first day of the week; used with “vox %y Week (1.83), where Monday is the first day of the week; used with ‘She %% Aliteral % All other characters are just copied to the mysqi> esult without interpretation: 3200", "aM aM BY); ECT DATE_FORMAT("1999- > "1998 As of MySQL Version 3.23, the % character is required before format specifier characters. In earlier versions of MySQL, % was optional. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4461 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Returns today’s date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending on whether the function is used in a string or numeric context: mysqi> SELECT CURDATE( ); => 1197-12-15" mysql> CURDATE( ) + 0; CURTIME() , CURRENT_TIME Returns the current time as a value in ‘HH:MM:SS' or HHMMS whether the function is used in a string or numeric context: format, depending on NOW(), SYSDATE() , CURRENT_TIMESTAMP Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:ss' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context: UNIX_TIMESTAMP() , UNIX_TIMESTAMP(date) If called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00" GMT) as an unsigned integer. If UNEX_TIMESTAMP( is called with a date argument, it returns the value of the argument ce 1970-01-01 00:00:00" econds hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4861 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari > 875996580 When UNIX_TIMESTAMP is used on a TIMESTAMP column, the function will return, the internal timestamp value direetly, with no implicit “string-to-unix-time- stamp” conversion. If you give UNIX_TIMESTAMP() a wrong or out-of-range date, it will return 0. Ifyou want to subtract UNIX_TIMESTAMP( ) columns, you may want to cast the result to signed integers. See Section 6.3.5. FROM_U IXTIME(unix_timestamp) Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD HH:MM$S' or YYYYMMDDHHMMSS format, depending on whether the function is used in a string or numeric context: mysql> T FROM_UNIXTIME (8759) => 1197-10-04 22:23:00" mysql> SELECT FROM_UNI (87 ho 997100422230 FROM_UNIXTIME(unix_timestamp,format) Returns a string representation of the Unix timestamp, formatted according to the format string. format may contain the same specifiers as those listed in the entry for the DATE_FORMAT( ) function: mysqi> SELECT F 1_UNIXT (ONIX_TIMESTAME( ), "SY SD SM Sh:8isss Sx"); > 11997 23rd December 03:43:30 1997" SEC_TO_TIME(seconds) Returns the seconds argument, converted to hours, minutes, and seconds, as a value in 'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or numeric context: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4661 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari Returns the time argument, converted to seconds: mysql> SELECT TIME_TO "22:23:00")3 —> a0! LE > 2378 mysql> § ¥00:39:38")7 Cast Functions ‘The syntax of the CAST function is: CAST (expression AS type) or CONVERT (expression, type) Where type is one of: © BINARY °D. © DATETIME © SIGNED {INTEGER} © TIME © UNSIGNED {INTEGER} CAS [() is ANSI SQL99 syntax and CONVER r() is ODBC syntax. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml art svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG To cast a string to a numeric value, you don’t normally have to do anything; just use the string value as if it were a number: mysql> SELECT 1471"; >2 MySQL supports arithmetic with both signed and unsigned 64-bit values. If you are using numerical operations (like +) and one of the operands is unsigned integer, the result will be unsigned. You can override this by using the SIGNED and UNSIGNED cast operators, which will cast the operation to a signed or unsigned 64-bit integer, respectively. cast ( > 184467440 Note that if either operation is a floating-point value (in this context DECIMAL() is regarded as a floating-point value), the result will be a floating-point value and is not affected by the preceding rule, UNSTGNED) Ifyou are using a string in an arithmetic operation, this is converted to a floating-point number. The CAST() and CONVERT() functions were added in MySQL 4.0.2. The handing of unsigned values was changed in MySQL 4.0 to be able to support BIGINT values properly. If you have some code that you want to run in both MySQL 4.0 and 3.23 (in which case you probably can’t use the CAST function), you can use the following trick to get a signed result when subtracting two unsigned integer columns: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 4861 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari QL 4.0, you can use the —sqr-mode: ‘ophon when starting, vs mysql. Note, however, that as long as you use this, you will not be able to make efficient use of the UNSIGNED BIGINT column type. Other Functions Bit functions MySQL uses BIGINT (64-bit) arithmetic for bit operations, so these operators have a maximum. range of 64 bits: Bitwise OR: mysql> 8 The result is an unsigned 64-bit integer. Bitwise AND: ECT 29 & 15; > 13 The result is an unsigned 64-bit integer. << Shifts a longlong (BIGINT) number to the left: mysql> SELECT 1 << 2; hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 49V61 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG The result is an unsigned 64-bit integer. Invert all bits: The result is an unsigned 64-bit integer. BIT_COUNT(N) Returns the number of bits that are set in the argument N: mysqi> SELECT BIT_COUNT(29) 7 4 Miscellaneous functions DATABASE() Returns the current datab: name: mysq: If there is no current database, DATABA sE() returns the empty string, USER() , SYSTEM_USER() , SESSION_USER() Returns the current MySQL username: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 50161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari mysql> SELECT SUBSTRING INDEX(USER( ),"@",1); PASSWORD(str) Calculates a password string from the plaintext password str. This is the function that is used for encrypting MySQL passwords for storage in the Password column of the user grant table: mysql> PASSWORD( ) encryption is non-reversible. PASSWORD() does not perform password encryption in the same way that Unix passwords are encrypted. You should not assume that if your Unix password and your MySQL password are the same, PASSWORD( ) will result in the same encrypted value tored in the Unix password file. See ENCRYPT( ). ENCRYPT(str[,salt}) Encrypt str using the Unix erypt( ) system call. The salt argument should be a string with two characters (as of MySQL Version 3.22.16, salt may be longer than two characters mysql> T("nello") ; /aR300! If erypt() is not available on your system, ENCRYPT( ) always returns NULL. ENCRYPT() ignores all but the first 8 characters of str, at least on some systems. This fem call, will be determined by the behavior of the underlying erypt() hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml S161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari DECODE(crypt_str,pass_str) Deserypts the encrypted string erypt_str using pass_str as the password. erypt_str should be a string returned from ENCODE(). MDS(string) Calculates an MDs checksum for the string. Value is returned as a 32 long hex number that may, for example, be used as a hash ke} mysql> SELECT MDS ("testing") ; 5d54£b22b8ed95575! > ‘ae2blfeasi! This is an “RSA Data Security, Inc. MDs Message-Digest Algorithm”. DES_ENCRYPT(string_to_encrypt [, (key_number | key_string) | ) Encrypts the string with the given key using the DES algorithm, which provides strong encryption. Note that this function only works if you have configured MySQL with SSL support. Section 4.3.8. The encryption key to use is chosen the following way: Argument Description Only one argument ‘The first key from des-key-file is used. Key number ‘The given key (0-9) from the des-key-file is used. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml e261 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari The return string will be a binary string where the first character will be CHAR(128 | key_number). The 128 is added to make it ea tring key, key_number will be 127. jer to recognize an encrypted key. If you use On error, this function returns NULL. The string length for the result will be new_length= org_length + (8-(org_length % 8)+1. The des-key-file has the following format: key_number des_key_s! key number des_key str: Each key_number must be a number in the range from 0 to 9. Lines in the file may be in any order. des_key_string is the string that will be used to encrypt the message. Between the number and the key there should be at least one space. The first key is the default y argument to DES_ENCRYPT( ). key that will be used if you don’t specify any k ‘You can tell MySQL to read new key values from the key file with the FLUSH. DES_KEY_FILE command. This requires the Reload_priv privilege. One benefit of having a set of default keys is that it gives applications a way to check for the existence of encrypted column values, without giving the end user the right to decrypt those values. CT customer add table WHERS ess FROM custom mysq: crypte: DES_ENCRY?T ("credit_card_nut DES_DECRYPT(string_to_decrypt |, key_string]) Deerypts a string encrypted with DES_ENCRYPT(). hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml 5161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari to work the user must have the process privilege. Ifyou pass this function a key_string argument, that string is used as the key for decrypting the message. If the string_to_decrypt doesn’t look like an encrypted string, MySQL will return the given string_to_decrypt. On error, this function returns NULL. LAST_INSERT_ID((expr]) Returns the last automatically generated value that was inserted into an AUTO_INCREMENT column, See Section 8.4.3.126. The last ID that was generated is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0). If you insert many rows at the same time with an insert statement, LAST_INSERT_ID( ) returns the value for the first inserted row. The reason for this is so that you can easily reproduce the same INSERT statement against some other server. If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is. returned by the function, is set as the next value to be returned by LAST_INSERT_ID( ), and is used as the next AUTO_INCREMENT value. This can be used to simulate sequences. First create the table: TABLE sequence (id INT NOT NULL); fe VALUES (0); hips: safarbooksontine.com/ibraryviewimysqhreference-manual’0596002650%ct06s03.ntml 54161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ‘ou can generate sequences without calling LAST TS "IDC, Dut the ulinty o1 using the function this way is that the ID value is maintained in the server as the last automatically generated value. You can retrieve the new ID as you would read any normal AUTO_INCREMENT value in MySQL. For example, LAST_INSERT_ID() (without an argument) will return the new ID, The C API function mysql_insert_id() can also be used to get the value. Note that as mysql_insert_id( ) is only updated after INSERT and UPDATE statements, you can’t use this function to retrieve the value for LAST_INSERT_ID(expr) after executing other SQL statements like SELECT or SET. FORMAT(X,D) Formats the number X to a format like '#,###,###.##, rounded to D decimals. If D is 0, the result will have no decimal point or fractional part: 23456, 4); > 112,332 mysql> SELECT FORMAT (12332.2,00; —> 112,332" VERSION() Returns a string indicating the MySQL server version: mysql> SELECT VERSTON( ); Note that if your version ends with -log this means that logging is enabled. CONNECTION_ID() Returns the connection id (thread_id) for the connection. Every connection has its own unique id: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 55161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari seconds. Returns 1 if the lock was obtained successfully, 0 if the attempt timed out, or NULL if an error occurred (such as running out of memory or the thread was killed with mysqladmin kill). A lock is released when you execute RELEASE_LOCK(), execute a new GET_LOCK(), or the thread terminates. This function can be used to implement application locks or to simulate record locks. It blocks requests by other clients for locks with the same name; clients that agree on a given lock string name can use the string to perform cooperative advisory locking: B_LOCK ("10¢k2") ; ASF_LOCK ("lock1") + Note that the second RELEASE_LOCK( ) call returns NULL because the lock "Iocki" was automatically released by the second GET_LOCK() call. RELEASE_LOCK(str) Releases the lock named by the string str that was obtained with GET_LOCK(). Returns 1 if the lock was released, 0 if the lock wasn't locked by this thread (in which case the lock is not released), and NULL if the named lock didn’t exist. The lock will not exist if it was never obtained by a call to GET_LOCK() or if it already has been released. The DO statement is convenient to use with RELEASE_LOCK( ). See Section 6.4.10. BENCHMARK (count,expr) The BENCHMARK( ) function executes the expression expr repeatedly count times. It may be used to time how fast MySQL processes the expression. The result value is always 0. The intended use is in the mysql client, which reports query execution times: hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 56161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari ‘The time reported is the elapsed time on the client end, not the CPU time on the server end. It may be advisable to execute BENCHMARK( ) several times, and interpret the result with regard to how heavily loaded the server machine is. INET_NTOA(expr) Given a numeric network address (4 or 8 bytes), returns the dotted-quad representation of the address as a string: aysa! 520061480) ; 224.401 INET_ATON(expr) Given the dotted-quad representation of a network address as a string, returns an integer that represents the numeric value of the address. Addresses may be 4- or 8-byte addresses: nysq: ‘The generated number is always in network byte order; for example, the previous number is calculated as 209*25643 + 207*2562 + 224*256 +40. MASTER_POS_WAIT(og_name, log_pos) Blocks until the slave reaches the specified position in the master log during replication. If master information is not initialised, returns NULL. If the slave is not running, will block and wait until itis started and goes to or passes the specified position. If the slave is already past the specified position, returns immediately. The return value is the number of log events it had to wait to get to the specified position, or NULL in case of error. Useful for control of master-slave synchronisation, but was originally written to facilitate replication testing. hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml srt svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari WHERE 3d > 100 LIMIT. 107 mysql> SELECT FOUND_ROWS( 7 The second SELECT will return a number indicating how many rows the first SELECT would have returned had it been written without the LIMIT clause. Note that if you are using SELECT SQL_CALC_FOUND_ROWS ... MySQL has to calculate all rows in the result set. However, this is faster than if you did not use LIMIT, as the result set need not be sent to the client. Functions for Use with GROUP BY Clauses If you use a group function in a statement containing no GROUP BY clause, it is equivalent to grouping on all rows. COUNT¢expr) Returns a count of the number of non-NULL values in the rows retrieved by a SELECT statement: > GROUP BY student_name; COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether they contain NULL values. COUNT(*) is optimised to return very quickly if the SELECT retrieves from one table, no other columns are retrieved, and there is no WHERE clause. For example: ECT COUNT(*) FROM student; COUNTISTINCT expr[expr...]) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650Vch06s03.niml sei61 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari y giving a st of expres concatenation of all expressions inside CODE(DISTINCT ...). AVG(expr) Returns the average value of expr: mysqi> MIN(expr) , MAX(expr) Returns the minimum or maximum value of expr. MIN() and MAX() may take a string argument; in such cases they return the minimum or maximum string value. See Section 5.4.3 ), MAK (test_score) GROUP BY student_name; SUM(expr) Returns the sum of expr. Note that if the return set has no rows, it returns NULL! STD(expr) , STDDEV(expr) Returns the standard deviation of expr. This is an extension to ANSI SQL. The STDDEV() form of this function is provided for Oracle compatibility. BIT_OR(expr) Returns the bitwise OR of all bits in expr. The calculation is performed with 64-bit (BIGINT) precision. BIT_AND(expr) hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 50161 svs0r2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fey; t ERG Safari items, For example, you don’t need to group on customer.name in the following query: mysql> SELECT order. custid, customer name, MAX (payments) > FROM order, customer WHERE order.custid = customer.custid GROUP BY order.custid; In ANSI SQL, you would have to add customer.name to the GROUP BY clause. In MySQL, the name is redundant if you don’t run in ANSI mode. Don’t use this feature if the columns you omit from the GROUP BY part aren't unique in the group! You will get unpredictable results. In some cases, you can use MIN() and MAX() to obtain a specific column value even if it isn’t unique. The following gives the value of column from the row containing the smallest value in the sort column: SUBSTR (MIN (CONCAT(RPAD (sort, 6," '),column)),7) See Section 3.5.4. Note that if you are using MySQL Version 3.22 (or earlier) or if you are trying to follow ANSI SQL, you can't use expressions in GROUP BY or ORDER BY clauses. You can work around this limitation by using an alias for the expres mysql> SELECT id, FLOOR(value/100) AS val FROM tbl_name UP BY Sa, va DER BY val; In MySQL Version 3.23 you can do: mysql> SELECT id, FLOOR (value/100) FROM IR BY RAND( ); hips: safarbooksontine.com/ibraryviewimysqhreference-manual0596002650/ct06s03.ntml 60161 sor2018 Functions for Use in SELEGT and WHERE Clauses - MySQL Reference Manual [Book] fess STEN Ad Safari credit card required Corry acts ren) rer cert ials Leelee) Queue App eli) Blog Contact Careers

You might also like