SQL PRIMARY KEY
A column or columns is called primary key (PK) that uniquely identifies each row in the table.
If you want to create a primary key, you should define a PRIMARY KEY constraint when you create or modify a table.
When multiple columns are used as a primary key, it is known as composite primary key.
In designing the composite primary key, you should use as few columns as possible. It is good for storage and performance both, the more columns you use for primary key the more storage space you require.
Loaded: 44.76%
Inn terms of performance, less data means the database can process faster.
Points to remember for primary key:
- Primary key enforces the entity integrity of the table.
- Primary key always has unique data.
- A primary key length cannot be exceeded than 900 bytes.
- A primary key cannot have null value.
- There can be no duplicate value for a primary key.
- A table can contain only one primary key constraint.
When we specify a primary key constraint for a table, database engine automatically creates a unique index for the primary key column.
Main advantage of primary key:
The main advantage of this uniqueness is that we get fast access.
In oracle, it is not allowed for a primary key to contain more than 32 columns.
SQL primary key for one column:
The following SQL command creates a PRIMARY KEY on the "S_Id" column when the "students" table is created.
MySQL:
- CREATE TABLE students
- (
- S_Id int NOT NULL,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- Address varchar (255),
- City varchar (255),
- PRIMARY KEY (S_Id)
- )
SQL Server, Oracle, MS Access:
- CREATE TABLE students
- (
- S_Id int NOT NULL PRIMARY KEY,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- Address varchar (255),
- City varchar (255),
- )
SQL primary key for multiple columns:
MySQL, SQL Server, Oracle, MS Access:
- CREATE TABLE students
- (
- S_Id int NOT NULL,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- Address varchar (255),
- City varchar (255),
- CONSTRAINT pk_StudentID PRIMARY KEY (S_Id, LastName)
- )
Note:you should note that in the above example there is only one PRIMARY KEY (pk_StudentID). However it is made up of two columns (S_Id and LastName).
SQL primary key on ALTER TABLE
When table is already created and you want to create a PRIMARY KEY constraint on the "S_Id" column you should use the following SQL:
Primary key on one column:
- ALTER TABLE students
- ADD PRIMARY KEY (S_Id)
Primary key on multiple column:
- ALTER TABLE students
- ADD CONSTRAINT pk_StudentID PRIMARY KEY (S_Id,LastName)
When you use ALTER TABLE statement to add a primary key, the primary key columns must not contain NULL values (when the table was first created).
How to DROP a PRIMARY KEY constraint?
If you want to DROP (remove) a primary key constraint, you should use following syntax:
MySQL:
- ALTER TABLE students
- DROP PRIMARY KEY
SQL Server / Oracle / MS Access:
SQL FOREIGN KEY
In the relational databases, a foreign key is a field or a column that is used to establish a link between two tables.
In simple words you can say that, a foreign key in one table used to point primary key in another table.
Let us take an example to explain it:
Here are two tables first one is students table and second is orders table.
Here orders are given by students.
First table:
S_Id | LastName | FirstName | CITY |
---|---|---|---|
1 | MAURYA | AJEET | ALLAHABAD |
2 | JAISWAL | RATAN | GHAZIABAD |
3 | ARORA | SAUMYA | MODINAGAR |
Second table:
O_Id | OrderNo | S_Id |
---|---|---|
1 | 99586465 | 2 |
2 | 78466588 | 2 |
3 | 22354846 | 3 |
4 | 57698656 | 1 |
Here you see that "S_Id" column in the "Orders" table points to the "S_Id" column in "Students" table.
- The "S_Id" column in the "Students" table is the PRIMARY KEY in the "Students" table.
- The "S_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The foreign key constraint is generally prevents action that destroy links between tables.
It also prevents invalid data to enter in foreign key column.
SQL FOREIGN KEY constraint ON CREATE TABLE:
(Defining a foreign key constraint on single column)
To create a foreign key on the "S_Id" column when the "Orders" table is created:
MySQL:
- CREATE TABLE orders
- (
- O_Id int NOT NULL,
- Order_No int NOT NULL,
- S_Id int,
- PRIMAY KEY (O_Id),
- FOREIGN KEY (S_Id) REFERENCES Persons (S_Id)
- )
SQL Server /Oracle / MS Access:
- CREATE TABLE Orders
- (
- O_Id int NOT NULL PRIMAY KEY,
- Order_No int NOT NULL,
- S_Id int FOREIGN KEY REFERENCES persons (S_Id)
- )
SQL FOREIGN KEY constraint for ALTER TABLE:
If the Order table is already created and you want to create a FOREIGN KEY constraint on the "S_Id" column, you should write the following syntax:
Defining a foreign key constraint on single column:
MySQL / SQL Server / Oracle / MS Access:
- ALTER TABLE Orders
- ADD CONSTRAINT fk_PerOrders
- FOREIGN KEY(S_Id)
- REFERENCES Students (S_Id)
DROP SYNTAX for FOREIGN KEY COSTRAINT:
If you want to drop a FOREIGN KEY constraint, use the following syntax:
MySQL:
- ALTER TABLE Orders
- ROP FOREIGN KEY fk_PerOrders
SQL Server / Oracle / MS Access:
- ALTER TABLE Orders
- DROP CONSTRAINT fk_PerOrders
Difference between primary key and foreign key in SQL:
These are some important difference between primary key and foreign key in SQL-
Primary key cannot be null on the other hand foreign key can be null.
Primary key is always unique while foreign key can be duplicated.
Primary key uniquely identify a record in a table while foreign key is a field in a table that is primary key in another table.
There is only one primary key in the table on the other hand we can have more than one foreign key in the table.
By default primary key adds a clustered index on the other hand foreign key does not automatically create an index, clustered or non-clustered. You must manually create an index for foreign key.
SQL Composite Key
A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.
Sometimes more than one attributes are needed to uniquely identify an entity. A primary key that is made by the combination of more than one attribute is known as a composite key.
In other words we can say that:
Composite key is a key which is the combination of more than one field or column of a given table. It may be a candidate key or primary key.
Columns that make up the composite key can be of different data types.
SQL Syntax to specify composite key:
- CREATE TABLE TABLE_NAME
- (COLUMN_1, DATA_TYPE_1,
- COLUMN_2, DATA_TYPE_2,
- ???
- PRIMARY KEY (COLUMN_1, COLUMN_2, ...));
In all cases composite key created consist of COLUMN1 and COLUMN2.
MySQL:
- CREATE TABLE SAMPLE_TABLE
- (COL1 integer,
- COL2 varchar(30),
- COL3 varchar(50),
- PRIMARY KEY (COL1, COL2));
MySQL:
- CREATE TABLE SAMPLE_TABLE
- (COL1 integer,
- COL2 varchar(30),
- COL3 varchar(50),
- PRIMARY KEY (COL1, COL2));
Oracle:
- CREATE TABLE SAMPLE_TABLE
- CREATE TABLE SAMPLE_TABLE
- (COL1 integer,
- COL2 varchar(30),
- COL3 varchar(50),
- PRIMARY KEY (COL1, COL2));
SQL Server:
Let's see the Syntax for the select top statement:
- CREATE TABLE SAMPLE_TABLE
- (COL1 integer,
- COL2 nvarchar(30),
- COL3 nvarchar(50),
- PRIMARY KEY (COL1, COL2));
Unique Key in SQL
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table.
You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.
The unique key and primary key both provide a guarantee for uniqueness for a column or a set of columns.
There is an automatically defined unique key constraint within a primary key constraint.
There may be many unique key constraints for one table, but only one PRIMARY KEY constraint for one table.
SQL UNIQUE KEY constraint on CREATE TABLE:
If you want to create a UNIQUE constraint on the "S_Id" column when the "students" table is created, use the following SQL syntax:
SQL Server / Oracle / MS Access:
(Defining a unique key constraint on single column):
- CREATE TABLE students
- (
- S_Id int NOT NULL UNIQUE,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- City varchar (255)
- )
MySQL:
- CREATE TABLE students
- CREATE TABLE students
- (
- S_Id int NOT NULL,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- City varchar (255),
- UNIQUE (S_Id)
- )
(Defining a unique key constraint on multiple columns):
MySQL / SQL Server / Oracle / MS Access:
- CREATE TABLE students
- (
- S_Id int NOT NULL,
- LastName varchar (255) NOT NULL,
- FirstName varchar (255),
- City varchar (255),
- CONSTRAINT uc_studentId UNIQUE (S_Id, LastName)
- )
SQL UNIQUE KEY constraint on ALTER TABLE:
If you want to create a unique constraint on "S_Id" column when the table is already created, you should use the following SQL syntax:
(Defining a unique key constraint on single column):
MySQL / SQL Server / Oracle / MS Access:
- ALTER TABLE students
- ADD UNIQUE (S_Id)
(Defining a unique key constraint on multiple columns):
MySQL / SQL Server / Oracle / MS Access:
- ALTER TABLE students
- ADD CONSTRAINT uc_StudentId UNIQUE (S_Id, LastName)
DROP SYNTAX FOR A FOREIGN KEY constraint:
If you want to drop a UNIQUE constraint, use the following SQL syntax:
MySQL:
- ALTER TABLE students
- DROP INDEX uc_studentID
SQL Server / Oracle / MS Access:
- ALTER TABLE students
- DROP CONSTRAINT uc_studentID
Alternate Key in SQL
Alternate key is a secondary key it can be simple to understand by an example:
Let's take an example of student it can contain NAME, ROLL NO., ID and CLASS.
Here ROLL NO. is primary key and rest of all columns like NAME, ID and CLASS are alternate keys.
If a table has more than one candidate key, one of them will become the primary key and rest of all are called alternate keys.
In simple words, you can say that any of the candidate key which is not part of primary key is called an alternate key. So when we talk about alternate key, the column may not be primary key but still it is a unique key in the column.
An alternate key is just a candidate key that has not been selected as the primary key.
How to Add Foreign Key in SQL
In this article, we will learn how to add a Foreign Key to the column in the table of our SQL database.
The FOREIGN KEY in SQL is used to join the record of two tables in the database. The column defined as the FOREIGN KEY in one table must be the PRIMARY KEY in another table in the same database.
We can easily add foreign key to the column in the following two ways:
- Add foreign key using Create table statement
- Add foreign key using Alter Table statement
If you want to add a FOREIGN KEY to the column into the SQL table, you have to follow the below steps in the given sequence:
- Create the database in the system.
- Create two tables in the same database.
- View Table structure before foreign key addition.
- Add a foreign key to the table.
- View the table structure.
Now, we are going to explain the above steps with an example:
Step 1: Create a Database
In the Structured Query Language, creating a database is the first step for storing the structured tables in the database.
Use the following SQL syntax to create a database:
- CREATE DATABASE Database_Name;
Suppose you want to create the Vehicles database. For this, you have to type the following command in Structured Query Language:
- CREATE DATABASE Vehicles;
Step 2: Create two Tables in the database
Now, you have to use the following SQL syntax for creating the tables in your database:
- CREATE TABLE table_name
- (
- column_Name_1 data type (size of the column_1),
- column_Name_2 data type (size of the column_2),
- column_Name_3 data type (size of the column_3),
- ...
- column_Name_N data type (size of the column_1)
- );
The following SQL query creates the Cars_Details table in the Vehicles database.
- CREATE TABLE Cars_Details
- (
- Car_Number INT AUTO_INCREMENT PRIMARY KEY,
- Model INT,
- Cars_Name VARCHAR (20),
- Colour VARCHAR (20),
- );
The following query creates Cars_Price_Details table in the Vehicles database:
- CREATE TABLE Cars_Price_Details
- (
- Model INT NOT NULL PRIMARY KEY,
- Cars_Price INT NOT NULL
- );
Step 3: View the Table Structure before Foreign key Addition
After table creation and data insertion, you can view the structure of both tables by typing the following query in your SQL application:
- DESC Cars
- or
- DESCRIBE Cars ;
Field | Type | NULL | Key | Default | Extra |
---|---|---|---|---|---|
Car_Number | INT | NO | PRI | NULL | auto_increment |
Model | INT | Yes | - | NULL | - |
Car_Name | Varchar(20) | Yes | - | NULL | |
Color | Varchar(20) | Yes | - | NULL | - |
- DESC Cars_Price_Details;
Field | Type | NULL | Key | Default | Extra |
---|---|---|---|---|---|
Car_Model | INT | No | PRI | NULL | - |
Car_Price | INT | No | - | NULL |
Step 4: Add a Foreign key to the column in the table
If you want to add the foreign key at the time of table creation, then you have to use the following CREATE TABLE syntax in SQL:
- CREATE TABLE table_name1
- (
- Column_Name_1 data type (size of the column_1),
- Column_Name_2 data type (size of the column_2),
- ......,
- Column_Name_N data type (size of the column_N) FOREIGN KEY REFERENCES Table_Name2 (Column_Name)
- ) ;
Example
The following query adds the FOREIGN KEY on the 'Model' column in the Cars_Details table:
- CREATE TABLE Cars_Details
- (
- Car_Number INT AUTO_INCREMENT,
- Model INT FOREIGN KEY REFERENCES Cars_Price_Details (Car_Model),
- Cars_Name VARCHAR (20),
- Color VARCHAR (20) UNIQUE,
- Price INT NOT NULL
- ) ;
This query in SQL joins the Cars_Details table with the Cars_Price_Details table with the help of a foreign key.
Step 5: View the Table Structure after Foreign key Addition
To check the result of the query executed in the 4th step, you have to type the following DESC command in SQL:
- DESC Cars_Details;
Field | Type | NULL | Key | Default | Extra |
---|---|---|---|---|---|
Car_Number | INT | Yes | PRIMARY | NULL | auto_increment |
Model | INT | No | FOREIGN | NULL | - |
Car_Name | Varchar(20) | Yes | - | NULL | - |
Color | Varchar(20) | Yes | - | NULL | - |
Price | INT | NO | - | NULL | - |
Average | INT | NO | - | 0 | - |
As shown in the above output, the Model column is created as the foreign key.
Add Foreign key to the Existing Table
If you want to add the foreign key to the existing table, you have to use the following ALTER syntax in SQL:
- ALTER TABLE Table_Name1 ADD CONSTRAINT ForeignKey_Name FOREIGN KEY (Column_Name) REFERENCES Table_Name2 (Column_Name);
The following query adds a FOREIGN KEY on the Model column when the Cars_Details table already exists in the database system:
- ALTER TABLE Cars_Details ADD CONSTRAINT FK_Cars_Details FOREIGN KEY (Model) REFERENCES Cars_Price_Details (Car_Model);
This ALTER query in SQL joins the Cars_Details table with the Cars_Price_Details table with the help of a foreign key.
Delete foreign key from the table
If you want to delete the foreign key from the column of the table, you have to use the following ALTER syntax in SQL:
- ALTER TABLE Table_Name DROP FOREIGN KEY Foreign_Key_Name;
The following query deletes the created FOREIGN KEY from the Model column of the Cars_Details table:
- ALTER TABLE Cars DROP FOREIGN KEY FK_Cars_Details;
How to Add a Primary Key in SQL
In this article, we will learn how to add Primary Key to the column in the table of our SQL database.
The PRIMARY KEY is used to retrieve each record of the SQL table. The field defined as the PRIMARY KEY must contain different and NOT NULL values. You can easily add a primary key to the column in the following two ways:
- Add Primary key using Create table statement
- Add primary key using Alter Table statement
If you want to add primary key to a column in the table, you have to follow the below steps in the given sequence:
- Create a database in the system.
- Create the table in the SQL database.
- View the table structure.
- Add the primary key to column in the table.
- View the table structure.
Now, we are going to explain the above steps with an example.
Step 1: Create a Database
In the structured query language, creating a database is the first step for storing the structured tables in the database.
Use the following SQL syntax to create a database:
- CREATE DATABASE Database_Name;
Suppose you want to create the Vehicles database. For this, you have to type the following command in Structured Query Language:
- CREATE DATABASE Vehicles;
Step 2: Create a Table and Insert the data
Now, you have to use the following SQL syntax to create a table in your database:
- CREATE TABLE table_name
- (
- column_Name_1 data type (size of the column_1),
- column_Name_2 data type (size of the column_2),
- column_Name_3 data type (size of the column_3),
- ...
- column_Name_N data type (size of the column_1)
- );
Suppose you want to create the Cars table in the Vehicles database. For this, you have to type the following query in your SQL application:
- CREATE TABLE Cars
- (
- Car_Number INT AUTO_INCREMENT,
- Model INT,
- Cars_Name VARCHAR (20),
- Colour VARCHAR (20),
- Price INT NOT NULL,
- ) ;
Step 3: View the Table Structure before Primary key Addition
After table creation and data insertion, you can view the structure of the Cars table by typing the following query in your SQL application:
- DESC Cars
- or
- DESCRIBE Cars ;
Field | Type | NULL | Key | Default | Extra |
---|---|---|---|---|---|
Car_Number | INT | NO | - | NULL | auto_increment |
Model | INT | Yes | - | NULL | - |
Car_Name | Varchar(20) | Yes | - | NULL | |
Color | Varchar(20) | Yes | - | NULL | - |
Price | INT | NO | - | NULL | - |
Step 4: Add a Primary key to the column in the table
If you want to add the primary key at the time of table creation, then you have to use the following CREATE TABLE syntax in SQL:
- CREATE TABLE table_name
- (
- Column_Name_1 data type (size of the column_1) NOT NULL PRIMARY KEY,
- Column_Name_2 data type (size of the column_2),
- .......,
- Column_Name_N data type (size of the column_N),
- ) ;
Example
The following query creates 'Cars' table and adds the PRIMARY KEY constraint on the 'Model' column:
- CREATE TABLE Cars
- (
- Car_Number INT AUTO_INCREMENT,
- Model INT NOT NULL PRIMARY KEY,
- Cars_Name VARCHAR (20),
- Color VARCHAR (20) UNIQUE,
- Price INT NOT NULL
- ) ;
This query in SQL does not allow database users to insert the same model of car in the Cars table.
Step 5: View the Table Structure after Primary key Addition
To check the result of the query executed in the 4th step, you have to type the following DESC command in SQL:
- DESC Cars;
Field | Type | NULL | Key | Default | Extra |
---|---|---|---|---|---|
Car_Number | INT | Yes | - | NULL | auto_increment |
Model | INT | No | PRI | NULL | - |
Car_Name | Varchar(20) | Yes | - | NULL | - |
Color | Varchar(20) | Yes | - | NULL | - |
Price | INT | NO | - | NULL | - |
Average | INT | NO | - | 0 | - |
You can see in the above SQL output that the Model column is created as the primary key. Now, the Model column must contain unique and NOT NULL values. If you enter the same and NULL values in this column, the SQL system will show an error.
Delete Primary key from the table
If you want to delete the Primary key from the column of the table, then you have to use the following ALTER syntax in SQL:
- ALTER TABLE Table_Name DROP PRIMARY KEY;
The following query deletes the PRIMARY KEY from the Model column of the Cars table:
- ALTER TABLE Cars DROP PRIMARY KEY;
Add Primary key to the Existing Table
If you want to add a primary key in the existing table, you have to use the following ALTER syntax in SQL:
- ALTER TABLE Table_Name ADD CONSTRAINT Constraint_Name PRIMARY KEY (Column_Name);
The following query adds a PRIMARY KEY constraint on the Color column when the Cars table already exists in the database system:
- ALTER TABLE Cars ADD CONSTRAINT clr_prmrykey PRIMARY KEY ( Color);
This ALTER query in SQL will not allow you to insert the same color of a car in the Cars table.