Skip to content
Advertisement

Select count of rows in another table in a Postgres SELECT statement

I don’t know quite how to phrase this so please help me with the title as well. 🙂

I have two tables. Let’s call them A and B. The B table has a a_id foreign key that points at A.id. Now I would like to write a SELECT statement that fetches all A records, with an additional column containing the count of B records per A row for each row in the result set.

I’m using Postgresql 9 right now, but I guess this would be a generic SQL question?

EDIT:

In the end I went for trigger-cache solution, where A.b_count is updated via a function each time B changes.

Advertisement

Answer

SELECT A.*, (SELECT COUNT(*) FROM B WHERE B.a_id = A.id) AS TOT FROM A
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement