sql - emulating MySQL's substring_index() in PGSQL -


i find elegant way emulate behavior of mysql's subtring_index() function in postgres.

in mysql, it's easy as:

mysql> create temporary table test1(test varchar(200)); query ok, 0 rows affected (0.01 sec)  mysql> insert test1 values('apples||oranges'),('apples||grapes'); query ok, 2 rows affected (0.00 sec) records: 2  duplicates: 0  warnings: 0  mysql> select * test1; +-----------------+ | test            | +-----------------+ | apples||oranges | | apples||grapes  | +-----------------+ 2 rows in set (0.00 sec)  mysql> select substring_index(test, '||', 1) field1, substring_index(test, '||', -1) field2 test1; +--------+---------+ | field1 | field2  | +--------+---------+ | apples | oranges | | apples | grapes  | +--------+---------+ 2 rows in set (0.00 sec) 

but current work around in pgsql quite ugly:

hoth=# create temporary table test1(test text); create table  hoth=# insert test1 values('apples||oranges'),('apples||grapes'); insert 0 2  hoth=# select * test1;       test        -----------------  apples||oranges  apples||grapes (2 rows)  hoth=# select substring(test, 0, position('||' in test)) field1,  substring(test, position('||' in test) + 2, char_length(test)) field2  test1;  field1 | field2   --------+---------  apples | oranges  apples | grapes (2 rows) 

perhaps there more elegant solution using regex, or maybe splitting string array in variable might reduce overhead if string derived sub-query or something, welcome suggestions.

always take time skim manuals.

http://www.postgresql.org/docs/current/static/functions-string.html

if split_part(string text, delimiter text, field int) doesn't want (and more, if understand mysql function) you'll need explain , why.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -