Explain Primary key with suitable example.
i. Primary key:
- A primary key is a special relational database table column (or combination of columns) designated to uniquely identify all table records.
- A primary key’s main features are:
- It must contain a unique value for each row of data.
- It cannot contain null values.
- A primary key is either an existing table column or a column that is specifically generated by the database according to a defined sequence.
- For example, students are routinely assigned unique identification (ID) numbers, and all adults receive government-assigned and uniquely-identifiable Social Security numbers.
ii. Candidate key:
- A candidate key is the most minimal subset of fields that uniquely identifies a tuple.
- Candidate keys are defined as the set of fields from which primary key can be selected. It is an attribute or set of attribute that can act as a primary key for a table to uniquely identify each record in that table.
Let’s take an example of an Employee table:
CREATETABLEEmployee ( EmployeeID, EmployeeName, SSN, DeptID )
Here in Employee table EmployeeID & SSN are eligible for a Primary Key and thus are Candidate keys.
iii. Foreign Key:
- A foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table. In simpler words, the foreign key is defined in a second table, but it refers to the primary key in the first table.
- For example, a table called Employee has a primary key called employee_id. Another table called Employee Details has a foreign key which references employee_id in order to uniquely identify the relationship between both the tables.
- A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It acts as a cross-reference between tables because it references the primary key of another table, thereby establishing a link between them.
iv. Super key:
- A superkey is defined in the relational model of database organization as a set of attributes of a relation variable for which it holds that in all relations assigned to that variable, there are no two distinct tuples (rows) that have the same values for the attributes in this set.
- Equivalently a superkey can also be defined as a set of attributes of a relation schema upon which all attributes of the schema are functionally dependent.
- A super key is a set of fields that contains a key.
- Consider the example where the combination of "user_id" and "pet_id" uniquely identifies a tuple if we added "pet_name" (which is not key because we can have multiple pets named "fluffy") it would be a super key. Basically it's like a candidate key without the "minimal subset of fields" constraint.
Please log in to add an answer.