⚡0 XP🔥0

Database Design and Normalization

Lesson 10 of 10 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs SQL

Design a database from requirements - entities, relationships (1:1, 1:N, M:N), ER diagrams, anomalies, and normalization to 1NF, 2NF and 3NF - plus a mini project and common SQL interview questions.

Writing queries is half the job; the other half is designing tables so that data stays correct, is stored once, and is easy to query. Bad design causes duplicated data, contradictions and painful queries forever.

Step 1: find the entities and attributes#

From the requirement "A college has departments. Students belong to a department and enrol in courses offered by departments. Each enrollment records marks. Faculty work in departments and report to a senior faculty member.":

Entity Attributes
Department dept_id, name, building
Student student_id, name, city, cgpa, dept_id
Course course_id, title, credits, dept_id
Faculty faculty_id, name, salary, dept_id, reports_to
Enrollment student_id, course_id, marks, grade

Step 2: relationships#

Type Example How to store it
One-to-one (1:1) student ↔ hostel locker FK with a UNIQUE constraint, or same table
One-to-many (1:N) department → students FK on the "many" side (students.dept_id)
Many-to-many (M:N) students ↔ courses a junction table (enrollments) with two FKs
Self (recursive) faculty → manager FK to the same table (faculty.reports_to)
 DEPARTMENT 1 ──────< STUDENT >────── ENROLLMENT ──────< COURSE >────── 1 DEPARTMENT
     1                    (M:N through ENROLLMENT)
     └──────< FACULTY ──┐
                 ▲      │ reports_to
                 └──────┘
हिंदी में समझें

Design करते समय पहले "चीज़ें" (entities) पहचानें - Student, Course, Department - और फिर उनके रिश्ते। एक department में कई students (1:N) - तो dept_id students table में जाता है। एक student कई courses और एक course में कई students (M:N) - तो बीच में एक अलग table (enrollments) बनती है।

Why normalise? Anomalies in a badly designed table#

Imagine everything in one wide table:

student_id name dept_name dept_building courses
101 Aarav Computer Science Block A CS101, MB101
102 Diya Computer Science Block A CS102
104 Sneha Electronics Block B EC101, EC201

Problems:

  • Update anomaly - Computer Science moves to Block E: you must change many rows; miss one and the data contradicts itself.
  • Insert anomaly - you cannot record the new Data Science department until it has a student.
  • Delete anomaly - delete Sneha (the only Electronics student) and you lose the fact that Electronics is in Block B.
  • The courses cell holds a list - you cannot easily join, count or index it.

Normalization splits the table so that each fact is stored exactly once.

First Normal Form (1NF)#

  • Every cell holds one atomic value (no lists, no repeating groups like course1, course2, course3 columns).
  • Each row is unique (there is a primary key).

Fix: one row per student-course pair (later moved to enrollments).

Second Normal Form (2NF)#

  • In 1NF, and
  • every non-key column depends on the whole primary key (no partial dependency).

If the key of the enrollment rows is (student_id, course_id), then student name depends only on student_id - a partial dependency. Fix: move student data to students and course data to courses; keep only marks, grade in enrollments.

Third Normal Form (3NF)#

  • In 2NF, and
  • no non-key column depends on another non-key column (no transitive dependency).

In students(student_id, name, dept_id, dept_name, dept_building), dept_building depends on dept_id, which depends on student_id. Fix: move department columns to a departments table. That is exactly the college database you have been using.

Tip

A memory aid for 3NF: every non-key column must depend on "the key, the whole key, and nothing but the key".

Note

Denormalization - deliberately duplicating some data - is sometimes used in analytics and reporting databases (data warehouses, star schemas) to make reads faster. Start normalised; denormalise only for a measured reason.

Mini project: college reports#

Use everything from this course to produce real reports from the college database.

▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Common SQL interview questions#

  1. Second highest salary - SELECT MAX(salary) FROM faculty WHERE salary < (SELECT MAX(salary) FROM faculty); or DENSE_RANK().
  2. Find duplicates - GROUP BY col HAVING COUNT(*) > 1.
  3. Top N per group - CTE + ROW_NUMBER() OVER (PARTITION BY ...).
  4. Rows without a match - LEFT JOIN ... WHERE right.id IS NULL or NOT EXISTS.
  5. WHERE vs HAVING, DELETE vs TRUNCATE vs DROP, UNION vs UNION ALL, INNER vs LEFT JOIN.
  6. What is an index / a view / a transaction / ACID?
  7. Normalization - explain 1NF, 2NF, 3NF with an example.
▶ Try it Yourselfdatabase: collegeSQL
Ctrl + Enter to run

Summary#

  • Design from entities and relationships: FKs for 1:N, junction tables for M:N, self-FKs for hierarchies.
  • Unnormalised tables cause update, insert and delete anomalies.
  • 1NF = atomic values; 2NF = no partial dependencies; 3NF = no transitive dependencies.
  • You can now model a database and answer real questions from it with SQL - congratulations on completing the course!

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Department report (mini project)

For every department (including those with no students) show department, number of students, number of courses, and number of faculty. Order by department name. Hint - count distinct ids after LEFT JOINs, or use subqueries.

Database: college (see the tables in this lesson)
2

Student result summary (mini project)

For each student with at least one enrollment, show name, number of courses as courses, average marks as avg_marks (1 decimal) and result: PASS if they have no grade F, else FAIL. Order by avg_marks descending, then name.

Database: college (see the tables in this lesson)

Quick Quiz

Q1.

How is a many-to-many relationship (students ↔ courses) stored?

Q2.

A table is in 1NF when...

Q3.

2NF removes...

Q4.

3NF removes...

Q5.

What is an update anomaly?