DBMS How to Convert ER Diagram to Table Easily
CREATE TABLE statements.Examples
How to Think About It
Algorithm
Code
CREATE TABLE Student ( RollNo INT PRIMARY KEY, Name VARCHAR(50), Age INT ); CREATE TABLE Course ( CourseID INT PRIMARY KEY, Title VARCHAR(100) ); CREATE TABLE Enroll ( RollNo INT, CourseID INT, PRIMARY KEY (RollNo, CourseID), FOREIGN KEY (RollNo) REFERENCES Student(RollNo), FOREIGN KEY (CourseID) REFERENCES Course(CourseID) ); -- Tables created for Student, Course, and Enroll relationship
Dry Run
Let's trace creating tables for Student, Course, and Enroll relationship from the ER diagram.
Create Student table
Student table with RollNo as primary key and columns Name, Age
Create Course table
Course table with CourseID as primary key and column Title
Create Enroll table
Enroll table with RollNo and CourseID as foreign keys and composite primary key
| Table | Columns | Primary Key | Foreign Keys |
|---|---|---|---|
| Student | RollNo, Name, Age | RollNo | None |
| Course | CourseID, Title | CourseID | None |
| Enroll | RollNo, CourseID | RollNo, CourseID | RollNo->Student, CourseID->Course |
Why This Works
Step 1: Entity to Table
Each entity in the ER diagram becomes a table with its attributes as columns to store data.
Step 2: Primary Key Selection
Choose a unique attribute as the primary key to identify each record in the table.
Step 3: Relationship Mapping
Relationships are represented by foreign keys or separate tables for many-to-many relationships to link entities.
Alternative Approaches
CREATE TABLE Department ( DeptID INT PRIMARY KEY, DeptName VARCHAR(50) ); CREATE TABLE Employee ( EmpID INT PRIMARY KEY, Name VARCHAR(50), DeptID INT, FOREIGN KEY (DeptID) REFERENCES Department(DeptID) );
CREATE TABLE Person ( ID INT PRIMARY KEY, Name VARCHAR(50), CourseID INT NULL, DeptID INT NULL );
Complexity: O(n) time, O(n) space
Time Complexity
Converting ER diagram to tables involves processing each entity and relationship once, so it is linear in the number of entities and relationships.
Space Complexity
Space depends on the number of tables and attributes created, proportional to the ER diagram size.
Which Approach is Fastest?
Direct mapping of entities and relationships to tables is fastest and simplest; alternatives may trade speed for design flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct Mapping | O(n) | O(n) | Clear ER diagrams with distinct entities |
| Nested Tables | O(n) | O(n) | Handling weak entities with dependencies |
| Single Table with Nullable Columns | O(n) | O(n) | Simple schemas with few relationships |