The INSTR function returns the position of the first occurrence of a substring in the main string, with position counting starting from 1. This is a commonly used string search function that supports exact matching and is case-sensitive. The function is widely used in text processing, data cleaning, and string analysis.
INSTR(<str>, <substr>)
| Parameter | Description |
|---|---|
<str> | Main string to search within. Type: VARCHAR |
<substr> | Substring to find. Type: VARCHAR |
Returns INT type, representing the position of the first occurrence of the substring in the main string.
Search rules:
Special cases:
SELECT INSTR('abc', 'b'), INSTR('abc', 'd');
+-------------------+-------------------+ | INSTR('abc', 'b') | INSTR('abc', 'd') | +-------------------+-------------------+ | 2 | 0 | +-------------------+-------------------+
SELECT INSTR('hello world', 'world'), INSTR('hello world', 'WORLD');
+------------------------------+------------------------------+ | INSTR('hello world', 'world') | INSTR('hello world', 'WORLD') | +------------------------------+------------------------------+ | 7 | 0 | +------------------------------+------------------------------+
SELECT INSTR(NULL, 'test'), INSTR('test', NULL);
+---------------------+---------------------+ | INSTR(NULL, 'test') | INSTR('test', NULL) | +---------------------+---------------------+ | NULL | NULL | +---------------------+---------------------+
SELECT INSTR('hello', ''), INSTR('', 'world');
+--------------------+---------------------+ | INSTR('hello', '') | INSTR('', 'world') | +--------------------+---------------------+ | 1 | 0 | +--------------------+---------------------+