Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL patindex equivalent in PostgreSQL

I am in need of Postgres equivalent of the SQL function patindex

like image 362
Priya Avatar asked May 11 '17 11:05

Priya


1 Answers

There is no exact equivalent to SQL Server's PATINDEX function. You can use other string functions for your needs. Here is the docs: https://www.postgresql.org/docs/current/static/functions-string.html

But if you need exactly the same function, you can write a "wrapper" as shown below:

CREATE OR REPLACE FUNCTION "patindex"( "pattern" VARCHAR, "expression" VARCHAR ) RETURNS INT AS $BODY$
SELECT
    COALESCE(
        STRPOS(
             $2
            ,(
                SELECT
                    ( REGEXP_MATCHES(
                        $2
                        ,'(' || REPLACE( REPLACE( TRIM( $1, '%' ), '%', '.*?' ), '_', '.' ) || ')'
                        ,'i'
                    ) )[ 1 ]
                LIMIT 1
            )
        )
        ,0
    )
;
$BODY$ LANGUAGE 'sql' IMMUTABLE;

Example:

SELECT patindex( '%e_t%', 'Test String' );

2

SELECT patindex( '%S_r%', 'Test String' );

6

SELECT patindex( '%x%', 'Test String' );

0

like image 76
ncank Avatar answered Oct 28 '22 04:10

ncank