A detailed explanation and application of the instr() function in Oracle.
The instr() function in Oracle is used to find the position of a specified substring within a string. Its syntax is as follows:
INSTR(string, substring [, start_position [, nth_occurrence]])
Explanation of parameters:
- string: the string to be searched.
- substring: the substring to be searched for.
- start_position: an optional parameter that specifies the position to start searching from, with a default value of 1.
- nth_occurrence: an optional parameter that specifies the position of the substring within the string to search for, with the default being the first occurrence.
Return value:
- If a substring is found, return its position in the string.
- If the substring is not found, return 0.
Here are some common usage examples:
- Find the position of a substring:
- The output would be 8 when searching for the position of ‘Database’ within the string ‘Oracle Database’.
- Find the position of the substring starting from a given location.
- The code will return the position of the letter ‘a’ in the string ‘Oracle Database’, starting from the 4th character.
— Result: 7 - Find the position of the Nth occurrence of a substring.
- The position of the second occurrence of the letter ‘a’ in the string ‘Oracle Database’ is 16.
- Return 0 if the substring is not found.
- The above query will return the position of ‘SQL’ in the string ‘Oracle Database’. The result is 0.
Besides finding the position of a substring, the instr() function can also be used for other purposes, such as:
- Replace a part of the string:
SELECT REPLACE(‘ABCDEF’, ‘CD’, ‘XY’) AS replaced_string FROM dual;
— Result: ABXYEF - Extracting substring:
SELECT SUBSTR(‘Oracle Database’, 8, 8) AS substring FROM dual;
— Result: Database
Summary:
The instr() function in Oracle is used to find the position of a subtring within a string, allowing for the specification of a starting position and search order. It is a commonly used string function that can be used in various scenarios.