I’ll continue today with another good database programming article. If you missed yesterdays, you may view it here.
Today’s article will discuss when to use a static COUNT() versus a dynamic COUNT(). On a regular basis we are tasked with creating a message center or a photo album and we need to display a count of new messages or pictures in the album.
The obvious solution is to do a simple query: SELECT COUNT(*) FROM pictures WHERE album_id = 1 and display the result beside our album name. Now, let’s assume that we allow multiple albums our actual query would be closer to this: SELECT albums.*, COUNT(pictures.*) as picture_count FROM albums INNER JOIN pictures ON albums.id = pictures.album_id WHERE albums.id = 1. This will of course work, but let me show you a better, more practical approach that will improve performance significantly on large databases. (more…)