View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
SQL

SQL Tutorial: Learn Structured…

  • 81
  • 9 Hours

Primary Key In SQL: A Complete Guide in 2024

Updated on 30/01/2025464 Views

Overview

A Primary Key in SQL is like a unique ID for each row in a table. Combining more than one attribute to create this unique ID is called a Composite Primary Key in SQL. Each table can only have one Primary Key, which must be different for each row and can't be empty.

What is SQL Primary Key?

A Primary Key in SQL is a single or group of columns that identify each record in any database table. It also speeds up data access and is used to build relationships between tables. Let's take an example: suppose you are developing an application called a "customer management system" to manage all the customer data of member-only resorts.

This data can include personal details, member-assigned IDs, and other details of the members it has opted for. Hence, this field will be the Primary Key.

This diagram shows a table called CUSTOMERS, which stores personal information about customers. Each customer has a unique identification number called CUST_ID, which is the primary way we identify them in the table. We can find all the details about a specific customer with this number.

But there are a few points to remember from the perspective of the "Primary Key in SQL."

  • It comprises unique values
  • It can't be a null
  • The most important thing is that one table only has one primary key
  • A primary key cannot be more than 900 bytes

Now, let's further understand the benefits of the Primary Key in SQL.

Benefits of an SQL Primary Key

There are two significant advantages of a Primary Key in SQL, which are as follows:

  • It identifies each row of the table in a unique way
  • It gets a unique index for each primary key column that helps in accessing faster.

Now further, let's understand what the Purpose of SQL Primary Key is

What is The Purpose of Using SQL Primary Key?

Choosing the right Primary Key in SQL is crucial when designing a database. A primary key ensures that each record in a table is unique.

The primary key helps when we're searching for specific data. We pick a primary key based on the type of searches we'll do most often to ensure we can find the data quickly.

Let's say we're creating a database for a college to keep track of students. We'll store their names, ages, GPAs, roll numbers, and sections.

Here's what the student table looks like:

Roll_no

CGPA

Name

Section

1

9.21

Amit

A

2

8.86

Mohit

A

13

9.21

Ishan

B

24

9.71

Akshay

5

8.56

Mohit

B

So based on the above table, we can see that there are no duplicate values, as well as there is no null value in the Roll_no column, but there are duplicate or null values present in the CGPA, Name, and Section columns.

Now, let's understand how you can create an SQL Primary Key.

Creating a SQL Primary Key

When making a table using the CREATE TABLE command, you can choose one column as the primary key. This column will uniquely identify each row in the table.

Here's a more straightforward way to say the syntax:

When creating a table, you can pick one column as the primary key. This column will have unique values for each row in the table. You need to write the column name followed by "PRIMARY KEY." Let's understand how we can create a Primary Key in SQL. Below is an example

Syntax

CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
column datatype,
PRIMARY KEY(column_name)
);

Example

In the below example, we will create a table named CUSTOMERS with various fields in an SQL database. We'll add the constraint "Primary Key" to the column named ID.

CREATE TABLE CUSTOMERS (
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE IS NOT NULL,
ADDRESS CHAR (25),
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

Verification

Since each primary key value must be unique, you can't add a record with the same ID as an existing one. To check if the ID constraint works, we'll insert records with duplicate ID values and see if it allows us to do so.

Let's start by adding some information to the CUSTOMERS table.

INSERT INTO CUSTOMERS VALUES (3, 'kaushik,' 23, 'Kota,' 2000.00);

Now, let's insert one more record with the same ID –

INSERT INTO CUSTOMERS VALUES (3, 'Chaitali,' 25, 'Mumbai,' 6500.00);

As we said earlier, each value must be unique when a column is set as the Primary Key. So, when we try to add a new record with a value already in the Primary Key column, the system will give an error message.

Likewise, a primary key column can't be empty (NULL). Here, we're trying to add a record where the primary key column (ID) doesn't have any value assigned to it.

INSERT INTO CUSTOMERS VALUES (null, 'Komal,' 22, 'Hyderabad,'' 4500.00);

Now, next, let us discuss and understand the Impact of Primary Key Selection on Database Performance.

Impact of Primary Key Selection on Database Performance

Some of the impacts that primary key selection can have on database performance are:

  • The selection of a Primary Key in SQL significantly influences database performance.
  • Consideration of the chosen primary key's impact on data access and query execution efficiency is crucial.
  • Optimal primary key selection can enhance indexing efficiency and minimize storage requirements.
  • High cardinality and minimal data type size are desirable attributes for primary keys to improve query performance.

Now, further, let us discuss the strategies for optimizing primary key choices.

Strategies For Optimizing Primary Key Choices

Here are the strategies to optimize primary key choices:

  • Evaluate trade-offs between natural and surrogate keys to optimize primary key choices.
  • Surrogate keys, such as auto-incrementing integers, are often preferred for simplicity and stability.
  • Select primary keys that minimize data redundancy, promote data integrity, and maximize query performance.
  • Consider factors such as uniqueness, immutability, and ease of indexing when selecting primary keys.

Best Practices for Managing Primary Key Constraints in Large-Scale Database Systems

You can manage primary key constraints in large-scale database systems in the following ways:

  • Efficient enforcement of primary key constraints with minimal overhead is essential for large-scale database systems.
  • Utilize features like clustered indexes to physically reorder data on disk and improve query performance.
  • Scale primary key management in distributed systems with techniques like data partitioning and replication.
  • Partition data across multiple nodes and replicate data for improved workload distribution and fault tolerance.

Insights Into Primary Key Indexing Techniques and Implications for Query Performance

Some of the features of primary key indexing techniques and their impact on query performance are detailed below:

  • Understanding primary key indexing techniques is crucial for optimizing query performance.
  • Clustered indexes physically reorder data on disk based on the primary key for fast retrieval.
  • Non-clustered indexes store index entries separately from the data, enabling efficient retrieval based on non-primary key columns.
  • Utilize covering indexes to include all columns referenced in a query within the index itself for improved performance.
  • Implement index optimizations such as index statistics maintenance and index fragmentation management to enhance query execution efficiency.

What is Dropping a SQL Primary Key in SQL Using Alter Primary Key SQL Server?

When adding a Primary Key Constraint to a column in any table, it allows you to drop it as well. This is done by leveraging the Alter Table statement.

To remove the main identifier rule from a table column, you can use the ALTER TABLE statement with this syntax:

Syntax

ALTER TABLE table_name DROP PRIMARY KEY;

Now, let’s quickly understand this with a simple example.

Let us take the CUSTOMERS table, which we have created as a primary key constraint in a column named ID. You can drop it from the column ID by implementing the below syntax –

ALTER TABLE CUSTOMERS DROP PRIMARY KEY;

Let’s see how the output looks.

The above-stated SQL query would generate the below output

Output

Query OK, 1 row affected (0.03 sec)
Records: 1 Duplicates: 0 Warnings: 0

Verification

When we remove the main identifier from the column called ID, we're able to add many records with the same ID. This statement adds four records with identical IDs.

INSERT INTO CUSTOMERS VALUES

(3, 'Chaitali', 25, 'Mumbai', 6500.00),

(3, 'Hardik', 27, 'Bhopal', 8500.00),

(3, 'Komal', 22, 'Hyderabad', 4500.00),

(3, 'Muffy', 24, 'Indore', 10000.00);

When you verify the content of the above table, you will find multiple records with the same ID.

SELECT * FROM CUSTOMERS;

Doing this will show a table like,

ID

Name

Age

Address

Salary

33

Rajvi

23

Kota

4000

33

Anjali

24

Ahmedabad

8000

33

Hardik

25

Rajgadh

6000

33

Rahul

26

Ahmedabad

10000

33

Kaushik

27

Indore

4000

Now, after learning how to Create and Crop the Primary Key in SQL, let’s understand the difference between a Primary Key and a Composite Key.

What is the Difference Between a Composite and Primary Key in SQL?

A unique key or a composite key is like a special rule in a database table that helps identify records. It's used to make sure that certain columns or groups of columns have different values in each row, but it's not the main identifier like a primary key.

We use unique keys when we already have a primary key in a table. Unlike primary keys, which there can only be one of, a table can have multiple unique keys.

Below are a few differences between Composite & Primary Key in SQL

- Accepting NULL values: Unique keys can allow NULL values, while primary keys can't.

- Number of keys: A table can only have one primary key, but it can have several unique keys.

- Changing values: Unique keys can be changed directly without having to be removed and recreated.

- Indexes: Unique keys create one type of index, while primary keys create another.

- Relationship: A primary key can also be a unique key, but a unique key can't always be a primary key.

Wrapping Up!

In conclusion, understanding the concept and implementation of primary keys in SQL is crucial for efficient database design and management.

A primary key works for as a unique identifier for each record in a table and ensuring data integrity and facilitating quick data access. It is essential to choose the right primary key, considering factors such as uniqueness, null value acceptance, and index creation.

Additionally, the ability to create, verify, and drop primary keys using SQL commands like CREATE TABLE, ALTER TABLE, and INSERT INTO is essential for database administrators and developers.

Furthermore, recognizing the differences between primary keys, composite keys, and unique keys is vital for designing robust database schemas. While primary keys uniquely identify records, unique keys ensure distinct values in specific columns or column groups.

Frequently Asked Questions:

1. What is the foreign key and primary key in SQL?

A primary key identifies each record in a table while a foreign key establishes a relationship between two tables based on a matching column.

2. How do you create a primary key?

To create a primary key, you specify the column(s) that uniquely identify each record in a table using the "PRIMARY KEY" constraint when defining the table structure.

3. What is the example of a primary key?

An example of a primary key could be a column named "ID" in a table called "Customers," where each ID value uniquely identifies a customer record.

4. Can the primary key be NULL?

No, a primary key cannot be NULL. It must have a unique value for each record in the table.

5. How to delete primary keys in SQL?

You can delete primary keys in SQL by using the "ALTER TABLE" statement with the "DROP PRIMARY KEY" clause.

6. Can we remove the primary key in MySQL?

Yes, you can remove the primary key in MySQL using the "ALTER TABLE" statement with the "DROP PRIMARY KEY" clause.

7. Which command is used to remove foreign keys?

The "ALTER TABLE" statement is used to remove foreign keys.

8. Which clause is used to remove foreign keys?

The "DROP FOREIGN KEY" clause is used to remove foreign keys.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.