Introduction
We use ER diagrams to plan how data is organized. Mapping them to tables helps us create the actual database structure.
Jump into concepts and practice - no test required
-- Basic steps to map ER diagram elements to tables -- 1. Each entity becomes a table -- 2. Each attribute becomes a column -- 3. Primary keys become primary keys in tables -- 4. Relationships become foreign keys or new tables CREATE TABLE EntityName ( PrimaryKeyColumn datatype PRIMARY KEY, Attribute1 datatype, Attribute2 datatype, ... ); -- For many-to-many relationships, create a new table with foreign keys CREATE TABLE RelationshipName ( Entity1_ID datatype, Entity2_ID datatype, PRIMARY KEY (Entity1_ID, Entity2_ID), FOREIGN KEY (Entity1_ID) REFERENCES Entity1(PrimaryKey), FOREIGN KEY (Entity2_ID) REFERENCES Entity2(PrimaryKey) );
CREATE TABLE Student ( StudentID INT PRIMARY KEY, Name VARCHAR(100), Age INT );
CREATE TABLE Course ( CourseID INT PRIMARY KEY, Title VARCHAR(100), Credits INT );
CREATE TABLE Enrollment ( StudentID INT, CourseID INT, PRIMARY KEY (StudentID, CourseID), FOREIGN KEY (StudentID) REFERENCES Student(StudentID), FOREIGN KEY (CourseID) REFERENCES Course(CourseID) );
CREATE TABLE Author ( AuthorID INT PRIMARY KEY, Name VARCHAR(100) ); CREATE TABLE Book ( BookID INT PRIMARY KEY, Title VARCHAR(100), AuthorID INT, FOREIGN KEY (AuthorID) REFERENCES Author(AuthorID) );
Author(id, name) and Book(id, title, author_id) with a one-to-many relationship from Author to Book, what will be the result of this SQL query?SELECT a.name, b.title FROM Author a JOIN Book b ON a.id = b.author_id WHERE a.name = 'Alice';Student(id, name) and Enrollment(student_id, course_id). You want to add a foreign key constraint to Enrollment.student_id. Which SQL statement is correct?Employee(emp_id, name), Project(proj_id, title), and a many-to-many relationship WorksOn between them. How should you map this relationship into tables?