
In MySQL, a primary key is a field that uniquely identifies each record in a table. For instance, student_id, employee_id, client_id, country_id, and more. When you join two or more columns to make the primary identifier, it is referred to as a composite key. On the other hand, an index is a data structure that increases the performance of the database when searching records. Indices adopt rapid intelligent lookup and processing algorithms to efficiently scan records. When you define a column with the primary key attribute, MySQL automatically creates an index for speed purposes.
In a mission-critical application, your database might contain many related tables. For the database to operate effectively, the only way to clearly define the relationships between the tables is by using primary keys, indices, and composite keys. MySQL only allows one primary key per table but you can have as many indices as you want. Also, a primary key field can not accept duplicates or null values.
In this guide, you'll learn how to create primary keys, indices, and composite keys on your MySQL server.
To follow along with this guide, you need a MySQL database server and user account.
In this step, you'll set up a database.
Log in to your MySQL server and run the command below to create a sample_db database.
Output.
Switch to the new sample_db database.
Output.
With the sample database created, you can now start creating the different MySQL keys in the following steps.
Your database should have the correct keys from the ground up to avoid issues as your data grows. Therefore, you should plan ahead and identify the primary key column and any other columns that you want to index. In this step, you'll create a single-column-based primary key and index on a table.
Create an employees table. This table will contain four columns. Define the employee_id as the unique column using the PRIMARY KEY statement. Then, use the AUTO_INCREMENT keyword to allow MySQL to generate the next employee_id in the series every time you INSERT a new record. Next, index the phone column using the statement INDEX(phone).
Output.
To ensure your table has the right indices, run the following command.
You should get the following output.
Next, INSERT a record into the employees table to test if everything is working as expected.
Output.
Query the employees table to make sure the data is in place.
Output.
Attempt to violate the PRIMARY KEY unique constraint by adding an employee with an existing employee_id of 1.
You should get the following error since MySQL does not accept duplicate values on the PRIMARY KEY columns.
In the previous step, your primary key and indices were based on a single column. MySQL also supports composite keys. These are unique keys that use a combination of two or more columns to uniquely identify each record. For instance, consider a case where you want to store vendors' names and the products they supply on a single table. In this scenario, every distinct vendor can only have a single record for each unique product they supply.
To understand the above use-case better, create the products_to_vendors table using the statement below. In the table, use the statement PRIMARY KEY(vendor_name, product_name) to set up the vendor_name and product_name as a multi-column PRIMARY KEY.
Output.
Make sure you have got the right indices.
Output.
Next, INSERT the following sample records into the products_to_vendors table.
Output.
List the records from the products_to_vendors table.
Output.
Attempt inserting a record that violates the composite key columns.
MySQL server should now throw the following error.
However, since the same product(WIRELESS MOUSE) can be supplied by a different vendor, the following statement should succeed.
Output.
Sometimes, you might forget to define keys when creating tables or find yourself in a situation where you want to index a column during the development process to speed up queries on your rapidly growing database. Luckily, MySQL provides you with the functionalities of creating keys on existing tables using the ALTER TABLE statement.
Create a products table without specifying any keys.
Output.
Ensure you've not accidentally defined any indices by running the following statement.
Output.
Now, to define the product_id as the PRIMARY KEY in the products table, run the following statement.
Output.
Next, use the following command to index the product_name column.
Output.
Then, query the INFORMATION_SCHEMA database again to see if you've enforced the new keys.
The output below confirms your indices are in place.
In every application, adding indices into your database tables allows you to:
Easily locate and identify records in large tables. For instance, if you have 1,000 employees on a table and you just want to locate a single staff member information, you can use their employee_id to look them up.
Prevent duplicate entries. In most business transactions, duplicate records may lead to losses due to conflicting data. Since a primary key column does not allow duplicate entries, it is a good bet when it comes to validating data.
Update and delete records. MySQL requires a unique key in a WHERE clause to look up, and UPDATE or DELETE a single record.
Define unique constraints and link related tables together. For instance, if you want to enforce referential integrity in your database, it would be impossible without using foreign keys.
This guide has focused on creating primary keys, indices, and composite keys on your MySQL server. While this is not a conclusive list of using MySQL indices, it should give you a good foundation to work with databases keys as a beginner.
0 Comments
Be the first to comment and share your perspective with the community.