ประเภทต่างๆ ของ keys ใน DBMS คือ -
- Candidate Key - Candidate keys ในตารางนิยามว่าเป็นชุดของ keys ที่เป็น minimal และสามารถระบุแถวข้อมูลใดๆ ในตารางได้อย่างไม่ซ้ำกัน
- Primary Key - Primary key ถูกเลือกจาก candidate keys หนึ่งและกลายเป็น identifying key ของตาราง สามารถระบุแถวข้อมูลใดๆ ของตารางได้อย่างไม่ซ้ำกัน
- Super Key - Super Key คือ superset ของ primary key Super key มีชุดแอตทริบิวต์ รวมถึง primary key ซึ่งสามารถระบุแถวข้อมูลใดๆ ในตารางได้อย่างไม่ซ้ำกัน
- Composite Key - หากแอตทริบิวต์เดี่ยวของตารางไม่สามารถเป็น key ได้ คือ ไม่สามารถระบุแถวได้อย่างไม่ซ้ำกัน เราจะรวมแอตทริบิวต์ 2 ตัวขึ้นไปเพื่อสร้าง key นี่เรียกว่า composite key
- Secondary Key - เพียงหนึ่งใน candidate keys ถูกเลือกเป็น primary key ส่วนที่เหลือเรียกว่า secondary keys
- Foreign Key - Foreign key คือค่าแอตทริบิวต์ในตารางที่ทำหน้าที่เป็น primary key ในอีกตารางหนึ่ง ดังนั้น foreign key จึงมีประโยชน์ในการลิงก์ตาราง 2 ตารางเข้าด้วยกัน ข้อมูลควรป้อนในคอลัมน์ foreign key ด้วยความระมัดระวัง เนื่องจากข้อมูลที่ป้อนผิดสามารถทำให้ความสัมพันธ์ระหว่าง 2 ตารางเป็นไม่ถูกต้อง
ตัวอย่างเพื่ออธิบาย keys ต่างๆ -
<STUDENT>
| Student_Number | Student_Name | Student_Phone | Subject_Number |
|---|---|---|---|
| 1 | Andrew | 6615927284 | 10 |
| 2 | Sara | 6583654865 | 20 |
| 3 | Harry | 4647567463 | 10 |
<SUBJECT>
| Subject_Number | Subject_Name | Subject_Instructor |
|---|---|---|
| 10 | DBMS | Korth |
| 20 | Algorithms | Cormen |
| 30 | Algorithms | Leiserson |
<ENROLL>
| Student_Number | Subject_Number |
|---|---|
| 1 | 10 |
| 2 | 20 |
| 3 | 10 |
Super Keys ใน <Student> ตาราง คือ -
{Student_Number} {Student_Phone} {Student_Number,Student_Name} {Student_Number,Student_Phone} {Student_Number,Subject_Number} {Student_Phone,Student_Name} {Student_Phone,Subject_Number} {Student_Number,Student_Name,Student_Phone} {Student_Number,Student_Phone,Subject_Number} {Student_Number,Student_Name,Subject_Number} {Student_Phone,Student_Name,Subject_Number}Super Keys ใน <Subject> ตาราง คือ -
{Subject_Number} {Subject_Number,Subject_Name} {Subject_Number,Subject_Instructor} {Subject_Number,Subject_Name,Subject_Instructor} {Subject_Name,Subject_Instructor}Super Key ใน <Enroll> ตาราง คือ -
{Student_Number,Subject_Number}Candidate Key ใน <Student> ตารางคือ {Student_Number} หรือ {Student_Phone}
Candidate Key ใน <Subject> ตารางคือ {Subject_Number} หรือ {Subject_Name,Subject_Instructor}
Candidate Key ใน <Student> ตารางคือ {Student_Number, Subject_Number}
Primary Key ใน <Student> ตารางคือ {Student_Number}
Primary Key ใน <Subject> ตารางคือ {Subject_Number}
Primary Key ใน <Enroll> ตารางคือ {Student_Number, Subject_Number}
Composite Key ใน <Enroll> ตารางคือ {Student_Number, Subject_Number}
Secondary Key ใน <Student> ตารางคือ {Student_Phone}
Secondary Key ใน <Subject> ตารางคือ {Subject_Name,Subject_Instructor}
{Subject_Number} เป็น Foreign Key ของ <Student> ตาราง และ Primary key ของ <Subject> ตาราง