Treat a subquery like a value
Postgres is cool with returning a value from a query.
select 1;
And also returning a value from a subquery.
select (select 1);
Turtles all the way down.
select (select (select 1));
But that subquery can only return one row or you'll get an error.
select (select unnest('{1, 2}'::integer[]));
ERROR: more than one row returned by a subquery used as an expression
This is used sometimes when you need to use a count in an expression.
select round((select count(*) from pg_class where reltype = 0) / (select count(*)::float from pg_class) * 100) as percent_with_zero_reltype;
percent_with_zero_reltype
---------------------------
39
Tweet