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.
Inn terms of performance, less data means the database can process faster.
Points to remember for primary key:
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.
SQL Server, Oracle, MS Access:
SQL primary key for multiple columns:
MySQL, SQL Server, Oracle, MS Access:
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:
Primary key on multiple column:
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:
SQL Server / Oracle / MS Access: