Understanding Primary and Foreign Keys in Relational Databases

--

In a relational database, a primary key is a unique identifier for each record in a table. A primary key ensures that no two records in a table have the same identifier, and it also ensures that each record has a unique identifier.

A foreign key, on the other hand, is a field in one table that is used to refer to the primary key of another table. A foreign key is used to establish a link between two tables, allowing data to be retrieved from one table based on the data in another table.

For example, consider two tables: "customers" and "orders". The "customers" table might have a primary key of "customer_id", and the "orders" table might have a foreign key of "customer_id" that refers to the primary key of the "customers" table. This creates a link between the two tables so that you can retrieve all the orders for a specific customer by looking up the customer's ID in the "customers" table and then using that ID to find all the orders in the "orders" table that have the same ID in the "customer_id" field.

Here's an example of creating a table with a primary key and a foreign key:

CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
);

CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id),
order_date DATE
);

Here, we created two tables, customers and orders. "customer_id" column in the customer's table is set as the primary key and the "customer_id" column in the orders table is set as a foreign key which references the primary key of the customer's table. This creates a relationship between the two tables, linking orders to the customers.

here's an example of creating a user, creating an order for that user, and then reading the order:

-- Create a new user
INSERT INTO customers (customer_id, name, email)
VALUES (1, 'John Doe', 'johndoe@example.com');

-- Create an order for the user
INSERT INTO orders (order_id, customer_id, order_date)
VALUES (1, 1, '2022-01-01');

-- Read the order for the user
SELECT * FROM orders
WHERE customer_id = 1;

This first statement uses the INSERT INTO command to insert a new row into the "customers" table, with a customer ID of 1, a name of "John Doe", and an email of "johndoe@example.com".

The second statement uses the INSERT INTO command to insert a new row into the "orders" table, with an order ID of 1, a customer ID of 1, and an order date of '2022-01-01'.

Finally, the third statement uses the SELECT command to retrieve all rows from the "orders" table where the customer_id is 1. This will return the order that was just created for the user with the ID of 1, "John Doe"

--

--

Hesh Ramsis ( Hesham El Masry 77 )

8+ yrs exp. front-end dev. Skilled in HTML, CSS, JS. 2yrs of teaching exp. Dedicated to creating visually stunning & UX websites and mentoring future developers