Our MySQL database has a users table with a logged_in, BOOL column which is set when a user is detected to log in or out.
On our website we would display “users logged in to application”, but I’m wary of simply doing SELECT COUNT(*) FROM users WHERE logged_in = 1 for performance reasons.
We expect the users table might have a few thousand rows, but only a handful (say 20) of users would be logged in at any time.
Is there a way to make sure this query can be optimized in MySQL, perhaps involving a KEY or a VIEW? Or do I need to create an auxillary table like logged_in_users along-side users and update this as well?
logged_init should be a very fast query since the number of those being logged in will be pretty small comapred to the whole user table (a logged_in = 0 might not be very efficient however 🙂 ) This is one of those cases where an index on a column with only 2 possible values can make for super efficient queries for one of the values.count(*), do acount(your_primary_key). That way if you have logged_in indexed, the entire query is covered for optimal performance.