πŸ”β­What is a Primary Key and a Foreign Key in a Database?



This content originally appeared on DEV Community and was authored by RenΓ§ber AKMAN

A Primary Key is a column (or set of columns) in a table that uniquely identifies each row. No two rows can have the same value, and it cannot contain NULL.

📌 Example: In a Customers table, customer_id can be the primary key because each customer has a unique ID.

A Foreign Key is a column (or set of columns) in a table that references the primary key in another table. It establishes a relationship between tables and ensures referential integrity.

📌 Example: In an Orders table, customer_id can be a foreign key referencing the customer_id in the Customers table. This links each order to the correct customer.

✅ Difference:

Primary Key β†’ Uniquely identifies rows in its own table ✅

Foreign Key β†’ Establishes a relationship with a primary key in another table 🗒

💡 Pro Tip:

Every table should have a primary key.

Foreign keys ensure data consistency and prevent orphaned records.

Using indexes on foreign keys speeds up JOIN queries.


This content originally appeared on DEV Community and was authored by RenΓ§ber AKMAN