Data Manipulation   «Prev 

Oracle INSTR Function and Syntax

The INSTR function allows for simple or sophisticated searching through a string for a set of characters, not unlike LTRIM and RTRIM, except that INSTR does not clip anything off. It simply tells you where in the string it found what you were searching for. This is similar to the LIKE logical operator. However, LIKE can only be used in a
  1. where or
  2. having
clause, and INSTR can be used anywhere except in the from clause. Of course, LIKE can be used for complex pattern searches that would be quite difficult, if even possible, using INSTR.
Here is the format for INSTR:

INSTR(string,set [,start [,occurrence ] ])

INSTR searches String


select Author from MAGAZINE;

AUTHOR
-------------------------
BONHOEFFER, DIETRICH
CHESTERTON, G.K.
RUTH, GEORGE HERMAN
WHITEHEAD, ALFRED
CROOKES, WILLIAM

To find the location of the first occurrence of the letter O, INSTR is used without its options and with set as 'O' (note the single quotation marks, since this is a literal), as shown in the following listing:
select Author, INSTR(Author,'O') from MAGAZINE;

AUTHOR INSTR(AUTHOR,'O')
------------------------- -----------------
BONHOEFFER, DIETRICH 2
CHESTERTON, G.K. 9
RUTH, GEORGE HERMAN 9
WHITEHEAD, ALFRED 0
CROOKES, WILLIAM 3

This is, of course, the same as the following:
select Author, INSTR(Author,'O',1,1) from MAGAZINE;

If INSTR had looked for the second occurrence of the letter O, it would have found
select Author, INSTR(Author,'O',1,2) from MAGAZINE;

AUTHOR INSTR(AUTHOR,'O',1,2)
------------------------- ---------------------
BONHOEFFER, DIETRICH 5
CHESTERTON, G.K. 0
RUTH, GEORGE HERMAN 0
WHITEHEAD, ALFRED 0
CROOKES, WILLIAM 4

INSTR found the second O in Bonhoeffer's name, at position 5, and in Crookes' name, at position 4.
Chesterton has only one O, so for him, Ruth, and Whitehead, the result is zero, meaning no success and no second O was found.
To tell INSTR to look for the second occurrence, you also must tell it where to start looking (in this case, position 1). The default value of start is 1, which means that is what it uses if you do not specify anything, but the occurrence option requires a start, so you have to specify both. If set is not just one character but several, INSTR gives the location of the first letter of the set, as shown here:
select Author, INSTR(Author,'WILLIAM') from MAGAZINE;

AUTHOR INSTR(AUTHOR,'WILLIAM')
------------------------- -----------------------
BONHOEFFER, DIETRICH 0
CHESTERTON, G.K. 0
RUTH, GEORGE HERMAN 0
WHITEHEAD, ALFRED 0
CROOKES, WILLIAM 10

This has many useful applications, such as in the MAGAZINE table, for instance:
select Author, INSTR(Author,',') from MAGAZINE;

AUTHOR INSTR(AUTHOR,',')
------------------------- -----------------
BONHOEFFER, DIETRICH 11
CHESTERTON, G.K. 11
RUTH, GEORGE HERMAN 5
WHITEHEAD, ALFRED 10
CROOKES, WILLIAM 8

Ad   Oracle Database SQL