Overview
![]()
Keys are a very important part of the database management system. They uniquely identify a record or a row and establish relationships between them. There are many types of keys in DBMS but two of the main keys are- Primary key and the foreign key. A Primary key is used to uniquely identify each row in a table. Foreign keys are referenced from a primary key from another table.
Scope
- This article deals with primary keys vs foreign keys in SQL and when should they be used.
- We will comprehend what are primary and foreign keys along with their examples and use cases.
Introduction
While creating a database, have you often wondered what all things should be added and taken care of? There are many things that need to be taken into consideration. Suppose, you have created a table, and you want that the records should be uniquely identified by us. In order to solve such a dilemma, keys play a very significant role in a database management system. Let us comprehend them in the next section.
What are the keys in DBMS?
Keys are a very important part of the database management system. Keys uniquely identify a record or a row of a table. But, the above is not the mere purpose of keys. There are other purposes that are sufficed by different types of keys. The types of keys are-
- Primary key
- Super key
- Candidate key
- Foreign key
- Alternate key
- Compound key
- Surrogate key
In this article, we will understand the concepts of primary key and foreign key in the database management system.
What is a Primary key?
A primary key is used to uniquely identify a record in a table. Primary keys must have unique values. They cannot contain null values. It is also necessary that there is only one primary key in the entire table.
The main advantage of the primary key is its uniqueness which leads to faster data access. When multiple fields are used as a primary key, they are known as composite keys.
Purpose of a Primary key
The primary key plays a very significant role in the data table of a relational database. Every table should have a primary key which should be based on a single attribute or multiple attributes.
Benefits of primary key-
- They are used to prevent duplicate records in a table.
- They ensure that the value is not null.
- It is helpful in identifying unique data.
- It is also beneficial to establish a relationship between tables.
- A primary key can become a foreign key also.
How to create a Primary key
To create a primary key, we use the PRIMARY KEY clause with the CREATE TABLE statement. We can also use the ALTER TABLE clause to change a primary key after it has already been created.
Let us create a primary key in the given example-
We will create a table of Students to store their ids, name, and marks. Here the id will be the primary key. The attribute which has to be declared as a primary key should have the ‘PRIMARY KEY’ written as a suffix where the attribute is declared in the table.
CREATE TABLE student(
id integer PRIMARY KEY,
name varchar(40),
marks integer
);
Also, it is not mandatory that the primary key should be of numeric type. It can also be of the type of characters and a combination of characters and numbers.
Example of the primary key
Let us look at some examples of primary keys in SQL. We will take a look at some codes-
- Create a primary key on a constraint in a table that already exists.
In order to create a primary key on a constraint in a table that already exists, we use the ALTER TABLE clause in SQL.
ALTER TABLE table_name ADD PRIMARY KEY (attribute);
Note- To use the ALTER TABLE command to add a primary key, it is necessary that the primary key to be made should be beforehand declared as ‘NOT NULL’ so that it does not carry null values. This should have been done when the table was created.
2. Delete a primary key
The deletion of a primary key is a crucial step. It is so because we want to ensure that the data that is being deleted should not cause an impact on the rest of the data.
ALTER TABLE table_name DROP PRIMARY KEY;
What is a Foreign key?
While discussing the benefits of the primary key, you must have noticed that one of the benefits was that it establishes a relation between two tables. Now you must be wondering how. So, in order to make a relation between two tables, we use the primary key and the foreign key.
So, a foreign key is a column or a group of columns that take reference from a primary key present in another table. So, in order to use a foreign key, we need a primary key. Similarly, we need two tables to establish a relation between them.
The table that contains a primary key is known as the parent table and the table that contains a foreign key is known as the child table. A foreign key is sometimes also known as a ‘reference key’.
A foreign key can contain null values. It can also contain duplicate values. A table can have more than one foreign key.
Rules —
In order to create a foreign key the following rules should be followed.
- The foreign key column in the child table should have the same data type as the primary key in the parent table.
- Both tables should be present in the same database.
- The referenced table should contain unique values.
Example of a Foreign Key
Creating a foreign key-
To create a foreign key, we need two tables. We will be creating two tables- a referencing table and a referenced table.
Table 1 Reference table-
We have information like customer id, order name, and order id in a table called Order.
The table can be created as —
CREATE TABLE Order(
C_id int PRIMARY KEY,
O_Name varchar(266),
O_id int
);
Table 2 Referencing table-
We have information like customer id, customer name, and customer bill in a table called Customer.
The table can be created as-
CREATE TABLE Customer(
C_id int,
C_Name varchar(266),
Bill int,
FOREIGN KEY (C_id) REFERENCES Order(C_id)
);
So, when we execute this, two tables will be created and C_id in the Customer table is the foreign key and it is linked on a common attribute C_id.
Difference between Primary key and Foreign key
When to use which key?
You must be in a dilemma that when to use which key. We have summarised the points for you.
The primary key is to be used when we want to have unique values in a column. It is necessary to remember that a table can have only one primary key and the value of a primary key should not be null.
For a foreign key, it should be used when we want to link two tables together. It is done to establish a relation between two tables. A foreign key accepts duplicate and null values.
Первичный ключ (PRIMARY KEY) в SQL
В SQL ограничение PRIMARY KEY используется для уникальной идентификации строк.
Ограничение PRIMARY KEY — это просто комбинация ограничений NOT NULL и UNIQUE. Это означает, что столбец не может содержать повторяющиеся значения, а также значения NULL .
Синтаксис создания первичного ключа:
Здесь столбец college_id имеет первичный ключ. Это означает, что значения этого столбца должны быть уникальными, а также не содержать значения NULL .
Примечание: Синтаксис создания первичного ключа может отличаться в некоторых СУБД.
Ошибка первичного ключа
Если мы попытаемся вставить нулевые или повторяющиеся значения в столбец с первичным ключом, то получим ошибку. Например:
SQL PRIMARY KEY Keyword
The PRIMARY KEY constraint uniquely identifies each record in a table.
A table can have only one primary key, which may consist of one single or of multiple fields.
SQL PRIMARY KEY on CREATE TABLE
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
SQL Server / Oracle / MS Access:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
Note: In the example above there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
SQL PRIMARY KEY on ALTER TABLE
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the following SQL:
MySQL / SQL Server / Oracle / MS Access:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
Note: If you use the ALTER TABLE statement to add a primary key, the primary key column(s) must already have been declared to not contain NULL values (when the table was first created).
SQL Primary Keys
В этом учебном материале вы узнаете, как создать и удалить первичный ключ в SQL, с синтаксисом и примерами.
Что такое первичный ключ в SQL?
В SQL первичный ключ — это отдельное поле или комбинация полей, которые однозначно определяют запись. Ни одно из полей, являющихся частью первичного ключа, не может содержать значение NULL. Таблица может иметь только один первичный ключ.
Вы можете использовать оператор CREATE TABLE или оператор ALTER TABLE для создания первичного ключа в SQL.
Создать первичный ключ (оператор CREATE TABLE)
Первичный ключ может быть создан при выполнении оператора CREATE TABLE в SQL.
Синтаксис
Синтаксис для создания первичного ключа с помощью оператора CREATE TABLE в SQL.
CONSTRAINT constraint_name PRIMARY KEY (pk_col1, pk_col2, . pk_col_n)
);
Пример
Давайте посмотрим, как создать первичный ключ с помощью оператора CREATE TABLE в SQL. Мы начнем с очень простого, где наш первичный ключ состоит всего из одного столбца.
Например: