postgresql search text into array of text
Asked Answered
U

3

6

i have a table t1

id  |  names
----|-------------------------
1   |  {jully , alex , sarah}
2   |  {bety , cate , jenifer}
3   |  {adam , pit , joee}
4   |  {piter , mat , andy}

so, i need rows have at least one name that start with "a" the result i need is in the below

in row 1 : alex

in row 3 : adam

in row 4 : andy

id   |   names
-----|-------------------------
1    |  {jully , alex , sarah}
3    |  {adam , pit , joee}
4    |  {piter , mat , andy}

a query like it

select * from t1 where 'a' like% any t1.name
Uriel answered 4/3, 2017 at 13:13 Comment(0)
V
6
select *
from (
    select id, unnest(names) as name
    from t
) s
where name like 'a%';
 id | name 
----+------
  1 | alex
  3 | adam
  4 | andy

To have it aggregated:

select id, array_agg(name)
from (
    select id, unnest(names) as name
    from t
) s
where name like 'a%'
group by id;
 id | array_agg 
----+-----------
  4 | {andy}
  1 | {alex}
  3 | {adam}
V2 answered 4/3, 2017 at 13:31 Comment(2)
unnest function, break each row to separate row that any row contain ow item , it means we have 12 records instead of 4 record , with extra filed "name" , it is not a solution , in our pivot table, we have millions of recordUriel
thanks clodoaldo , i tried it, as i guest... . thus i changed the arrays item into sapparate of item, that i sure they are unique (such as "andy" => "an" , "dy" ) , now i use array contain operand.... so by this approach my problem was sold... my experience ;-)Uriel
S
2

And yet another solution using unnest

select * from t1
where exists (
  select * from unnest(t1.names) n
  where n like 'a%')
Spahi answered 4/3, 2017 at 14:52 Comment(0)
P
2

If you have to search multiple values inside the text array. You can use this:

SELECT * FROM t1 WHERE names && ARRAY['alex', 'jully'] ;
Patch answered 23/8, 2019 at 5:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.