PostgreSQL POSITION() Function
The PostgreSQL POSITION()
function returns the location of the first instance of a substring within a string.
Syntax
The following illustrates the syntax of the POSITION()
function:
Arguments
The POSITION()
function requires two arguments:
1) substring
The substring argument is the string that you want to locate.
2) string
The string
argument is the string for which the substring is searched.
Return Value
The POSITION()
function returns an integer representing the location of the first instance of the substring within the input string.
The POSITION()
function returns zero (0) if the substring is not found in the string. It returns NULL if either substring
or string
argument is null.
Examples
The following example returns the position of the 'Tutorial'
in the string 'PostgreSQL Tutorial'
:
The result is as follows:
Note that the POSITION()
function searches for the substring case-insensitively.
See the following example:
It returns zero (0), indicating that the string tutorial
does not exist in the string 'PostgreSQL Tutorial'
.
The following example uses the POSITION()
function to locate the first string 'fateful'
in the description
column of the film
table from the sample database:
Output:
Remarks
The POSITION()
function returns the location of the first instance of the substring in the string.
For example:
Output:
Even though the substring 'is'
appears twice in the string 'This is a cat'
, the POSITION()
function returns the first match.
Summary
- Use the
POSITION()
function to locate the first instance of a substring within a string.