10

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 ?

1
  • What "just somebody" is trying to say: your database model is wrong. Read up on normalization Commented Jul 15, 2013 at 11:23

3 Answers 3

15

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} )
Sign up to request clarification or add additional context in comments.

Comments

0

What you're looking for is probably split_part which is available as a String function in PostgreSQL. See http://www.postgresql.org/docs/9.1/static/functions-string.html.

Comments

0
select
    id,       
    prodname[1] as size,
    prodname[2] as brand
from (
    select
        id,
        regexp_split_to_array(prodname, ' ') as prodname
    from products
) s
where
    ({0} is null or prodname[1] = {0})
    and
    ({1} is null or prodname[2] = {1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.