Key plays an important role in SQL or Oracle database. Generally it is used for defining a unique set of records. It also establishes the connection
Types of Keys in SQL or Oracle Database
- Primary Key (PK)
- Unique Key
- Composite/compound Key
- Alternate Key / Secondary key
- Foreign Key/References
1. Primary Key
Primary keys can allow only non repeated value (unique value) and it can’t accept null value.
A primary key length cannot be exceeded more than 900 bytes.
Example
MySQL Command-
Create table student
Command for SQL Server, Oracle DB-
Create table student
SQL primary key for multiple columns-
Create table student
Note
Use of primary key in alter table command-
Alter table student
Drop primary key constraints
2. Unique Key
It is similar to primary key that means it can’t allow repeated value, but it
Example
SQL Server / Oracle / MS Access Example-
Create table student
MySQL Example-
Create table student
3. Composite/compound Key
When multiple numbers of columns are used as a primary key, it is also known as composite key or composite primary key.
Example
Create table test(col1 int, col2 varchar(30), col3 varchar(30), col4 varchar(30), col5 varchar(30), primary key (col1,col2,col5));
Note- In the above example, a combination of all three (col1, col2, col5) does uniquely identify each record.
4. Alternate Key
In simple words, a column which is not a part of the primary key is called alternate keys. It is also known as
For Example
Create table student
Note- In above example stu_id is primary key and the rest of all columns like stu_name and stu_address are alternate keys.
5. Foreign key/References
In other word you can also say this, the foreign key is used for establishing the link/connection between two tables.
Example-
Parent table student
Create table student
Child table fees
Create table fees
Leave Comment