0

I have two tables:

"sites" has_many "users" 
"users" belongs_to "sites"

Is it better that whenever a users got added to sites I added column called users_count in sites table and increment it by one. Or is doing a conditional count on users table the best way?

2
  • It depends on what you're up to. Commented Apr 5, 2012 at 4:57
  • if the count's being done MANY times, then it'd make sense to store a cached value. But low traffic/low query-rate, the extra overhead might not be worth it. Commented Apr 5, 2012 at 4:59

1 Answer 1

2

"Better" is a subjective term.

However, I'll be adamant about this. There should not be two sources of the same information in a database, simply because they may get out of step.

The definitive way to discover how many users belong to a site is to use count to count them.

Third normal form requires that every non-key attribute depends on the key, the whole key, and nothing but the key (so help me, Codd).

If you add a user count to sites, that does not depend solely on the sites key value, it also depends on information in other tables.

You can revert from third normal form for performance if you understand the implications and mitigate the possibility of inconsistent data (such as with triggers) but the vast majority of cases should remain 3NF.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.