
When performing a select query on a database, you’ll likely be specifying a where clause to narrow your results. Searching through a database can be “expensive” (CPU and time intensive). Today we’ll be looking at a case where you can make this search less-expensive.
First of all, let’s talk about a use case for this article. If you want to retrieve a single row from the database, based off a field that will always contain unique data. For example, if you were retrieving a blog post from the database, you might search for it by a unique id.
If you have a use similar to the one described above, you may be able to speed up your select query. By adding a primary key to the described unique field, MySQL will keep an index of these fields for quick searching. This will allow you to perform quick select queries using the primary key field for the where clause.
As you may imagine, this has many use cases. From selecting a blog post by its “url slug”, selecting a product by its id and infinitely so-on.





Metal Briefcase
September 15, 2009 11:53 am
Good tip. I’m sure many people incorrectly setup databases without using primary keys. I never realized that this would increase speed of select queries, but it definitely makes sense.