Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Primary Keys and Uniqueness | Fundamentals of Relational Database Design
Database Design Patterns

bookPrimary Keys and Uniqueness

メニューを表示するにはスワイプしてください

Understanding how a relational database ensures data integrity starts with primary keys. A primary key is a column, or a set of columns, in a table whose values uniquely identify each row. The primary key serves several essential purposes:

  • It guarantees that every row is distinct;
  • It prevents duplicate data;
  • It acts as the main reference point for relationships between tables.

Without a primary key, it becomes difficult to reliably retrieve, update, or delete specific records, and the risk of duplicate or ambiguous data increases. For these reasons, every table should have a primary key defined.

-- Create a 'courses' table with a primary key on 'course_id'
CREATE TABLE courses (
    course_id INT PRIMARY KEY,
    course_name VARCHAR(100),
    course_code VARCHAR(20),
    credits INT
);

By defining a primary key, you instruct the database to enforce uniqueness for that column or combination of columns. This means that no two rows can have the same primary key value. The database automatically creates an index on the primary key, which makes searching for rows by their key values fast and efficient. When you use primary keys, you can quickly retrieve, update, or delete a specific row without scanning the entire table. This combination of uniqueness and performance is why primary keys are fundamental to reliable and efficient database design.

12345
-- Attempting to insert duplicate primary key values INSERT INTO courses (course_id, course_name, course_code, credits) VALUES (101, 'Advanced Mathematics', 'MATH201', 4); -- Error: duplicate key value violates unique constraint "courses_pkey"
copy

1. What is a primary key in a relational database?

2. What happens if you try to insert two rows with the same primary key value?

3. Which column(s) should typically be chosen as a primary key?

question mark

What is a primary key in a relational database?

正しい答えを選んでください

question mark

What happens if you try to insert two rows with the same primary key value?

正しい答えを選んでください

question mark

Which column(s) should typically be chosen as a primary key?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  2
some-alt