The PRIMARY KEY and FOREIGN KEY are fundamental concepts in relational database design. They help ensure data integrity by defining relationships between tables. The PRIMARY KEY uniquely identifies each record in a table, while the FOREIGN KEY establishes a link between two tables.
NULLEach table can have only one primary key, but that key may consist of multiple columns. Foreign keys ensure that related records always exist in the referenced table.
// Creating a table with a PRIMARY KEY
CREATE TABLE employees (
employee_id INT NOT NULL,
first_name VARCHAR(50),
last_name VARCHAR(50),
PRIMARY KEY (employee_id)
);
// Creating a table with a FOREIGN KEY reference
CREATE TABLE orders (
order_id INT NOT NULL,
employee_id INT,
order_date DATE,
PRIMARY KEY (order_id),
FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
);
The employees table stores unique employee records. The orders table references employees using a foreign key, ensuring that every order is associated with a valid employee.
departments table linked to employeesstudents and courses tables with relationships