I’ve recently started developing my first serious application which uses a SQL database, and I’m using phpMyAdmin to set up the tables. There are a couple optional “features” I can give various columns, and I’m not entirely sure what they do:
- Primary Key
- Index
I know what a PK is for and how to use it, but I guess my question with regards to that is why does one need one – how is it different from merely setting a column to “Unique”, other than the fact that you can only have one PK? Is it just to let the programmer know that this value uniquely identifies the record? Or does it have some special properties too?
I have no idea what “Index” does – in fact, the only times I’ve ever seen it in use are (1) that my primary keys seem to be indexed, and (2) I heard that indexing is somehow related to performance; that you want indexed columns, but not too many. How does one decide which columns to index, and what exactly does it do?
edit: should one index colums one is likely to want to ORDER BY?
Thanks a lot,
Mala
Primary key is usually used to create a numerical ‘id’ for your records, and this id column is automatically incremented.
For example, if you have a
bookstable with anidfield, where theidis the primary key and is also set toauto_increment(Under ‘Extra in phpmyadmin), then when you first add a book to the table, the id for that will become 1’. The next book’s id would automatically be ‘2’, and so on. Normally, every table should have at least one primary key to help identifying and finding records easily.Indexes are used when you need to retrieve certain information from a table regularly. For example, if you have a
userstable, and you will need to access theemailcolumn a lot, then you can add an index on email, and this will cause queries accessing the email to be faster.However there are also downsides for adding unnecessary indexes, so add this only on the columns that really do need to be accessed more than the others. For example,
UPDATE,DELETEandINSERTqueries will be a little slower the more indexes you have, as MySQL needs to store extra information for each indexed column. More info can be found at this page.Edit: Yes, columns that need to be used in
ORDER BYa lot should have indexes, as well as those used inWHERE.