Database Keys
Learn how to create database keys and their representation.
In a relational database, a key is a column or a set of columns that uniquely identifies each row in a table. Without keys, data can become inconsistent, duplicate records can appear, and searching for specific information becomes slow.
Let’s see why we need keys with a real-world example. Imagine running an online store. Your store has grown rapidly, and you now manage thousands of customers, products, and orders. One day, a customer calls in, asking about their recent purchase. You search the customer table but find two records with the same names.
Name | Phone Number | |
Emily Clark | emily@example.com | 123-456-7890 |
John Doe | john@example.com | 987-654-3210 |
Emily Clark | emily1@example.com | 123-456-7890 |
The same name, Emily Clark, appears twice with different emails.
A phone number is shared between two different email addresses.
There is no way to uniquely identify each customer without confusion.
Having a unique column helps, but uniqueness isn’t limited to just a single column. A key can consist of one or multiple columns, ensuring each row remains distinct in the table.
Let’s discuss how we can identify the unique columns:
Identifying unique column
Let’s look at the following customer table. Can you identify which column(s) should have unique values?
Name | Phone Number | |
Emily Clark | emily@example.com | 123-456-7890 |
John Doe | john@example.com | 987-654-3210 |
Emily Clark | emily1@example.com | 123-456-7890 |
Can you spot the problem?
Let’s modify this table and make sure the unique data.