Primary Key And Composite Key In Sql

6 min read

Introduction: Primary Key and Composite Key in SQL

A primary key and composite key in SQL are essential database concepts used to uniquely identify records in a table. On the flip side, understanding them helps you design cleaner tables, prevent duplicate data, create reliable relationships between tables, and build SQL databases that are easier to maintain. Whether you are learning database management, preparing for interviews, or designing an application backend, knowing when to use a single-column primary key versus a multi-column composite key is an important skill Practical, not theoretical..

What Is a Primary Key in SQL?

A primary key is a column, or a set of columns, that uniquely identifies each row in a database table Simple, but easy to overlook..

Take this: in a students table, each student may have a unique student_id. That student_id can be used as the primary key because no two students should have the same value.

Characteristics of a Primary Key

A primary key must follow these rules:

  • It must contain a unique value for every row.
  • It cannot contain NULL.
  • A table can have only one primary key.
  • It is commonly used to create relationships with other tables through foreign keys.
  • Most database systems automatically create an index on the primary key.

Example:

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    last_name VARCHAR(50),
    email VARCHAR(100)
);

In this table, student_id is the primary key. Each student record must have a unique student_id, and the value cannot be empty or NULL.

Why Primary Keys Are Important

Primary keys are important because they provide a reliable way to identify records. Without a primary key, it becomes difficult to distinguish between two rows that contain similar or identical data Less friction, more output..

Take this: two students may have the same name:

Ahmad Ali
Ahmad Ali

If names are used as identifiers, the database may confuse one student with another. A primary key solves this problem by assigning each student a unique identifier.

Common Uses of Primary Keys

Primary keys are used to:

  • Uniquely identify each record in a table.
  • Improve data retrieval speed through indexing.
  • Create relationships between tables.
  • Prevent duplicate records.
  • Support data integrity and consistency.
  • Make updates and deletes more accurate.

To give you an idea, if you want to update the email address of one student, you can use the student_id to make sure you update the correct record But it adds up..

UPDATE students
SET email = 'newemail@example.com'
WHERE student_id = 101;

What Is a Composite Key in SQL?

A composite key is a primary key or unique key made up of two or more columns. It is used when one column alone is not enough to uniquely identify a row Which is the point..

Here's one way to look at it: imagine a table that stores exam results. A student may take many exams, and each exam may be taken by many students. To identify a specific result, you may need both student_id and exam_id.

CREATE TABLE exam_results (
    student_id INT,
    exam_id INT,
    score INT,
    exam_date DATE,
    PRIMARY KEY (student_id, exam_id)
);

In this example, the primary key is composite because it contains two columns:

student_id + exam_id

Neither student_id nor exam_id alone may be unique, but together they identify one specific exam result Practical, not theoretical..

Primary Key vs Composite Key

The main difference between a primary key and a composite key is the number of columns used to identify a row.

Feature Primary Key Composite Key
Number of columns Usually one column Two or more columns
Purpose Uniquely identifies a row Uniquely identifies a row using combined values
NULL values Not allowed Not allowed in any key column
Number per table Only one primary key Can be part of the primary key or a separate unique constraint
Example student_id student_id + course_id

A composite key can also be a primary key. In plain terms, a composite primary key is a type of primary key that uses more than one column.

How a Composite Primary Key Works

A composite primary key works by combining the values of multiple columns to create uniqueness It's one of those things that adds up..

For example:

CREATE TABLE enrollments (
    student_id INT,
    course_id INT,
    enrollment_date DATE,
    PRIMARY KEY (student_id, course_id)
);

This table allows the following:

student_id = 1, course_id = 101
student_id = 1, course_id = 102
student_id = 2, course_id = 101

But it does not allow this duplicate combination:

student_id = 1, course_id = 101
student_id = 1, course_id = 101

The database checks the combination of both columns, not each column individually Not complicated — just consistent..

Example: Single Primary Key

A single primary key is best when one column can naturally and permanently identify each row.

CREATE TABLE customers (
    customer_id INT PRIMARY KEY,
    customer_name VARCHAR(100),
    phone VARCHAR(20),
    city VARCHAR(50)
);

Here, customer_id is the only primary key. It is simple, efficient, and easy to reference from other tables.

A related table may use customer_id as a foreign key:

CREATE TABLE orders (
    order_id INT PRIMARY KEY,
    customer_id INT

```sql
    FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);

When to Use a Composite Key

Composite keys shine when the natural identifier of an entity consists of multiple attributes. Common scenarios include:

  • Associative tables (many-to-many relationships) like student_id + course_id
  • Time-series data where device_id + timestamp uniquely identifies a reading
  • Geographic data using country_code + postal_code

That said, composite keys add complexity. Joins become more verbose, and ORM frameworks sometimes struggle with multi-column references Which is the point..

When to Use a Surrogate Key Instead

A surrogate key is an artificial column (usually id SERIAL or UUID) that stands in for natural keys. Consider surrogate keys when:

  • Natural keys are wide (many columns or long strings)
  • Business rules might change (a student ID format could change, but the internal ID remains stable)
  • You need simple foreign key references across many tables
CREATE TABLE enrollments (
    enrollment_id SERIAL PRIMARY KEY,
    student_id INT,
    course_id INT,
    enrollment_date DATE,
    UNIQUE (student_id, course_id)
);

Here, enrollment_id serves as the primary key, while the combination of student_id and course_id remains unique through a constraint No workaround needed..

Performance Considerations

Composite keys create composite indexes. While efficient for queries filtering on the leading columns, they can waste space if you frequently query only the second column without the first.

-- Efficient: uses the index
SELECT * FROM enrollments WHERE student_id = 5 AND course_id = 101;

-- Less efficient: may require index scan
SELECT * FROM enrollments WHERE course_id = 101;

Best Practices

  1. Keep keys narrow: Use integers or short strings rather than UUIDs or long text fields
  2. Consider immutability: Choose columns that won't change over time
  3. Document constraints: Clearly comment why a composite key exists
  4. Test query patterns: Ensure your common filters align with the key order

Conclusion

Choosing between a single primary key and a composite key depends on your data model and access patterns. Composite keys naturally enforce uniqueness across multiple attributes and eliminate the need for artificial identifiers, but they introduce complexity in joins and indexing. Surrogate keys offer simplicity and stability but require additional unique constraints to maintain data integrity.

The best approach often combines both: use a surrogate key as the primary key for foreign key relationships, while applying a unique constraint on the natural composite key to prevent duplicate business records. This hybrid strategy gives you the referential simplicity of single-column keys with the semantic accuracy of composite uniqueness.

Some disagree here. Fair enough.

Just Dropped

Latest Batch

In the Same Zone

Picked Just for You

Thank you for reading about Primary Key And Composite Key In Sql. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home