Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store row count in database or get dynamically

Tags:

php

mysql

Say I have a table full of comments, each from different users, and I want to count how many comments each user has. Should I have a separate table with the count, and update that on creation/deletion of comments, or should I query the count every time?

I feel like the latter is better, but I want some more experienced input on the matter. Thanks.

like image 925
Pat Avatar asked Jun 28 '26 00:06

Pat


2 Answers

Following the good old YAGNI principle, I would suggest you go with the simplest solution for now, which is just counting the number of comments as needed. This is just pragmatic coding.

If, down the line, you find this is causing even small performance problems, then you should replace it with a cached value using a stored procedure or similar, but chances are it will serve you just fine.

So, I realise this probably isn't the clear answer you want, but: if you're making something small, go with the easy solution (counting); if you're making something bigger, go with the easy solution (counting) then upgrade to the harder solution (storing a value) if you find you need it. If you know what you're making is guaranteed to be big (lucky you!) then fine, go straight for the harder solution.

Note: I've said "harder solution" but as you probably know it's only fractionally harder than the easy solution.

like image 115
TwoStraws Avatar answered Jun 29 '26 13:06

TwoStraws


After a commnent is created or deleted you should count right in the hour.

If you count every time you will make some desnecessary querys.

like image 31
Pedro Avatar answered Jun 29 '26 14:06

Pedro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!