I have two tables in a one-to-many relationship. Let's say that for each row in table foo, there can be 0 or more rows in table bar that reference the row in foo.
The client wants to know how many rows in bar reference a row in foo, for all the rows in foo.
I can accomplish this with the following query:
SELECT count(bar_id) FROM bar WHERE bar.foo_id = foo.foo_id;
However, what if the tables foo and bar were large? Say foo has 1 million rows, and bar has 10 million rows. Let's also say that 99% of rows in foo would have a count of less than 1,000 bar rows referencing it. Let's say that the client typically asks for around 100 rows of foo at a time.
Should I use the naive count() query with an index on the foreign key, or would it be better to keep a counter? Is it even possible to keep a counter? By updating the counter with atomic increments and decrements using a trigger on bar, I believe it's possible, but I could be wrong.