Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL more than one row returned by a subquery used as an expression

Tags:

sql

postgresql

Running PostgreSQL 9.6. I'm trying to output rows consisting of a value and a list of names. This is my query:

SELECT name, (SELECT car_name FROM cars WHERE user = id)
FROM users WHERE user_id = 1 ORDER BY name;

But it fails with:

ERROR:  more than one row returned by a subquery used as an expression

It of course make sense, but I would like to have the nested query to be outputted as a list or json. I've tried with row_to_json, but that fails also.

like image 374
Alfred Balle Avatar asked Nov 15 '25 05:11

Alfred Balle


1 Answers

Use an aggregation function, such as string_agg() or json_agg():

SELECT name,
       (SELECT string_agg(car_name) FROM cars WHERE user = id)
FROM users
WHERE user_id = 1
ORDER BY name;
like image 180
Gordon Linoff Avatar answered Nov 17 '25 20:11

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!