I have SELECT:
SELECT c FROM (
SELECT "candidate_id" as id, count("candidate_id") as c
FROM "Applicaions"
GROUP BY &
I was made aware of this question by the author of this related one who was led to believe his problem could not be solved after reading here. Well, it can.
This answer is almost two years old, but the final questions were still pending.
Is it possible to write it simpler or is this the best solution?
To test for a single ID, the query you found is good. You can simplify:
SELECT coalesce((SELECT count(candidate_id)
FROM "Applications" WHERE candidate_id = _SOME_ID_), 0) AS c;
The WHERE condition limits to a single candidate_id and there is a single aggregate function in the SELECT list. GROUP BY candidate_id was redundant.
The column alias was swallowed by COALESCE(). If you want to name the resulting column move the alias to the end.
Another, cleaner (IMHO) form would be to use LEFT JOIN:
SELECT count(a.candidate_id) AS c
FROM (SELECT _SOME_ID_ AS candidate_id) x
LEFT JOIN "Applicaions" a USING (candidate_id)
This works nicely for multiple IDs, too:
WITH x(candidate_id) AS (
VALUES
(123::bigint)
,(345)
,(789)
)
SELECT x.candidate_id, count(a.candidate_id) AS c
FROM x
LEFT JOIN "Applicaions" a USING (candidate_id)
GROUP BY x.candidate_id;
LEFT JOIN is typically faster for a long list than multiple WHERE clauses or an IN expression.Or, for all rows in your table "Candidates":
SELECT x.candidate_id, count(a.candidate_id) AS c
FROM "Candidates" x
LEFT JOIN "Applications" a USING (candidate_id)
GROUP BY x.candidate_id;
Should I create any indexes?
If read performance is important and the table holds more than just a couple of rows you definitely need an index of the form:
CREATE INDEX foo_idx ON "Applications" (candidate_id);
Since this seems to be a foreign key column referencing "Candidates".candidate_id, you should most probably have that to begin with.