1. Tables, Rows, and Columns in Relational Databases
1. Tables
A table is the fundamental structure in a relational database. It organizes data into rows and columns, similar to a spreadsheet. Each table represents an entity (e.g., Customers, Orders, Employees).
Example Table: Customers
| CustomerID | Name | Email | Age |
|--------------|-----------|--------------------|------|
| 1 | John Doe | john@example.com | 30 |
| 2 | Jane Smith | jane@example.com | 25 |
2. Columns
A column represents a specific attribute or field of the entity. Each column has a data type (e.g., INTEGER, VARCHAR, DATE).
Example Columns in Customers Table:
- CustomerID → Unique identifier (INTEGER, PRIMARY KEY)
- Name → Customer’s name (VARCHAR)
- Email → Contact email (VARCHAR, UNIQUE)
- Age → Customer's age (INTEGER)
3. Rows
A row (also called a record) represents a single instance of an entity. Each row contains values for every column.
Example Row in Customers Table:
| CustomerID | Name | Email | Age |
|--------------|------------|--------------------|------|
| 1 | John Doe | john@example.com | 30 |
4. Primary and Foreign Keys
- Primary Key (PK) → A unique identifier for each row (e.g.,
CustomerID). - Foreign Key (FK) → A reference to a primary key in another table, enabling relationships.
Example Relationship: Customers & Orders
- Orders table has a foreign key (CustomerID) linking to Customers table.
Orders Table:
| OrderID | CustomerID (FK) | Total Amount |
|-----------|----------------|--------------|
| 101 | 1 | 150.00 |
| 102 | 2 | 200.00 |
SQL Example
Creating a Table:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(100),
Email VARCHAR(100) UNIQUE,
Age INT
);
Inserting Data:
INSERT INTO Customers (CustomerID, Name, Email, Age)
VALUES (1, 'John Doe', 'john@example.com', 30);
Retrieving Data:
SELECT * FROM Customers;
This structure ensures organized, scalable, and efficient data management in relational databases.