Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres JSON_AGG and Order By not working together

Tags:

postgresql

I have a query that looks like this:

SELECT *,
(SELECT json_agg(deals.*) FROM deals WHERE vendors.id = deals.vendorid) as deals
FROM vendors

That query works great, however when I try and order by a field in the deals table like this:

SELECT *,
(SELECT json_agg(deals.*) FROM deals WHERE vendors.id = deals.vendorid ORDER BY priority) as deals
FROM vendors

I get the following error:

error: column "deals.priority" must appear in the GROUP BY clause or be used in an aggregate function

Any ideas how to do a sort like this?

like image 869
Jordash Avatar asked Jan 23 '18 18:01

Jordash


3 Answers

You can

SELECT *,
(SELECT json_agg(deals.* ORDER BY priority) FROM deals WHERE vendors.id = deals.vendorid) as deals
FROM vendors

See examples with array_agg and string_agg.

like image 190
2 revs Avatar answered Nov 17 '22 07:11

2 revs


Shouldn't the syntax be this?

(SELECT json_agg(deals.*) WITHIN GROUP (ORDER BY priority)
 FROM deals
 WHERE vendors.id = deals.vendorid 
) as deals

The documentation is here.

like image 28
Gordon Linoff Avatar answered Nov 17 '22 07:11

Gordon Linoff


As a side note, if you don't limit the amount of deals queried, you should use a left join instead of a subquery:

SELECT *
FROM vendors
LEFT JOIN (
  SELECT vendorid, json_agg(* ORDER BY priority) AS deals
  FROM deals
  GROUP BY vendorid
)
ON vendors.id = deals.vendorid
like image 1
Oreille Avatar answered Nov 17 '22 09:11

Oreille