Как найти подстроку в строке oracle

В этом учебном пособии вы узнаете, как использовать Oracle/PLSQL функцию INSTR с синтаксисом и примерами.

Описание

Oracle/PLSQL функция INSTR возвращает n-е вхождение подстроки в строке.

Синтаксис

Синтаксис функции Oracle/PLSQL INSTR:

INSTR( string, substring [, start_position [, nth_appearance ] ] )

Параметры или аргументы

string является строка для поиска. string может быть CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB или NCLOB.

substring подстрока для поиска в строке. substring может быть CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB или NCLOB.

start_position является положение символа в строке, с которого начнется поиск. Этот аргумент является необязательным. Если аргумент опущен, то по умолчанию 1. Первая позиция в строке 1. Если параметр start_position отрицательный, то функция INSTR рассчитывает позицию start_position в обратном направлении от конца строки, а затем ищет к началу строки.

nth_appearance является n-м вхождением подстроки. Аргумент не является обязательным. Если опущен, то по умолчанию 1.

Примечание

  • Если подстрока не найдена в строке, то функция INSTR вернет 0.

Применение

Функцию INSTR можно использовать в следующих версиях Oracle/PLSQL:

  • Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

Пример

Рассмотрим несколько примеров функции INSTR и изучим, как использовать функцию INSTR в Oracle/PLSQL.

SQL> SELECT INSTR(‘На дворе трава’, ‘а’) FROM DUAL;

–Результат:       2

SQL> SELECT INSTR(‘На дворе трава’, ‘а’, 1, 1) FROM DUAL;

–Результат:       2

SQL> SELECT INSTR(‘На дворе трава’, ‘а’, 1, 2) FROM DUAL;

–Результат:       12

SQL> SELECT INSTR(‘На дворе трава’, ‘а’, 1, 3) FROM DUAL;

–Результат:       14

SQL> SELECT INSTR(‘На дворе трава’, ‘а’, -3, 2) FROM DUAL;

–Результат:       2

The Oracle INSTR() function searches for a substring in a string and returns the position of the substring in a string.

Syntax

The followig illustrates the syntax of the Oracle INSTR() function:

INSTR(string , substring [, start_position [, occurrence]])

Code language: SQL (Structured Query Language) (sql)

Arguments

The Oracle INSTR() function accepts four arguments:

string

is the string or character expression that contains the substring to be found.

 substring

is the substring to be searched

start_position

is a nonzero integer that specifies where in the string the INSTR() function begins to search. The start_position is calculated using characters as defined by input character set.

If the start_position is positive, then INSTR() function searches and counts forward from the beginning of the string. In case the start_position is negative, the INSTR() function will search and count backward from the end of the string.

The start_position is an optional parameter. The default value of the start_position is 1. It means that, by default, the INSTR() function searches from the begining of the string.

occurrence

is an positive integer that specifies which occurrence of the substring for which the INSTR() function should search. The occurence is optional and its default value is 1, meaning that the INSTR() funtion searches for the first occurrence of the substring by default.

Return value

The INSTR() function returns a positive integer that is the position of a substring within a string.

If the string does not contain the substring, the INSTR() function returns 0 (zero).

Examples

Oracle INSTR

1) Search from the start of the string

The following statement returns the  location of the first occurrence of the is substring in This is a playlist, starting from position 1 (the first character) in the string.

SELECT INSTR( 'This is a playlist', 'is' ) substring_location FROM dual;

Code language: SQL (Structured Query Language) (sql)

Oracle INSTR - search forward

In this example, the INSTR() function searched for the first occurrence of the substring is from the beginning of the string This is a playlist.

2) Search for the 2nd and 3nd occurrence of a substring

The following statement returns the location of the 2nd and 3rd occurrences of the substring is in This is a playlist

SELECT INSTR( 'This is a playlist', 'is', 1, 2 ) second_occurrence, INSTR( 'This is a playlist', 'is', 1, 3 ) third_occurrence FROM dual;

Code language: SQL (Structured Query Language) (sql)

Oracle INSTR - search for 2nd and 3rd occurrence

In this example, we passed the start_position as 1 and the occurrence as 2 and 3 to instruct the INSTR() function to search for the 2nd and 3rd occurrences of the substring is in the string This is a playlist.

3) Search for a substring that does not exist in a string

The following example illustrates the result when the substring are is not found in the searched string:

SELECT INSTR( 'This is a playlist', 'are' ) substring_location FROM dual;

Code language: SQL (Structured Query Language) (sql)

Oracle INSTR - substring not found

4) Search backward

The following example searches the first occurrence of the substring is backward from the end of the searched string.

SELECT INSTR( 'This is a playlist', 'is',-1 ) substring_location FROM dual;

Code language: SQL (Structured Query Language) (sql)

Oracle INSTR - search backward

In this tutorial, you have learned how to search and return the position of a substring in a string.

Was this tutorial helpful?

totn Oracle Functions


This Oracle tutorial explains how to use the Oracle/PLSQL INSTR function with syntax and examples.

Description

The Oracle/PLSQL INSTR function returns the location of a substring in a string.

Syntax

The syntax for the INSTR function in Oracle/PLSQL is:

INSTR( string, substring [, start_position [, th_appearance ] ] )

Parameters or Arguments

string
The string to search. string can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
substring
The substring to search for in string. substring can be CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
start_position
Optional. The position in string where the search will start. If omitted, it defaults to 1. The first position in the string is 1. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
nth_appearance
Optional. The nth appearance of substring. If omitted, it defaults to 1.

Returns

The INSTR function returns a numeric value. The first position in the string is 1.
If substring is not found in string, then the INSTR function will return 0.
If string is NULL, then the INSTR function will return NULL.
If substring is NULL, then the INSTR function will return NULL.

Applies To

The INSTR function can be used in the following versions of Oracle/PLSQL:

  • Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i

Example

Let’s look at some Oracle INSTR function examples and explore how to use the INSTR function in Oracle/PLSQL.

For example:

INSTR('Tech on the net', 'e')
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 1)
Result: 2   (the first occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 2)
Result: 11  (the second occurrence of 'e')

INSTR('Tech on the net', 'e', 1, 3)
Result: 14  (the third occurrence of 'e')

INSTR('Tech on the net', 'e', -3, 2)
Result: 2

In Oracle, the INSTR() function searches for a substring in a given string, and returns an integer indicating the position of the first character of this substring. If the substring isn’t found, the function returns 0.

INSTR() requires at least two arguments; the string, and the substring. It also accepts an optional third and fourth arguments that allows you to specify the starting position to search, and which occurrence to search for.

INSTR() can also be thought of as a group of functions. There are five separate functions; INSTR(), INSTRB(), INSTRC(), INSTR2(), and INSTR4(). Each function calculates the length in a different way.

Syntax

The syntax goes like this:

{ INSTR
| INSTRB
| INSTRC
| INSTR2
| INSTR4
}
(string , substring [, position [, occurrence ] ])

Where string is the string to search, substring is the substring to find, position is the starting position of the substring, and occurrence is which occurrence to find.

The functions calculate lengths as follows:

Function Calculates length using…
INSTR() Characters as defined by the input character set, with the first character of string having position 1.
INSTRB() Bytes
INSTRC() Unicode complete characters
INSTR2() UCS2 code points
INSTR4() UCS4 code points

Example

Here’s a basic example:

SELECT INSTR('Big fat cat', 'fat')
FROM DUAL;

Result:

5

Compared with INSTRB()

This example shows how the results can differ, depending on which specific function you’re using, and the character set involved.

In this case, we compare INSTR() with INSTRB():

SELECT 
    INSTR('Böyük yağlı pişik', 'yağlı') AS INSTR,
    INSTRB('Böyük yağlı pişik', 'yağlı') AS INSTRB
FROM DUAL;

Result:

   INSTR    INSTRB 
________ _________ 
       7         9

We can see that the two functions returned two different results. This is because some characters in this string use two bytes.

The INSTR() function returns the position as defined by the input character set, whereas the INSTRB() function returns the position based in bytes.

If we return to the original string, the results are the same between the two functions:

SELECT 
    INSTR('Big fat cat', 'fat') AS INSTR,
    INSTRB('Big fat cat', 'fat') AS INSTRB
FROM DUAL;

Result:

   INSTR    INSTRB 
________ _________ 
       5         5 

That’s because this string uses just one byte per character, and so the length in bytes is the same as the number of characters.

Starting Position

Here’s an example that specifies the position for which to start the search:

SELECT INSTR('That fat cat', 'at', 8)
FROM DUAL;

Result:

11

In this case, the search starts at position 8, which is after the first two occurrences. Therefore, we get the position of the third match.

Specify Which Occurrence

Here’s an example of specifying which occurrence to find:

SELECT INSTR('That fat cat', 'at', 1, 2)
FROM DUAL;

Result:

7

In this case, we started at position 1, and then searched for the second occurrence from that starting position.

Here it is again, but this time we compare three different values for the occurrence argument:

SELECT 
    INSTR('That fat cat', 'at', 1, 1) AS "o1",
    INSTR('That fat cat', 'at', 1, 2) AS "o2",
    INSTR('That fat cat', 'at', 1, 3) AS "o3"
FROM DUAL;

Result:

   o1    o2    o3 
_____ _____ _____ 
    3     7    11

But here’s what happens if we increase the position argument:

SELECT 
    INSTR('That fat cat', 'at', 5, 1) AS "o1",
    INSTR('That fat cat', 'at', 5, 2) AS "o2",
    INSTR('That fat cat', 'at', 5, 3) AS "o3"
FROM DUAL;

Result:

   o1    o2    o3 
_____ _____ _____ 
    7    11     0 

In this case we don’t get the position of the first occurrence, because it’s located before our starting position. We also get 0 in the third column because there’s no third occurrence, based on our starting position.

Negative Position

Specifying a negative value for the position causes the starting position to be counted backwards from the end of the string, and for Oracle to search backward from that position:

SELECT INSTR('That fat cat', 'at', -3)
FROM DUAL;

Result:

7

And any occurrence that is specified is counted backward from that position:

SELECT INSTR('That fat cat', 'at', -3, 2)
FROM DUAL;

Result:

3

Null Arguments

If any (or all) of the arguments are null, the result is null:

SET NULL 'null';
SELECT 
    INSTR(null, 'f', 1, 1) AS r1,
    INSTR('Coffee', null, 1, 1) AS r2,
    INSTR('Coffee', 'f', null, 1) AS r3,
    INSTR('Coffee', 'f', 1, null) AS r4
FROM DUAL;

Result:

     R1      R2      R3      R4 
_______ _______ _______ _______ 
   null    null    null    null

By default, SQLcl and SQL*Plus return a blank space whenever null occurs as a result of a SQL SELECT statement.

However, you can use SET NULL to specify a different string to be returned. Here I specified that the string null should be returned.

Incorrect Argument Count

Calling INSTR() without passing any arguments results in an error:

SELECT INSTR()
FROM DUAL;

Result:

Error starting at line : 1 in command -
SELECT INSTR()
FROM DUAL
Error at Command Line : 1 Column : 8
Error report -
SQL Error: ORA-00938: not enough arguments for function
00938. 00000 -  "not enough arguments for function"
*Cause:    
*Action:

And passing too many arguments also results in an error:

SELECT INSTR('Big fat cat', 'at', 1, 2, 3)
FROM DUAL;

Result:

Error starting at line : 1 in command -
SELECT INSTR('Big fat cat', 'at', 1, 2, 3)
FROM DUAL
Error at Command Line : 1 Column : 38
Error report -
SQL Error: ORA-00939: too many arguments for function
00939. 00000 -  "too many arguments for function"
*Cause:    
*Action:

How can I check for a substring in a string in Oracle without using LIKE? Let’s say I want to select all users from a table that have the letter “z” in their last name:

SELECT * FROM users WHERE last_name LIKE '%z%';

That would work, but I don’t want to use LIKE. Is there some other function I could use?

buddemat's user avatar

buddemat

4,40713 gold badges25 silver badges49 bronze badges

asked Oct 15, 2009 at 12:05

Richard Knop's user avatar

Richard KnopRichard Knop

80.2k149 gold badges391 silver badges551 bronze badges

1

I’m guessing the reason you’re asking is performance?
There’s the instr function. But that’s likely to work pretty much the same behind the scenes.

Maybe you could look into full text search.

As last resorts you’d be looking at caching or precomputed columns/an indexed view.

Community's user avatar

answered Oct 15, 2009 at 12:09

wefwfwefwe's user avatar

7

If you were only interested in ‘z’, you could create a function-based index.

CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))

Then your query would use WHERE INSTR(last_name,'z') > 0.

With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.

Also, keep in mind that if your data has the names capitalized in the standard way (e.g., “Zaxxon”), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z').

answered Oct 15, 2009 at 13:32

Dave Costa's user avatar

Dave CostaDave Costa

47k8 gold badges56 silver badges71 bronze badges

1

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don’t you want to use like?

Edit: I took the liberty of making the search case insensitive so you don’t miss Bob Zebidee. 🙂

answered Oct 18, 2009 at 4:21

darreljnz's user avatar

darreljnzdarreljnz

2,2602 gold badges18 silver badges18 bronze badges

Databases are heavily optimized for common usage scenarios (and LIKE is one of those).

You won’t find a faster way of doing your search if you want to stay on the DB-level.

answered Oct 15, 2009 at 12:45

Foxfire's user avatar

FoxfireFoxfire

5,67521 silver badges29 bronze badges

Bear in mind that it is only worth using anything other than a full table scan to find these values if the number of blocks that contain a row that matches the predicate is significantly smaller than the total number of blocks in the table. That is why Oracle will often decline the use of an index in order to full scan when you use LIKE ‘%x%’ where x is a very small string. For example if the optimizer believes that using an index would still require single-block reads on (say) 20% of the table blocks then a full table scan is probably a better option than an index scan.

Sometimes you know that your predicate is much more selective than the optimizer can estimate. In such a case you can look into supplying an optimizer hint to perform an index fast full scan on the relevant column (particularly if the index is a much smaller segment than the table).

SELECT /*+ index_ffs(users (users.last_name)) */
       * 
FROM   users
WHERE  last_name LIKE "%z%"

answered Oct 15, 2009 at 14:13

David Aldridge's user avatar

David AldridgeDavid Aldridge

51.3k8 gold badges68 silver badges95 bronze badges

try using the function REGEXP_INSTR

answered Apr 12 at 7:56

AlexandrIT's user avatar

1

Добавить комментарий