Primary Key in DBMS

Ayushi Trivedi Last Updated : 18 Jun, 2024
5 min read

Introduction

With a focus on data integrity and effective retrieval, this article offers a thorough description of primary keys in a database management system (DBMS). It covers types of primary keys, their creation and implementation, and practical applications. The article also discusses best practices for choosing and managing primary keys, highlighting their advantages like uniqueness, referential integrity, performance enhancement, and simplified database design.

Overview

  • Learn the role of primary keys play in maintaining data integrity and speedy data retrieval.
  • Recognize scenarios where each type of primary key is appropriate.
  • Create primary keys during the initial table creation.
  • Maintain consistency and minimalism in primary key selection.
  • Understand how primary keys simplify database design and improve data security.
Primary Key in DBMS

What is Primary Key in DBMS?

An essential component of a DBMS that is necessary for relational database design and administration is the primary key. It guarantees the uniqueness of every record in a database, protecting data integrity and enabling speedy data retrieval.

A primary key is a column, or a set of columns, in a database table that uniquely identifies each row in that table. The primary key must contain unique values and cannot contain null values.

Purpose of Primary Key

  • Uniqueness: makes ensuring that the value of the primary key column (or columns) in a table is unique across all rows.
  • Integrity: guarantees the unique identity of every record, hence upholding entity integrity.
  • Indexing: Often automatically indexed by the database system, which speeds up query performance.
  • Relationships: Serves as a reference point for foreign keys in other tables, helping to establish relationships between tables.

Characteristics of Primary Keys

  • Unique Values: Each value in the primary key column(s) must be unique.
  • Non-null: Primary key columns cannot contain null values.
  • Immutable: The values in a primary key should not change over time.
  • Minimal: Composed of the smallest number of columns necessary to ensure uniqueness.

Types of Primary Keys

Let us now explore types of primary keys in detail and with example.

Single-Column Primary Key

A single-column key is the main key of a database table that has just one column. This column ensures that each entry in the table is distinct and that no two rows have the same value. The simplest kind of primary key is a single-column key, which is frequently employed when a record can be identified just by one feature.

CREATE TABLE employees (
    employee_id INT PRIMARY KEY,
    name VARCHAR(50),
    position VARCHAR(50)
);

Composite Primary Key

A composite primary key is a primary key in a database table that has two or more columns. By combining these columns, it is possible to identify each entry in the table individually. When a single column is insufficient to guarantee each record’s uniqueness, composite primary keys are employed. When used in junction tables and many-to-many connection tables, this kind of primary key is quite helpful.

CREATE TABLE orders (
    order_id INT,
    product_id INT,
    PRIMARY KEY (order_id, product_id)
);

Creating a Primary Key

Let us now learn to create a primary key.

During Table Creation

You can specify a primary key right in the CREATE TABLE line when making a new table. This guarantees that as soon as the table is formed, the primary key constraint is implemented.

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    birthdate DATE
);

By defining the primary key during table creation, the database ensures from the outset that every student has a unique student_id, which helps maintain data integrity and optimizes query performance.

Adding to an Existing Table

If a table doesn’t already contain a primary key constraint, it can be added with the ALTER TABLE statement. This comes in handy when you realize you need a primary key constraint after the table has been created and loaded with data.

ALTER TABLE students
ADD CONSTRAINT pk_student_id PRIMARY KEY (student_id);

The database guarantees that the student_id column now enforces uniqueness and non-null values by adding the primary key constraint to an existing table. This may require verifying and maybe changing existing data to comply with these constraints.

Example

Consider a simple database with two tables: students and enrollments. Each student has a unique student_id and can enroll in multiple courses.

Students Table

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    birthdate DATE
);

Enrollments Table

CREATE TABLE enrollments (
    enrollment_id INT PRIMARY KEY,
    student_id INT,
    course_id INT,
    FOREIGN KEY (student_id) REFERENCES students(student_id)
);

Inserting Data into the Students Table

INSERT INTO students (student_id, name, birthdate) VALUES
(1, 'Alice Johnson', '2000-05-15'),
(2, 'Bob Smith', '1999-11-23'),
(3, 'Charlie Brown', '2001-02-10');

Inserting Data into the Enrollments Table

INSERT INTO enrollments (enrollment_id, student_id, course_id) VALUES
(101, 1, 101),
(102, 2, 101),
(103, 1, 102),
(104, 3, 102);

Retrieving Data

Now, let’s retrieve data from both tables to see the output:

Query to Retrieve Data

SELECT * FROM students;

Output:

+------------+---------------+------------+
| student_id | name          | birthdate  |
+------------+---------------+------------+
| 1          | Alice Johnson | 2000-05-15 |
| 2          | Bob Smith     | 1999-11-23 |
| 3          | Charlie Brown | 2001-02-10 |
+------------+---------------+------------+

Query to Retrieve Data from Enrollments Table

SELECT * FROM enrollments;

Output:

+---------------+------------+-----------+
| enrollment_id | student_id | course_id |
+---------------+------------+-----------+
| 101           | 1          | 101       |
| 102           | 2          | 101       |
| 103           | 1          | 102       |
| 104           | 3          | 102       |
+---------------+------------+-----------+

Best Practices

  • Choose Natural Keys When Possible: Use the primary key if there is a naturally occurring unique attribute (such as the Social Security number or the ISBN for publications).
  • Use Surrogate Keys When Necessary: Use a surrogate key (such as an auto-incremented integer) if there isn’t a natural key.
  • Consistency: Keep the primary keys’ names constant across all tables.
  • Normalization: To prevent redundancies and dependence problems, make sure the database is appropriately normalized.

Advantages of Primary Key in DBMS

Here are the key advantages of using primary keys in a Database Management System, summarized in simple points:

  • Uniqueness
    • Ensures each record is uniquely identifiable.
    • Prevents duplicate records.
  • Efficient Data Retrieval
    • Automatically indexed by the DBMS.
    • Speeds up search queries.
  • Supports Referential Integrity
    • Used to establish relationships between tables.
    • Maintains data integrity through foreign keys.
  • Prevents Null Values
    • Primary keys cannot contain null values.
    • Ensures every record has a valid identifier.
  • Data Integrity and Consistency
    • Enforces unique and non-null constraints.
    • Maintains consistent data across the database.
  • Simplifies Database Design
    • Provides a clear structure for the database.
    • Easier to understand and manage the database schema.
  • Enhances Performance
    • Optimizes queries that filter, join, or sort data.
    • Improves overall database performance.
  • Supports Data Integrity in Distributed Systems
    • Ensures unique identification across different nodes.
    • Useful in distributed databases.
  • Facilitates Updates and Deletions
    • Efficient and straightforward to update or delete records.
    • Avoids ambiguity in data modifications.
  • Enables Data Consistency Across Transactions
    • Ensures consistent operations in transactions.
    • Important for transactional integrity.
  • Provides a Foundation for Normalization
    • Essential for reducing redundancy.
    • Helps in organizing data logically.
  • Enhances Data Security
    • Improves access control mechanisms.
    • Ensures only authorized modifications.

Conclusion

In relational database architecture, primary keys play a critical role in guaranteeing data integrity, uniqueness, and quick retrieval. To guarantee consistency between records, they are defined during the construction or updating of tables. They improve database speed and maintain referential integrity. Following best practices results in a more robust and dependable DBMS by streamlining database design, enhancing performance, and fortifying data security.

Frequently Asked Questions

Q1. What is a primary key in a DBMS?

A. A primary key guarantees that every entry in a database table is distinct by acting as a unique identifier for each record. It is used to maintain entity integrity and speed up effective data retrieval; it cannot include null values.

Q2. Why is a primary key important?

A. A primary key preserves data integrity, guarantees record uniqueness, and facilitates effective querying. Additionally, it strengthens the relational database structure by establishing associations between tables via foreign keys.

Q3. Can a primary key contain null values?

A. No, null values are not allowed in a primary key. In order to guarantee the integrity and uniqueness of the data, every value in a primary key column needs to be distinct and not null.

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details