Convert Subquery Result to Array

I want my subquery results (multi rows) return as a singale row in my query. For example.


select u.url, (select c.categoryid from category c 
where c.categoryid = u.categoryid) from url u

If url contains multiple categories, subquery will return multiple rows as following
P.S Subquery return multiple rows is not supported in most of the database but PostgreSQL


url | categoryid
---------------------
1   |  1
1   |  2
2   |  1

Result i wanted is as following


url | categoryid
---------------------
1   |  1,2
2   |  1

I’m not sure how easy it can achieve in others database like oracle or mysql, however PostgreSQL provided Array data type, using array it’s very easy to get what i want. I have to changed my query to


select u.url, (select array(select c.categoryid from category c 
where c.categoryid = u.categoryid))as categoryid from url u

Result ~


url | categoryid
---------------------
1   |  {1,2}
2   |  1

Done ~ PostgreSQL Array Rock ~

7 comments on “Convert Subquery Result to Array

  1. SELECT u.url, array_agg(u.categoryid) AS categoryids
    FROM url u
    ORDER BY url

    Reply
  2. thanks for the informative blog entries.
    I have the following problem and would appreciate your comments.
    I am trying to port the following Oracle sql to postgres:
    SELECT CAST (MULTISET (SELECT cd.a, cd.xml_key, cd.b,
    cd.c, cd.d, cd.e
    FROM table1 cd
    WHERE cd.a = t.a
    ) AS custom_typ )AS my_list
    FROM table2 t, table3 aclp
    WHERE t.foo = aclp.bar

    here the subquery has “multiple columns (not just one as in your example”. How could I convert the result set from the inner query into an array (of row set)?

    Reply
  3. Hey there, does anyone know how can I read this output (an array column) using hibernate ? I’ve done this using array_to_string and then splitting the string column in Java, but I don’t like that. The any on SQLQuery was deprecated. custom and Hibernate.* types are deprecated also.

    Reply
  4. If you want the result 1,2 you can get it by using the array_to_string function

    Like this :
    SELECT u.url, (SELECT array_to_string(array(SELECT c.categoryid FROM category c
    WHERE c.categoryid = u.categoryid)), ‘,’) AS categoryid FROM url u

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *