Skip to content
Advertisement

Purpose of Secondary Key

What is the purpose of the Secondary key? Say I have a table that logs down all the check-ins (similar to Foursquare), with columns id, user_id, location_id, post, time, and there can be millions of rows, many people have stated to use secondary keys to speed up the process.

Why does this work? And should both user_id and location_id be secondary keys?

I’m using mySQL btw…

Edit: There will be a page that lists/calculates all the check-ins for a particular user, and another page that lists all the users who has checked-in to a particular location

mySQL Query

Type 1

SELECT location_id FROM checkin WHERE user_id = 1234 

SELECT user_id FROM checkin WHERE location_id = 4321

Type 2

SELECT COUNT(location_id) as num_users FROM checkin

SELECT COUNT(user_id) as num_checkins FROM checkin

Advertisement

Answer

The key (also called index) is for speeding up queries. If you want to see all checkins for a given user, you need a key on user_id field. If you want to see all checking for a given location, you need index on location_id field. You can read more at mysql documentation

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement