0
0
SQLquery~3 mins

Why Composite primary keys in SQL? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if one key isn't enough to find your data? Discover how combining keys solves this puzzle!

The Scenario

Imagine you have a big notebook where you write down orders from customers. Each page has a customer name and a product name. To find a specific order, you try to remember just the customer or just the product, but many pages have the same customer or the same product. It becomes very hard to find the exact order you want.

The Problem

Using only one piece of information like customer name or product name to find orders is slow and confusing. You might pick the wrong order because many orders share the same customer or product. Writing down extra notes to keep orders unique is messy and easy to make mistakes.

The Solution

Composite primary keys let you use two or more pieces of information together to uniquely identify each order. This means you can quickly and correctly find the exact order by looking at both customer and product together, avoiding confusion and mistakes.

Before vs After
Before
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerName VARCHAR(50), ProductName VARCHAR(50));
After
CREATE TABLE Orders (CustomerName VARCHAR(50), ProductName VARCHAR(50), PRIMARY KEY (CustomerName, ProductName));
What It Enables

It enables precise and reliable identification of records using multiple related fields, making data management clearer and safer.

Real Life Example

In a school, a student's grade in a subject is unique only when you know both the student and the subject. Using a composite primary key with student ID and subject ID ensures each grade record is unique and easy to find.

Key Takeaways

Composite primary keys use multiple columns to uniquely identify records.

This prevents confusion when one column alone is not unique.

It helps keep data accurate and easy to search.