Let’s pretend I’ve got a social network.
I’m always showing to the user how many users are registered and have activated their profile.
So, everytime a single user logs in, it goes to DB and make a:
select count(*) from users where status = 'activated'
so if 5.000 users logs in, or simply refreshes the page, it will make 5.000 requests to SQL above.
I was wondering if is better to have a variable some place(that I still have no idea where to put) that everytime a user activates his profile will add 1 and then, when I want to show how many users are registered to that social network, I’ll only get the value of this variable.
How can I make this? Is it really a better solution to what I’ve got?
You could use an indexed view, that SQL Server will automatically maintain:
This just has two possible statuses, but could expand to more using a different data type. As I say, in this case, SQL Server will maintain the counts behind the scenes, so you can just query the view:
and it won’t have to query the underlying table. You need to use the
WITH (NOEXPAND)hint on editions below (Enterprise/Developer).Although as @Jim suggested, doing a COUNT(*) against an index when the index column(s) can satisfy the query criteria using equality comparisons should be pretty quick also.