2

How can I get subquery array and it`s count?

SELECT location.country,    
       (SELECT array(
            SELECT competition.id
            FROM competition
            WHERE location.id = competition.location_id )) AS list,
       array_length(list, 1) AS list_count
FROM location

I am trying to get competition list for every country. Query works fine without: array_length(list, 1) AS list_count

It is arguing that column 'list' doesn't exists.
Model: http://sqlfiddle.com/#!2/4c449

7
  • Can you add an example datamodel on sqlfiddle? sqlfiddle.com/#!15
    – Wolph
    Commented Jan 9, 2014 at 10:48
  • Your question is unclear. You need to add a table definition and define the array. Commented Jan 9, 2014 at 11:03
  • @ErwinBrandstetter Sorry, I have edited question. Commented Jan 9, 2014 at 11:10
  • I don't see much of an improvement. Still no table definition. Still your query is incomplete and the question unclear. Also, the description doesn't match the code. array_length(p,1) does not even reference list ... I can only guess: It's not possible to reference a column alias on the same query level. You would have to use a subquery. Commented Jan 9, 2014 at 11:23
  • @Wolph sqlfiddle.com/#!2/4c449 Commented Jan 9, 2014 at 12:22

2 Answers 2

2

Probably even simpler / faster: aggregate and count in a separate query and join to it (thereby avoiding your original problem to begin with):

SELECT l.country, c.list, c.list_count
FROM   location l
LEFT   JOIN (
   SELECT location_id AS id
         ,array_agg(id) AS list
         ,count(*) AS list_count
   FROM   competition
   GROUP  BY 1
   ) c USING (id)

Should be faster as long as you fetch large parts of the table or all of it.

1
  • That makes more sense for me. Commented Jan 9, 2014 at 12:55
1
select country, 
       list, 
       array_length(list, 1) as list_count
from (
  SELECT country,    
         (SELECT array(
            SELECT competition.id
            FROM competition
            WHERE location.id = competition.location_id )) AS list
  FROM location
) t

Using an aggregate might be faster though:

select country, 
       list, 
       array_length(list, 1) as list_count
from (
  SELECT l.country,    
         array_agg(c.id) as list
  FROM location l
    JOIN competition c ON l.id = c.location_id
  GROUP BY l.country
) t

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.