<< back to Guides

๐Ÿง  Relational Database Design โ€“ In-Depth Guide

Relational databases are one of the most commonly used systems for storing structured data. Designing them well is crucial for scalability, maintainability, and query performance.


๐Ÿงพ What is SQL?

SQL (Structured Query Language) is the standard language used to interact with relational databases. It supports operations like:


๐Ÿ”‘ Keys in Relational Databases

1. Primary Key

CREATE TABLE users (
  id INT PRIMARY KEY,
  username VARCHAR(100) UNIQUE
);

2. Natural Key

3. Surrogate Key

4. Foreign Key

CREATE TABLE orders (
  id INT PRIMARY KEY,
  user_id INT,
  FOREIGN KEY (user_id) REFERENCES users(id)
);

๐Ÿ” Relationship Types

Type Description Example
One-to-One Each record links to one in the other table User โ†’ Profile
One-to-Many One record maps to multiple in another User โ†’ Orders
Many-to-Many Requires a join table Students โ†” Courses
// Join table example
CREATE TABLE student_courses (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES students(id),
  FOREIGN KEY (course_id) REFERENCES courses(id)
);

๐Ÿ”— JOIN Types

Type Description
INNER JOIN Returns only matching records
LEFT JOIN Returns all records from left + matches
RIGHT JOIN Returns all records from right + matches
FULL JOIN All records with matches or NULLs
CROSS JOIN Cartesian product of two tables
SELF JOIN A table joined to itself
SELECT u.name, o.amount
FROM users u
INNER JOIN orders o ON u.id = o.user_id;

๐Ÿ“ Normalization

Normalization reduces data redundancy and improves data integrity by structuring the data into logical tables.

Normal Form Description
1NF Atomic values, no repeating groups
2NF 1NF + No partial dependency on composite keys
3NF 2NF + No transitive dependencies

โœ… Normalize for integrity
โ— Denormalize for performance (carefully)


โœ… Best Practices

โœ” Use Meaningful Table and Column Names

โœ” Prefer Surrogate Keys for Simplicity

โœ” Enforce Constraints

โœ” Index Important Columns

CREATE INDEX idx_user_id ON orders(user_id);

โœ” Avoid EAV and Over-Normalization

โœ” Back Your Schema With Migrations


๐Ÿ—ƒ๏ธ Example Schema

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100) UNIQUE
);

CREATE TABLE posts (
  id SERIAL PRIMARY KEY,
  user_id INT REFERENCES users(id),
  content TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

๐Ÿ“˜ Learning Resources


<< back to Guides