For working professionals
For fresh graduates
More
SQL Tutorial: Learn Structured…
1. SQL Tutorial
2. The Essential Guide To Understanding SQL In DBMS
3. SQL Commands
4. SQL Data Types
5. SQL Aliases
6. SQL INSERT INTO With Examples
7. Master SQL Update
8. SQL Delete Statement: A Complete Overview with Examples
9. SQL Delete Statement Example
10. SQL WHERE Clause
11. SQL AND Operator
12. SQL NOT Operator: A Comprehensive Guide
13. SQL Like
14. SQL Between Operator: A Complete Overview with Examples
15. Difference Between SQL and MySQL: Get to Know Your DBMS
16. MySQL Workbench
17. A Comprehensive Guide to MySQL Workbench Installation and Configuration
18. Mastering SQL: Your Comprehensive Guide to Becoming an SQL Developer
19. SQL CREATE TABLE With Examples
20. How To Add Columns In SQL: A Step-By-Step Guide
21. Drop Column in SQL: Everything You Need to Know
22. Index in SQL
23. Constraints in SQL: A Complete Guide with Examples
24. Schema in SQL
25. Entity Relationship Diagram (ERD) - A Complete Overview
26. Foreign Key in SQL with Examples
27. An Ultimate Guide to Understand all About Composite Keys in SQL
28. Normalization in SQL
29. Better Data Management: The Efficiency of TRUNCATE in SQL
30. Difference Between DELETE and TRUNCATE in SQL
31. SQL ORDER BY
32. SQL Not Equal Operator
33. SQL Intersect Operator: A Comprehensive Guide
34. SQL Union: Explained with Examples
35. SQL Case Statement Explained with Examples
36. Unleashing the CONCAT Function In SQL: String Manipulation Made Easy
37. Understanding and Mastering COALESCE in SQL
38. NVL in SQL
39. Understanding SQL Date Formats and Functions
40. DateDiff in SQL: A Complete Guide in 2024
41. SQL Wildcards
42. SQL DISTINCT: A Comprehensive Guide
43. LIMIT in SQL: A Comprehensive Tutorial
44. SQL Aggregate Functions
45. GROUP BY in SQL
46. SQL HAVING
47. EXISTS in SQL
48. SQL Joins
49. Inner Join in SQL
50. Left Outer Join in SQL
51. Full Outer Join in SQL
52. Cross Join in SQL
53. Self Join SQL
54. Left Join in SQL
55. Mastering SQL Substring
56. Understanding the ROW_NUMBER() Function in SQL
57. Cursor in SQL
58. Triggers In SQL
59. Stored Procedures in SQL
60. RANK Function in SQL
61. REPLACE in SQL
62. How to Delete Duplicate Rows in SQL
63. Transact-SQL
64. INSTR in SQL
65. PostgreSQL vs MySQL: Explore Key Differences
66. Mastering SQL Server Management Studio (SSMS): A Comprehensive Guide
67. Auto-Increment in SQL
68. Unveiling the Power of SQL with Python
69. SQL Vs NoSQL: Key Differences Explained
70. Advanced SQL
71. SQL Subquery
72. Second Highest Salary in SQL
73. Database Integrity Constraints: Everything You Need to Know
74. Primary Key In SQL: A Complete Guide in 2024
Now Reading
75. A Comprehensive Guide on View in SQL
76. Understanding PostgreSQL: A Complete Tutorial
77. SQL Injection Attack
78. MySQL database
79. What is SQLite
80. SQLite
81. ALTER Command in SQL
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.
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."
Now, let's further understand the benefits of the Primary Key in SQL.
There are two significant advantages of a Primary Key in SQL, which are as follows:
Now further, let's understand what the Purpose of SQL Primary Key is
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.
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.
Some of the impacts that primary key selection can have on database performance are:
Now, further, let us discuss the strategies for optimizing primary key choices.
Here are the strategies to optimize primary key choices:
You can manage primary key constraints in large-scale database systems in the following ways:
Some of the features of primary key indexing techniques and their impact on query performance are detailed below:
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.
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.
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.
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.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.