Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql search text into array of text

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
like image 910
Mehdi Monzavi Avatar asked Mar 04 '17 13:03

Mehdi Monzavi


3 Answers

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}
like image 172
Clodoaldo Neto Avatar answered Oct 20 '22 15:10

Clodoaldo Neto


And yet another solution using unnest

select * from t1
where exists (
  select * from unnest(t1.names) n
  where n like 'a%')
like image 2
Abelisto Avatar answered Oct 20 '22 14:10

Abelisto


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

SELECT * FROM t1 WHERE names && ARRAY['alex', 'jully'] ;
like image 2
Kundan Sharma Avatar answered Oct 20 '22 14:10

Kundan Sharma