SQL instr () and LOCATE () string lookup Functions

Source: Internet
Author: User
Tags sql instr

Because the subcategories of a website today use the SQL instr () and LOCATE () string operation functions, let's take a note and put it down. If you need them, please refer to them.

INSTR (str, substr)
Returns the first occurrence position of the str substring. This is the same as the double parameter form of LOCATE () unless the order of parameters is reversed.

The Code is as follows: Copy code
Mysql> select instr ('foobar', 'bar ');
-> 4
Mysql> select instr ('xbar', 'foobar ');
-> 0


LOCATE (substr, str), LOCATE (substr, str, pos)
The first syntax returns the first occurrence position of the substring substr. The second syntax returns the first occurrence position of the substring substr In the str string, starting at the pos. 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', 'foobarbarbar ', 5 );
-> 7

This function supports multi-byte characters and is case sensitive only when at least one parameter is a binary string.


POSITION (substr IN str)
Returns the position of the substring substr that appears for the first time in the str string. If the 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

The query result returned by MySQL is null (zero rows ). (The query takes 0.0050 seconds)

The Code is as follows: Copy code

SELECT * FROM 'O _ soft 'where instr ('d200', tid2)> 0

The query result returned by MySQL is null (zero rows ). (The query takes 0.0009 seconds)

Related Article

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.