Database.Is primary key always indexed ?

✅ Is a Primary Key Always Indexed?

Yes — in all major relational database systems, a primary key is automatically indexed.


📌 Why?

Because:

  • The primary key must be unique.
  • The database must be able to quickly check for duplicates.
  • Fast access is essential for searching, joining, and enforcing referential integrity.

So when you declare a primary key:

CREATE TABLE Customers (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100)
);

The database automatically creates a unique index on customer_id.


🧠 Note:

  • You don’t need to manually add an index for a primary key — it’s built-in.
  • If you define a composite primary key, a composite index is also created automatically.

🛠 Example (composite key):

CREATE TABLE StudentCourses (
    student_id INT,
    course_id INT,
    PRIMARY KEY (student_id, course_id)
);

➡️ This will create a composite index on (student_id, course_id).

This entry was posted in Без рубрики. Bookmark the permalink.