Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract specific word from string in Postgres

Tags:

sql

postgresql

Product name contains words deliminated by space. First word is size second in brand etc.

How to extract those words from string, e.q how to implement query like:

select
  id,       
  getwordnum( prodname,1 ) as size,
  getwordnum( prodname,2 ) as brand
  from products
where ({0} is null or getwordnum( prodname,1 )={0} ) and
    ({1} is null or getwordnum( prodname,2 )={1} )


create table product ( id char(20) primary key, prodname char(100) );

How to create getwordnum() function in Postgres or should some substring() or other function used directly in this query to improve speed ?

like image 273
Andrus Avatar asked Jul 15 '13 11:07

Andrus


1 Answers

You could try to use function split_part

select
  id,       
  split_part( prodname, ' ' , 1 ) as size,
  split_part( prodname, ' ', 2 ) as brand
  from products
where ({0} is null or split_part( prodname, ' ' , 1 )= {0} ) and
    ({1} is null or split_part( prodname, ' ', 2 )= {1} )
like image 78
xisco rossello Avatar answered Sep 26 '22 13:09

xisco rossello