MySQL 5.7 String Functions

Post on 18-Feb-2017

129 views 1 download

Transcript of MySQL 5.7 String Functions

MySQL 5.7 String FunctionsA complete presentation of MySQL 5.7 String Functions with explanation, syntax and examples.

Francesco Marinofrancesco.ingmarino@gmail.com

String Operators

ASCII(str)

SELECT ASCII ('4');Output: 54

SELECT ASCII (4);Output: 54

SELECT ASCII ('ab');Output: 97

Returns the numeric value of the leftmost character of the string str. Returns 0 if str is an empty string, NULL if str is NULL

BIN(N)

SELECT BIN ('12');Output: 1100

SELECT BIN (5);Output: 101

Returns a string representation of the binary value of N, where N is of BIGINT type number. Returns NULL if N is NULL.

BIT_LENGHT(N)

SELECT BIT_LENGTH('text');Output: 32

SELECT BIT_LENGTH('error');Output: 40

Returns the length of the string str in bits.

CHAR(N,... [USING charset_name])

SELECT CHAR(77,121,83,81,76);Output: MySQL

SELECT CHAR(77,121,83,81,'76' USING UTF8);Output: MySQL

Hint: If MySQL Workbench get back a BLOB icon, Go to Edit > Preferences > SQL Editor > SQL Execution > check Treat BINARY/VARBINARY as nonbinary character string > Restart Workbench

Interprets each argument N as an integer and returns a string consisting of the characters given by the code values of those integers. NULL values are skipped.

CHAR_LENGTH(str)

SELECT CHAR_LENGTH('test');Output: 4

SELECT CHAR_LENGTH('test word');Output: 9

Returns the length of the string str, measured in characters. A multibyte character counts as a single character.

CHARACTER_LENGTH(str)

SELECT CHARACTER_LENGTH('test');Output: 4

SELECT CHARACTER_LENGTH('test word');Output: 9

Is a synonym for CHAR_LENGTH(str).

CONCAT(str1,[str2,...,strN])

SELECT CONCAT('a');Output: a

SELECT CONCAT('a','b','c',1); Output: abc1

SELECT CONCAT('a', NULL, 3);Output: NULL

Returns the string that results from concatenating the arguments. If all arguments are nonbinary strings, the result is a nonbinary string; if include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent nonbinary string form.

CONCAT_WS(separator,str1[,str2,...,strN])

SELECT CONCAT_WS(';','String1','String2','Last Name');Output: String1;String2;Last Name

SELECT CONCAT_WS('&','a','&','Co'); Output: a&2&Co

Stands for Concatenate With Separator. The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string. If the separator is NULL, the result is NULL.

ELT(N,str1[,str2,...,strN])

SELECT ELT(1, 'test', 'word', 'string', 'char');Output: test

SELECT ELT(4, 'test', 'word', 'string', 'char');Output: char

SELECT ELT(6, 'test', 'word', 'string', 'char');Output: NULL

Returns the Nth element of the list of strings: str1 if N = 1, str2 if N = 2, and so on. Returns NULL if N is less than 1 or greater than the number of arguments.

EXPORT_SET(bits,on,off[,separator[,number_of_bits]])

SELECT EXPORT_SET(5,'Y','N',',',4);Output: Y,N,Y,N

SELECT EXPORT_SET(7,'Y','N',',',4);Output: Y,Y,Y,N

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. The number of bits examined is given by number_of_bits, which has a default of 64 if not specified.

FIELD(str,str1,[str2,...,strN])

SELECT FIELD ('string', 'test', 'word', 'string', 'char');Output: 3

SELECT FIELD (7,5,2,3,9,7,7);Output: 5

SELECT FIELD (1,5,2,3,9,7,7);Output: 0

Returns the index (position) of str in the str1, str2, ..., strN list. Returns 0 if str is not found.

FIND_IN_SET(str,strlist)

SELECT FIND_IN_SET ('string', 'test,word,string,char');Output: 3

SELECT FIND_IN_SET ('strength', 'test,word,string,char');Output: 0

SELECT FIND_IN_SET (7,'5,2,3,9,7,7');Output: 5

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by “,” characters. Returns 0 if str is not in strlist or if strlist is the empty string.

FORMAT(X,D[,locale])

SELECT FORMAT(12332.123456, 4);Output: 1,332.1235

SELECT FORMAT(1332.123456, 0);Output: 1,332

SELECT FORMAT(1332.123456, 3,'it_IT');Output: 1332,123

Formats the number X to a format like '#,###,###.##', rounded to D decimal places, and returns the result as a string. If D is 0, the result has no decimal point or fractional part. Locale is optional and used for the result number's decimal point, thousands separator, and grouping between separators.

FROM_BASE64(str)

SELECT TO_BASE64('abc'), FROM_BASE64(TO_BASE64('abc'));Output: JWJj,abc

Hint: If MySQL Workbench get back a BLOB icon for the FROM_BASE64 operator, Go to Edit > Preferences > SQL Editor > SQL Execution > check Treat BINARY/VARBINARY as nonbinary character string > Restart Workbench

Takes a string encoded with the base64 encoded rules used by TO_BASE64() and returns the decoded result as a binary string. The result is NULL if the argument is NULL or not a valid base-64 string.

HEX(str), HEX(N)

SELECT X'616263', HEX('abc'), UNHEX(HEX('abc'));Output: abc, 616263, abc

SELECT HEX(255), CONV(HEX(255),16,10);Output: FF, 255

For a string argument str, returns a hexadecimal string representation of str where each byte of each character in str is converted to two hexadecimal digits. The inverse operation is UNHEX(). For a numeric argument N, HEX() returns a hexadecimal string representation of the value of N treated as a longlong (BIGINT) number. The inverse operation is CONV().

INSERT(str,pos,len,newstr)

SELECT INSERT('Start', 3, 4, 'End');Output: StEnd

SELECT INSERT('Start', -1, 4, 'End');Output: Start

SELECT INSERT('Start', 2, 10, 'End');Output: SEnd

Returns the string str, with the substring beginning at position pos and len characters long replaced by the string newstr. Returns the original string if pos is not within the length of the string. Replaces the rest of the string from position pos if len is not within the length of the rest of the string. Returns NULL if any argument is NULL.

INSTR(str,substr)

SELECT INSTR ('Start', 'art');Output: 3

SELECT INSTR ('Start', 'ort');Output: 0

Returns the position of the first occurrence of substring substr in string str.

LCASE(str)

SELECT LCASE('START');Output: start

SELECT LCASE('STArt');Output: start

Is a synonym for LOWER(str)

LEFT(str,len)

SELECT LEFT('Start', 1);Output: S

SELECT LEFT('Start', 4);Output: Star

Returns the leftmost len characters from the string str, or NULL if any argument is NULL.

LENGTH(str)

SELECT LENGTH('Start');Output: 5

SELECT LENGTH('!Start ');Output: 7

Returns the length of the string str, measured in bytes. A multibyte character counts as multiple bytes. For a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

(NOT) LIKE pat [ESCAPE 'escape_char']

SELECT 'Start!' LIKE 'Start_';Output: 1

SELECT 'Start!' LIKE '%ta%t%';;Output: 1

SELECT 'Start!' NOT LIKE 'Start_';Output: 0

These are string comparison operators. Pattern matching using an SQL pattern. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL. Two wildcard can be used: % matches any number of characters, even zero characters; _ matches exactly one character. To specify a different escape character, use the ESCAPE clause.

LOAD_FILE(file_name)

SELECT LOAD_FILE('/tmp/myFile') WHERE id=1Output: Text correctly read

Reads the file and returns the file contents as a string. The file must be readable and its size less than max_allowed_packet bytes, located on the server host, you must specify the full path name to the file and have the FILE privilege. its. If the file does not exist or cannot be read, the function returns NULL.

LOCATE(substr,str), LOCATE(substr,str,pos)

SELECT LOCATE('al', 'Wallball');Output: 2

SELECT LOCATE('bat', 'Wallball');Output: 0

SELECT LOCATE('al', 'Wallball', 5);Output: 6

The first syntax returns the position of the first occurrence of substring substr in string str. The second syntax 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.

LOWER(str)

SELECT LOWER('START');Output: start

SELECT LOWER('STArt');Output: start

Returns the string str with all characters changed to lowercase according to the current character set mapping. The default is latin1 (cp1252 West European).

LPAD(str,len,padstr)

SELECT LPAD('Hi',4,'!!!');Output: !!Hi

SELECT LPAD('Hi',1,'!!!');Output: H

Returns the string str, left-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.

LTRIM(str)

SELECT LTRIM(' Start ');Output: Start

Returns the string str with leading space characters removed.

MAKE_SET(bits,str1[,str2,...,strN])

SELECT MAKE_SET(2,'a','b','c');Output: b

SELECT MAKE_SET(5,'a','b','c');Output: a,c

SELECT MAKE_SET(7,'a','b','c');Output: a,b,c

Returns a set value (a string containing substrings separated by “,” characters) consisting of the strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, and so on. NULL values in str1, str2, …, strN are not appended to the result.

MATCH (col1,col2,[...,colN]) AGAINST (expr [search_modifier])

SELECT * FROM filmWHERE MATCH (title,author)AGAINST ('database' IN NATURAL LANGUAGE MODE);Output:

MATCH() takes a comma-separated list that names the columns to be searched. AGAINST takes a string to search for, and an optional modifier that indicates what type of search to perform. The search string must be a string value that is constant during query evaluation. This rules out, for example, a table column because that can differ for each row.

Avatar Cameron

The Italian Job

Gray

MID(str,pos,len)

SELECT MID('Wonderwall',5);Output: erwall

SELECT MID('Wonderwall',5,2);Output: er

Is a synonym for SUBSTRING(str,pos,len).

OCT(N)

SELECT OCT(10);Output: 12

Returns a string representation of the octal value of N, where N is a longlong (BIGINT) number. This is equivalent to CONV(N,10,8). Returns NULL if N is NULL.

OCTET_LENGTH(str)

SELECT OCTET_LENGTH('Start');Output: 5

SELECT OCTET_LENGTH('!Start ');Output: 7

Returns the length of the string str, measured in bytes. A multibyte character counts as multiple bytes. For a string containing five 2-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH() returns 5.

ORD(str)

SELECT ORD('3');Output: 51

If the leftmost character of the string str is a multibyte character, returns the code for that character, calculated from the numeric values of its constituent bytes. If the leftmost character is not a multibyte character, returns the same value as the ASCII() function.

POSITION(substr IN str)

SELECT POSITION('al' IN 'Wallball');Output: 2

SELECT POSITION('bat' IN 'Wallball');Output: 0

Is a synonym for LOCATE(substr,str).

QUOTE(str)

SELECT QUOTE('Can\'t!');Output: 'Can\'t!'

SELECT QUOTE(NULL);Output: NULL

Quotes a string returned enclosed by single quotation marks and with each instance of backslash (“\”), single quote (“'”), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.

(NOT) REGEXP pat

SELECT 'banana' REGEXP '^ba'; (^: Match the beginning of a string.)Output: 1

SELECT 'banana' REGEXP '^na$'; ($: Match the end of a string.)Output: 0

Performs a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression, the syntax for which is discussed later in this section. Returns 1 if expr matches pat; otherwise it returns 0. If either expr or pat is NULL, the result is NULL.

REPEAT(str,count)

SELECT REPEAT('Test', 3);Output: TestTestTest

SELECT REPEAT('Test', -3);Output: ''

SELECT REPEAT('Test', NULL);Output: NULL

Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty string. Returns NULL if str or count are NULL.

REPLACE(str,from_str,to_str)

SELECT REPLACE('banana', 'n', 't');Output: batata

SELECT REPLACE('banana', 'N', 't');Output: banana

Returns the string str with all occurrences of the string from_str replaced by the string to_str. Performs a case-sensitive match when searching for from_str.

REVERSE(str)

SELECT REVERSE(12345);Output: 54321

SELECT REVERSE('abcd');Output: dcba

Returns the string str with the order of the characters reversed.

RIGHT(str,len)

SELECT RIGHT('Start', 1);Output: t

SELECT RIGHT('Start', 4);Output: tart

Returns the rightmost len characters from the string str, or NULL if any argument is NULL.

(NOT) RLIKE pat

SELECT 'banana' RLIKE '^ba'; (^: Match the beginning of a string.)Output: 1

SELECT 'banana' RLIKE '^na$'; ($: Match the end of a string.)Output: 0

Is a synonym for REGEXP pat.

RPAD(str,len,padstr)

SELECT RPAD('Hi',4,'!!!');Output: Hi!!

SELECT RPAD('Hi',6,'!!!');Output: Hi!!!!

Returns the string str, right-padded with the string padstr to a length of len characters. If str is longer than len, the return value is shortened to len characters.

RTRIM(str)

SELECT RTRIM('Start! ');Output: Start!

Returns the string str with trailing space characters removed.

SOUNDEX(str)

SELECT SOUNDEX('Test');Output: T230

SELECT SOUNDEX('Start!');Output: S363

Returns a soundex string from str. Two strings that sound almost the same should have identical soundex strings. A standard soundex string is four characters long, but the SOUNDEX() function returns an arbitrarily long string. All international alphabetic characters outside the A-Z range are treated as vowels.

expr1 SOUNDS LIKE expr2

SELECT ('Start!') SOUNDS LIKE('Test');Output: 0

SELECT ('Test') SOUNDS LIKE('Test');Output: 1

This the same as SOUNDEX(expr1) = SOUNDEX(expr2).

SPACE(N)

SELECT SPACE(5);Output: ' '

SELECT SPACE(-5);Output: ''

Returns a string consisting of N space characters.

STRCMP(expr1,expr2)

SELECT STRCMP('test', 'test1');Output: -1

SELECT STRCMP('test1', 'test');Output: 1

SELECT STRCMP('test', 'test');Output: 0

Returns 0 if expr1, expr2 are the same, -1 if the first argument is smaller than the second according to the current sort order, and 1 otherwise.

SUBSTR(str,pos), SUBSTR(str FROM pos), SUBSTR(str,pos,len), SUBSTR(str FROM pos FOR len)

SELECT SUBSTR('Wonderwall',5);Output: erwall

SELECT SUBSTR('Wonderwall',5,2);Output: er

SELECT SUBSTR('Wonderwall' FROM 3 FOR 4);Output: nder

Is a synonym for SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len).

SUBSTRING(str,pos), SUBSTRING(str FROM pos), SUBSTRING(str,pos,len), SUBSTRING(str FROM pos FOR len)

SELECT SUBSTRING('Wonderwall',5);Output: erwall

SELECT SUBSTRING('Wonderwall',5,2);Output: er

SELECT SUBSTRING('Wonderwall' FROM 3 FOR 4);Output: nder

Without a len argument return a substring from string str starting at position pos. With a len argument return a substring len characters long from string str, starting at position pos. The forms that use FROM are standard SQL syntax. If pos has a negative value, the beginning of the substring is pos characters from the end of the string, rather than the beginning.

SUBSTRING_INDEX(str,delim,count)

SELECT SUBSTRING_INDEX('www.testSubstringIndex.com', '.', 2);Output: www.testSubstringIndex

SELECT SUBSTRING_INDEX('www.testSubstringIndex.com', '.', -2);Output: testSubstringIndex.com

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. Performs a case-sensitive match when searching for delim.

TO_BASE64(str)

SELECT TO_BASE64('start'), FROM_BASE64(TO_BASE64('start'));Output: c3RhcnQ=, start

Converts the string argument to base-64 encoded form and returns the result as a character string with the connection character set and collation. If the argument is not a string, it is converted to a string before conversion takes place. The result is NULL if the argument is NULL. Base-64 encoded strings can be decoded using the FROM_BASE64() function.

TRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str), TRIM([remstr FROM] str)

SELECT TRIM(' start ');Output: start

SELECT TRIM(LEADING 'x' FROM 'xxxstartxxx');Output: startxxx

SELECT TRIM(TRAILING 'abc' FROM 'xxxstartabc');Output: xxxstart

Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiers BOTH, LEADING, or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are removed.

UCASE(str)

SELECT UCASE('start');Output: START

Is a synonym for UPPER(str).

UNHEX(str)

SELECT UNHEX('4D7953514C');Output: MySQL

SELECT UNHEX(HEX('string'));Output: string

SELECT UNHEX('HH');Output: NULL

For a string argument str, interprets each pair of characters in the argument as a hexadecimal number and converts it to the byte represented by the number. The return value is a binary string.

UPPER(str)

SELECT UPPER('start');Output: START

Returns the string str with all characters changed to uppercase according to the current character set mapping. The default is latin1 (cp1252 West European).

WEIGHT_STRING(str [AS {CHAR|BINARY}(N)] [LEVEL levels] [flags]) levels: N [ASC|DESC|REVERSE] [, N [ASC|DESC|REVERSE]] ...

SELECT HEX(WEIGHT_STRING(0x007fff LEVEL 1));Output: 007FFF

SELECT HEX(WEIGHT_STRING(0x007fff LEVEL 1 DESC REVERSE));Output: 0080FF

Returns the weight string for the input string. The return value is a binary string that represents the sorting and comparison value of the string.The input string, str, is a string expression. The LEVEL clause may be given to specify that the return value should contain weights for specific collation levels.