Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing view counts in database table

What is the appropriate and most efficient way to store a view count each time a database record is access?

I have table ITEMS containing the following fields: id, item_name

Each item has its own permalink: http://domain.com/item_name

I would like to be able to use this data and display a Views: 2,938 on the page. Which method is best?


Method A

Create an additional field view_count in the ITEMS table and update it to increment the view count:

view_count = view_count + 1;

Method B

Create a new table VIEWS containing the following fields:

id, item_id, timestamp, ip

And add a new record to the VIEWS table each time a page is viewed.

Method C

Is there another method altogether?


I have seen Method A used in a variety of PHP forum software, however my University instructors have informed me that Method B is better because add() requires less strain than update()

like image 544
user3474346 Avatar asked Oct 25 '25 05:10

user3474346


1 Answers

It's somewhat true that an INSERT operation will often consume less resources than an UPDATE statement; but a well tuned UPDATE statement isn't necessarily a strain".

There are other considerations. If the only known and foreseen requirement is for a "total" page count, then a single row will consume much less storage than storing individual rows for each "view" event. Also, the queries to retrieve the view count will be much more efficient.

(Where the "strain" is in the real world is in storage, not in terms of just disk space, but the number of tapes and the amount of clock time required for backups, time required for restore, etc.)

If you need to be able to report on views by hour, or by day, then having the more granular data will provide you the ability to do that, which you can't get from just a total.

You could actually do both.

If I needed a "summary" count to put the page, I wouldn't want to have to run a query against a boatload of rows in the historical event record, just to come up with a new value of 2,939 the next time the page is viewed. It would be much less of a "strain" on database resources to retrieve a single column value from a single row, than it would be to churn through thousands of rows of event data to aggregate it into a count, every time a page is viewed.

If I also needed to be able to administratively report "views" by country, or by IP, by hour, by day or week or month, I would also store the individual event rows, to have them available for slice and dice analytics.

like image 95
spencer7593 Avatar answered Oct 26 '25 18:10

spencer7593