SQL InStr () and locate () string lookup function

Source: Internet
Author: User
Tags sql instr

INSTR (STR,SUBSTR)
Returns the first occurrence of a string of str neutron strings. This is the same as locate (), unless the order of the parameters is reversed.

The code is as follows Copy Code
mysql> SELECT INSTR (' Foobarbar ', ' Bar ');
-> 4
mysql> SELECT INSTR (' Xbar ', ' foobar ');
-> 0


LOCATE (SUBSTR,STR), LOCATE (Substr,str,pos)
The first syntax returns the first occurrence of the string substr of the str neutron string. The second syntax returns the first occurrence of the string str neutron string substr, starting at the Pos point. If SUBSTR is not in Str, the return value is 0.

The code is as follows Copy Code
mysql> SELECT LOCATE (' Bar ', ' Foobarbar ');
-> 4
mysql> SELECT LOCATE (' Xbar ', ' foobar ');
-> 0
mysql> SELECT LOCATE (' Bar ', ' Foobarbar ', 5);
-> 7

This function supports multibyte characters and is case-sensitive only if at least one argument is a binary string.


POSITION (substr in str)
Returns the position of the substring substr the first occurrence in string str. If substring substr does not exist in STR, the return value is 0:

The code is as follows Copy Code
mysql> SELECT POSITION (' Bar ', ' Foobarbar ');
-> 4
mysql> SELECT POSITION (' Xbar ', ' foobar ');
-> 0

Efficiency test

The code is as follows Copy Code

SELECT * from ' O_soft ' WHERE LOCATE (' d200 ', Tid2) >0

MySQL returned a query result that is empty (that is, 0 rows). (Query takes 0.0050 seconds)

The code is as follows Copy Code

SELECT * from ' O_soft ' WHERE INSTR (' d200 ', Tid2) >0

MySQL returned a query result that is empty (that is, 0 rows). (Query takes 0.0009 seconds)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.