Mapping Overview
Mapping Algorithm
Read aloud is unavailable in this browser.
The Algorithm Behind the Translation
In the previous page, we understood why ER-to-relational mapping exists and explored the overall process at a conceptual level. Now we transition from understanding to execution.
This page presents the canonical mapping algorithm—a systematic procedure that transforms any ER diagram into a relational schema. This isn't a loose set of guidelines; it's a precise algorithm with defined inputs, outputs, and decision procedures for each step.
The algorithm we'll study is based on the foundational work of Peter Chen and subsequent refinements by database researchers over decades. While variations exist (and tools may implement slightly different versions), the core algorithm presented here represents the industry standard approach taught in database courses worldwide and implemented in CASE tools.
By the end of this page, you will be able to execute the complete mapping algorithm from memory. You'll understand the precise rules for each construct type, know how to handle edge cases, and be able to verify the correctness of your mappings. This is the algorithmic foundation that separates systematic database design from ad-hoc table creation.
Algorithm Prerequisites
Before executing the mapping algorithm, certain prerequisites must be in place. Attempting to map an incomplete or ambiguous ER diagram will result in undefined or incorrect outcomes.
Required ER Diagram Components:
The input ER diagram must clearly specify:
- •All entity types — Each entity must have a unique name, defined attributes, and identified key attribute(s)
- •Attribute classifications — Each attribute must be identified as: simple/composite, single-valued/multivalued, and derived/stored
- •Key attributes — Every strong entity must have at least one candidate key identified; weak entities must have partial keys
- •All relationship types — Each relationship must have a name, participating entity types, and relationship attributes (if any)
- •Cardinality ratios — Every binary relationship must specify its cardinality (1:1, 1:N, or M:N)
- •Participation constraints — Each entity's participation in each relationship must be marked as total or partial
- •Weak entity identifications — Weak entities must be linked to their identifying (owner) entities
- •Specialization/Generalization details — Hierarchies must specify disjoint/overlapping and total/partial constraints
If any of the above is missing or ambiguous, STOP. Return to the ER diagram and resolve the ambiguity before proceeding. Guessing during mapping introduces silent errors that may not surface until production data exposes integrity violations.
Algorithm Output Specification:
The algorithm produces a relational schema consisting of:
| Output Component | Description |
|---|---|
| Relation schemas | Table definitions with column names and data types |
| Primary key designations | PK specification for each table |
| Foreign key declarations | FK constraints with referenced tables |
| Referential actions | CASCADE, SET NULL, RESTRICT, etc. for each FK |
| Uniqueness constraints | UNIQUE declarations for alternate keys |
| Nullability specifications | NOT NULL constraints for mandatory attributes |
| Check constraints | Domain constraints expressible as CHECK clauses |
The algorithm does NOT automatically generate:
- Index specifications (performance tuning concern)
- Physical storage parameters (DBMS-specific)
- View definitions (application-layer concern)
- Trigger logic (complex constraint enforcement)
Step 1: Map Strong Entity Types
The algorithm begins with strong (regular) entity types—entities that have their own key attributes and do not depend on other entities for identification.
Procedure:
12345678910111213141516171819202122
FOR EACH strong entity type E in the ER diagram: 1. CREATE a relation R with name = E.name 2. FOR EACH simple attribute A of E: ADD column A to R with appropriate data type 3. FOR EACH composite attribute C of E: FOR EACH simple component attribute A of C: ADD column C_A to R (flattened naming convention) 4. MARK derived attributes for later decision: Option A: Store with trigger/procedure refresh Option B: Compute on query (do not add column) Option C: Materialize as computed column (if DBMS supports) 5. SET the primary key of R: Choose one candidate key from E's key attributes Remaining candidate keys become UNIQUE constraints 6. MARK all non-key attributes based on participation: Required attributes → NOT NULL Optional attributes → Allow NULLExample: Mapping the EMPLOYEE Entity
Transform a typical EMPLOYEE entity with various attribute types
**EMPLOYEE** entity with:
- **SSN** (key attribute)
- **Name** (composite: FirstName, MiddleName, LastName)
- **BirthDate** (simple)
- **Address** (composite: Street, City, State, Zip)
- **Salary** (simple)
- **Age** (derived from BirthDate)```sql
CREATE TABLE EMPLOYEE (
SSN CHAR(11) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
MiddleName VARCHAR(50),
LastName VARCHAR(50) NOT NULL,
BirthDate DATE NOT NULL,
Street VARCHAR(100),
City VARCHAR(50),
State CHAR(2),
Zip CHAR(10),
Salary DECIMAL(10,2)
-- Age is derived, computed on query
);
```Key Decisions in Step 1:
-
Composite Attribute Flattening Strategy:
- Prefix approach:
Name_First,Name_Last— Clear hierarchy but verbose - Direct approach:
FirstName,LastName— Simpler but loses grouping context - Structured type: Use DBMS composite types (PostgreSQL, Oracle) — Complex but preserves structure
- Prefix approach:
-
Derived Attribute Handling:
- Compute on read: No storage, always current, but computation cost per query
- Store and refresh: Fast reads, but requires triggers/batch updates for consistency
- Materialized: Best of both if DBMS supports computed columns
-
Candidate Key Selection:
- Prefer stable attributes (SSN over Email, which might change)
- Prefer single-attribute keys (simpler foreign key references)
- Consider surrogate keys if natural keys are problematic
Step 2: Map Weak Entity Types
Weak entities depend on owner (strong) entities for identification. They have partial keys (discriminators) that only differentiate instances within the scope of their owner.
Procedure:
1234567891011121314151617181920
FOR EACH weak entity type W in the ER diagram: 1. IDENTIFY the owner entity type O via the identifying relationship 2. CREATE a relation R with name = W.name 3. FOR EACH simple/flattened attribute A of W: ADD column A to R 4. ADD the primary key columns of O's relation to R: These become foreign key columns referencing O 5. SET the primary key of R: PK(R) = {PK(O)} ∪ {Partial_Key(W)} (Combination of owner's PK and weak entity's discriminator) 6. ADD foreign key constraint: FOREIGN KEY (owner_pk_columns) REFERENCES owner_table(pk_columns) ON DELETE CASCADE -- Weak entity cannot exist without owner ON UPDATE CASCADE -- Propagate owner PK changesExample: Mapping the DEPENDENT Weak Entity
DEPENDENT is a weak entity identified by EMPLOYEE through the 'Has' relationship
**DEPENDENT** (weak entity) with:
- **DependentName** (partial key/discriminator)
- **BirthDate** (simple)
- **Relationship** (simple - e.g., 'Spouse', 'Child')
Identified by **EMPLOYEE** through the identifying relationship **Has**```sql
CREATE TABLE DEPENDENT (
EmployeeSSN CHAR(11) NOT NULL,
DependentName VARCHAR(50) NOT NULL,
BirthDate DATE,
Relationship VARCHAR(20),
PRIMARY KEY (EmployeeSSN, DependentName),
FOREIGN KEY (EmployeeSSN)
REFERENCES EMPLOYEE(SSN)
ON DELETE CASCADE
ON UPDATE CASCADE
);
```The ON DELETE CASCADE is not optional for weak entities—it's semantically required. By definition, a weak entity cannot exist independently of its owner. If an employee is deleted, their dependents must also be deleted (or the operation should be blocked at a higher level). This is the relational enforcement of the identifying relationship.
Multi-Level Weak Entities:
Weak entities can themselves own other weak entities, creating a chain of identification dependencies. In such cases:
- Map in order from owner to dependent (strong → weak₁ → weak₂ → ...)
- Each weak entity includes the complete composite key of its owner
- The transitive foreign key chain must be maintained
Example Chain: BUILDING → FLOOR → ROOM
CREATE TABLE BUILDING (
BuildingID VARCHAR(10) PRIMARY KEY
);
CREATE TABLE FLOOR (
BuildingID VARCHAR(10) NOT NULL,
FloorNumber INT NOT NULL,
PRIMARY KEY (BuildingID, FloorNumber),
FOREIGN KEY (BuildingID) REFERENCES BUILDING(BuildingID)
);
CREATE TABLE ROOM (
BuildingID VARCHAR(10) NOT NULL,
FloorNumber INT NOT NULL,
RoomNumber VARCHAR(10) NOT NULL,
PRIMARY KEY (BuildingID, FloorNumber, RoomNumber),
FOREIGN KEY (BuildingID, FloorNumber)
REFERENCES FLOOR(BuildingID, FloorNumber)
);
Step 3: Map Multivalued Attributes
The relational model requires atomicity—each cell contains exactly one value. Multivalued attributes (where an entity can have multiple values for a single attribute) cannot be stored directly in a column and require decomposition into separate tables.
Procedure:
12345678910111213141516
FOR EACH multivalued attribute A of entity type E: 1. CREATE a new relation R_A with name = E_A (or meaningful alternative) 2. ADD the primary key columns of E's relation as columns in R_A: These become foreign key columns 3. ADD a column A to R_A for the attribute value 4. SET the primary key of R_A: PK(R_A) = {PK(E)} ∪ {A} (Unless duplicates are allowed, in which case consider surrogate key) 5. ADD foreign key constraint: FOREIGN KEY (entity_pk_columns) REFERENCES entity_table(pk_columns) ON DELETE CASCADE -- Attribute values don't exist without entityExample: Employee Skills (Multivalued Attribute)
An employee can have multiple skills, each skill is a single value
**EMPLOYEE** entity has a multivalued attribute **Skills** (e.g., 'Python', 'SQL', 'Project Management')```sql
-- Employee table from Step 1 (already created)
CREATE TABLE EMPLOYEE_SKILLS (
EmployeeSSN CHAR(11) NOT NULL,
Skill VARCHAR(50) NOT NULL,
PRIMARY KEY (EmployeeSSN, Skill),
FOREIGN KEY (EmployeeSSN)
REFERENCES EMPLOYEE(SSN)
ON DELETE CASCADE
);
```Composite Multivalued Attributes:
When a multivalued attribute is also composite, flatten the composite structure within the new table:
Example: EMPLOYEE has multivalued PreviousJobs (composite: Company, Title, StartDate, EndDate)
CREATE TABLE EMPLOYEE_PREVIOUS_JOBS (
EmployeeSSN CHAR(11) NOT NULL,
Company VARCHAR(100) NOT NULL,
Title VARCHAR(100) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE,
PRIMARY KEY (EmployeeSSN, Company, StartDate),
FOREIGN KEY (EmployeeSSN)
REFERENCES EMPLOYEE(SSN)
ON DELETE CASCADE
);
Design Consideration: The choice of primary key for multivalued attribute tables requires careful thought. In the example above, we assume an employee cannot have two jobs at the same company starting the same date. If this assumption doesn't hold, consider:
- Adding a surrogate key
- Expanding the composite key
- Using a UNIQUE constraint instead of composite PK
Recognizing multivalued attributes during ER modeling is essentially recognizing a normalization requirement (specifically, 1NF violation). The mapping algorithm automatically produces a 1NF-compliant design by factoring multivalued attributes into separate tables.
Step 4: Map 1:1 Binary Relationships
Binary 1:1 relationships connect two entity types where each instance of one entity relates to at most one instance of the other (and vice versa). These offer the most mapping flexibility but require careful analysis of participation constraints.
Three Mapping Approaches:
| Approach | When to Use | Resulting Schema |
|---|---|---|
| Foreign Key | Default approach; one side has total participation | Add FK to one table referencing the other |
| Merged Tables | Both entities have total participation; always accessed together | Combine into single table with all attributes |
| Separate Relationship Table | Both participations partial; rare cases with many relationship attributes | Create third table with FKs to both entities |
123456789101112131415161718192021222324252627282930313233343536373839
FOR EACH 1:1 binary relationship R between entities E1 and E2: OPTION A - Foreign Key Approach (PREFERRED): ============================================ 1. DETERMINE which side has total participation: IF E1 has total participation in R: Add FK to E1's table referencing E2 ELSE IF E2 has total participation in R: Add FK to E2's table referencing E1 ELSE (both partial): Add FK to the table with fewer rows (estimation) Or the side more frequently accessed in joins 2. ADD the primary key of the referenced entity as FK 3. IF total participation: Mark FK as NOT NULL ELSE: Allow NULL (partial participation) 4. ADD any relationship attributes to the table with the FK 5. ADD UNIQUE constraint on FK column (enforces 1:1) OPTION B - Merged Table Approach: ================================= USE WHEN: Both entities have total participation AND entities are always accessed/queried together 1. CREATE single table with combined attributes 2. CHOOSE primary key from either entity's PK 3. Make alternate PK a UNIQUE constraint 4. INCLUDE all relationship attributes WARNING: This couples entities tightly; complicates future changes OPTION C - Relationship Table Approach: ====================================== USE ONLY WHEN: Both participations partial AND significant relationship attributes exist 1. CREATE new table R_table 2. ADD PKs from both E1 and E2 as FKs in R_table 3. EITHER PK can serve as R_table's PK (with UNIQUE on other) 4. ADD relationship attributes to R_tableExample: EMPLOYEE Manages DEPARTMENT (1:1)
Each department has exactly one manager; each employee can manage at most one department
**MANAGES** relationship (1:1) between:
- **EMPLOYEE** (partial participation — not all employees manage)
- **DEPARTMENT** (total participation — every department has a manager)```sql
-- FK goes in DEPARTMENT (total participation side)
CREATE TABLE DEPARTMENT (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL,
ManagerSSN CHAR(11) NOT NULL UNIQUE, -- 1:1 enforced
MgrStartDate DATE, -- Relationship attribute
FOREIGN KEY (ManagerSSN)
REFERENCES EMPLOYEE(SSN)
ON DELETE RESTRICT -- Can't delete employee who manages
ON UPDATE CASCADE
);
```Without the UNIQUE constraint on the foreign key, the schema would allow 1:N (one employee managing multiple departments). The UNIQUE constraint is what enforces the 1:1 cardinality in the relational schema. This is a common mapping error that violates semantic preservation.
Step 5: Map 1:N Binary Relationships
Binary 1:N (one-to-many) relationships are the most common relationship type. One entity instance (on the '1' side) can relate to many instances of another entity (the 'N' side), but each instance on the 'N' side relates to at most one on the '1' side.
The mapping approach is straightforward: add a foreign key to the table on the 'N' side.
Procedure:
12345678910111213141516171819
FOR EACH 1:N binary relationship R between E1 (1-side) and EN (N-side): 1. ADD the primary key of E1 as a foreign key column in EN's table 2. SET nullability based on EN's participation in R: IF EN has total participation: Mark FK as NOT NULL -- Every N-entity must have a 1-entity ELSE (partial participation): Allow FK to be NULL -- N-entity may exist without 1-entity 3. ADD any relationship attributes to EN's table (They belong with the N-side since each relationship instance corresponds to one N-side entity) 4. ADD foreign key constraint with appropriate referential action: FOREIGN KEY (e1_pk_columns) REFERENCES E1_table(pk_columns) ON DELETE ??? -- Depends on business rules ON UPDATE CASCADEReferential Action Decision Guide:
Choosing the correct ON DELETE action requires understanding the business rules:
| Action | Meaning | Use When |
|---|---|---|
| CASCADE | Delete N-side records when 1-side deleted | N-side entities meaningless without 1-side (e.g., OrderItems when Order deleted) |
| SET NULL | Set FK to NULL when 1-side deleted | N-side can exist independently (e.g., Employee's DeptId when Dept dissolved) |
| RESTRICT | Block deletion if N-side records exist | Deletion should be explicit; protect data from accidental loss |
| NO ACTION | Same as RESTRICT (standard SQL) | Default behavior if not specified |
| SET DEFAULT | Set FK to default value | When a default 1-side entity exists (e.g., "Uncategorized" department) |
Example: DEPARTMENT Contains EMPLOYEES (1:N)
Each department has many employees; each employee belongs to one department
**WORKS_IN** relationship (1:N) between:
- **DEPARTMENT** (1-side, partial participation — depts can be empty)
- **EMPLOYEE** (N-side, partial participation — employees may be unassigned)```sql
CREATE TABLE EMPLOYEE (
SSN CHAR(11) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
-- ... other attributes ...
DeptID INT, -- NULL allowed (partial participation)
FOREIGN KEY (DeptID)
REFERENCES DEPARTMENT(DeptID)
ON DELETE SET NULL -- If dept deleted, keep employee
ON UPDATE CASCADE
);
```If the N-side has total participation (every employee MUST belong to a department), the FK must be NOT NULL. However, this creates an insertion problem: you can't insert an employee without a department. This may require INSERT ordering, deferred constraints, or application-level handling.
Step 6: Map M:N Binary Relationships
Binary M:N (many-to-many) relationships cannot be represented by adding columns to either participating entity's table—this would violate 1NF. Instead, M:N relationships require a new junction (bridge/associative) table.
Procedure:
12345678910111213141516171819202122
FOR EACH M:N binary relationship R between entities E1 and E2: 1. CREATE a new relation R_table with meaningful name (Convention: E1_E2 or relationship name or domain term) 2. ADD primary key columns from E1's table as columns in R_table 3. ADD primary key columns from E2's table as columns in R_table 4. SET R_table's primary key: PK(R_table) = {PK(E1)} ∪ {PK(E2)} (Composite key from both entity PKs) 5. ADD two foreign key constraints: FOREIGN KEY (e1_pk_columns) REFERENCES E1_table(pk) FOREIGN KEY (e2_pk_columns) REFERENCES E2_table(pk) 6. ADD any relationship attributes as columns in R_table 7. SET referential actions: Typically ON DELETE CASCADE for junction tables (Relationship instance meaningless if either entity deleted)Example: EMPLOYEE Works On PROJECT (M:N)
Employees work on multiple projects; projects have multiple employees
**WORKS_ON** relationship (M:N) between:
- **EMPLOYEE** (participates in many projects)
- **PROJECT** (has many employees)
Relationship attribute: **Hours** (hours worked per assignment)```sql
CREATE TABLE WORKS_ON (
EmployeeSSN CHAR(11) NOT NULL,
ProjectID INT NOT NULL,
Hours DECIMAL(5,2), -- Relationship attribute
PRIMARY KEY (EmployeeSSN, ProjectID),
FOREIGN KEY (EmployeeSSN)
REFERENCES EMPLOYEE(SSN)
ON DELETE CASCADE,
FOREIGN KEY (ProjectID)
REFERENCES PROJECT(ProjectID)
ON DELETE CASCADE
);
```Participation Constraints in M:N:
Enforcing total participation in M:N relationships is more complex than in 1:N:
- Via CHECK constraints: Most RDBMSs don't support complex subquery-based CHECK constraints
- Via triggers: Create triggers that prevent insertion of entities without corresponding junction records
- Via application logic: Enforce in the business layer (less reliable)
- Via stored procedures: Require all inserts through procedures that enforce rules
Surrogate Key Consideration:
For junction tables with many columns or frequent independent references, consider adding a surrogate primary key:
CREATE TABLE WORKS_ON (
AssignmentID INT PRIMARY KEY AUTO_INCREMENT, -- Surrogate
EmployeeSSN CHAR(11) NOT NULL,
ProjectID INT NOT NULL,
Hours DECIMAL(5,2),
UNIQUE (EmployeeSSN, ProjectID), -- Natural key as UNIQUE
-- FK constraints as before
);
This allows other tables to reference a specific assignment with a single column.
KEEP LEARNING
Keep learning for free.
Read the complete lesson, save your notes and pick up where you left off with a free account. No card needed.