Chapter 2: Relational Database Fundamentals
2.1 Understanding Tables, Rows, and Columns
Relational databases organize data into tables, which are composed of rows and columns. This structure is fundamental to understanding how relational databases work.
2.1.1 Tables
- A table represents a single entity type (e.g., customers, orders, products).
- Each table has a unique name within the database.
2.1.2 Rows
- Also known as records or tuples.
- Each row represents a single instance of the entity (e.g., one specific customer).
- All rows in a table have the same structure.
2.1.3 Columns
- Also known as fields or attributes.
- Each column represents a specific characteristic of the entity (e.g., customer name, email).
- Columns have a defined data type (e.g., integer, varchar, date).
2.2 Primary Keys, Foreign Keys, and Relationships
These concepts are crucial for maintaining data integrity and establishing relationships between tables.
2.2.1 Primary Keys
- A primary key uniquely identifies each row in a table.
- It can be a single column or a combination of columns.
- Every table should have a primary key.
Example:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100)
);
2.2.2 Foreign Keys
- A foreign key is a column (or combination of columns) that refers to the primary key of another table.
- It establishes a link between two tables.
Example:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
2.2.3 Relationships
There are three types of relationships in relational databases:
- One-to-One (1:1)
- One-to-Many (1:N)
- Many-to-Many (M:N)
Example of a One-to-Many relationship:
- One customer can have many orders, but each order belongs to only one customer.
2.3 SQL Basics (SELECT, INSERT, UPDATE, DELETE)
SQL (Structured Query Language) is the standard language for interacting with relational databases. Here are the fundamental SQL operations:
2.3.1 SELECT
Used to retrieve data from one or more tables.
SELECT column1, column2 FROM table_name WHERE condition;
-- Example
SELECT Name, Email FROM Customers WHERE City = 'New York';
2.3.2 INSERT
Used to add new rows to a table.
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
-- Example
INSERT INTO Customers (Name, Email) VALUES ('John Doe', 'john@example.com');
2.3.3 UPDATE
Used to modify existing data in a table.
UPDATE table_name SET column1 = value1 WHERE condition;
-- Example
UPDATE Customers SET Email = 'newemail@example.com' WHERE CustomerID = 1;