I have a Postgres 9.6 database with two tables, template and project.
template
id integer
name varchar
project
id integer
name varchar
template_id integer (foreign key)
is_deleted boolean
is_listed boolean
I want to get a list of all templates, with a count of the projects for each template, and a count of the deleted projects for each template, i.e. this type of output
id,name,num_projects,num_deleted,num_listed
1,"circle",19,2,7
2,"square",10,0,8
I have a query like this:
select id, name,
(select count(*) from project where template_id=template.id)
as num_projects,
(select count(*) from project where template_id=template.id and is_deleted)
as num_deleted,
(select count(*) from project where template_id=template.id and is_listed)
as num_listed
from template;
However, looking at the EXPLAIN, this isn't very efficient as the large project table is queried separately three times.
Is there any way to get Postgres to query and iterate over the project table just once?