When I have do some sql tody, some confusion come up to me.
Its about the index && PRIMARY KEY && UNIQUE KEY in MySQL. So I google it for the answers. There is a clearly answer on the
*. So I share it on this BLOG.
About INDEX:
Firstly, we should understand KEY and INDEX are synonyms in MySQL. They mean the same thing.
You may have the quersion : what is exactly the INDEX mean ?
Here is a shortcut about the INDEX:
In databases you would use indexes to improve the speed of data retrieve. An index is typically created on columns used in
JOIN, WHERE, and ORDER BY clauses.
There is an example about INDEX so you can understand it better :
Imagine you have a table called users
and you want to search for all the users which have the last name 'Smith'. Without an index, the database would have to go through all the records of the table: this is slow, because the more records you have in your database, the more work it has to do to find the result. On the other hand, an index will help the database skip quickly to the relevant pages where the 'Smith' records are held. This is very similar to how we, humans, go through a phone book directory to find someone by the last name: We don't start searching through the directory from cover to cover, as long we inserted the information in some order that we can use to skip quickly to the 'S' pages.
About PRIMARY KEY :
Primary keys and unique keys are similar. A primary key is a column, or a combination of columns, that can uniquely identify a row.
the five rules of primary key :
1. The data in a primary key can't be repeated. (Because primary key is a special kind of unique key)
2. A primary key must have a value.
3. The primary key must be set when a new row is inserted.
4. A primary key must be as efficient as possible.
5. The value of a primary key can't be changed
About UNIQUE KEY:
When you specify a unique key on a column, no two distinct rows in a table can have the same value.
The columns in which no two rows are similar .
Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.
Primary key does not allow null value but unique key allows null value.