Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LOCATE vs INSTR

Tags:

mysql

    SELECT INSTR('1234','2')  #returns 2
    SELECT LOCATE('2','1234') #returns 2

Besides the argument numbering are there any significant differences to be aware of before choosing either of the functions?

like image 488
Maaz Rehman Avatar asked Jul 20 '17 14:07

Maaz Rehman


People also ask

What is the difference between Instr and Substr?

The substr functions allows you to extract a substring from a string. The instr function returns the location of a substring in a string. position and length of characters to be fetched. character in a word which returns numeric value.

What is locate in SQL?

The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search. Note: This function is equal to the POSITION() function.

What is locate in Oracle?

The LOCATE function is used to search for a string within another string. If the desired string is found, LOCATE returns the index at which it is found. If the desired string is not found, LOCATE returns 0.

What is Instr used for?

Definition and Usage. The INSTR() function returns the position of the first occurrence of a string in another string. This function performs a case-insensitive search.


2 Answers

The INSTR() function starts the search from the first character.

The LOCATE() function has a third parameter which allows you to change the starting position.

-- returns 4
SELECT INSTR("Alibaba", "ba")

-- returns 4 because the third parameter was not specified
SELECT LOCATE("ba", "Alibaba")

-- returns 6
SELECT LOCATE("ba", "Alibaba", 5)
like image 69
Revnic Robert-Nick Avatar answered Oct 08 '22 18:10

Revnic Robert-Nick


Locate

The LOCATE() function returns the position of the first occurrence of a substring in a string.

Instr

The INSTR() function returns the position of the first occurrence of a string in another string.

For example

SELECT LOCATE("H", "PHP") AS MatchPosition;`
-- -> returns 2
SELECT INSTR("PHP", "H") AS MatchPosition;
-- -> returns 2

And the performance is

-- 5.074 sec
SELECT BENCHMARK(100000000,INSTR('foobar','foo'));

-- 5.086 sec
SELECT BENCHMARK(100000000,LOCATE('foo','foobar')); 
like image 21
Naveen DA Avatar answered Oct 08 '22 18:10

Naveen DA