Relational Model
Relational databases organize data into tables with relationships.
Relational Concepts
Table (Relation):
┌────┬─────────┬───────────┬──────┐
│ ID │ Name │ Email │ Age │
├────┼─────────┼───────────┼──────┤
│ 1 │ Alice │ a@b.com │ 25 │
│ 2 │ Bob │ b@c.com │ 30 │
│ 3 │ Charlie │ c@d.com │ 28 │
└────┴─────────┴───────────┴──────┘
Row (Tuple): A single record
Column (Attribute): A single field
Primary Key: Unique identifier (ID)
Foreign Key: Reference to another table
Relationships
One-to-One:
User (1) ←──→ (1) UserProfile
One-to-Many:
User (1) ←──→ (Many) Orders
Many-to-Many:
Student (Many) ←──→ (Many) Courses
(through junction table)
SQL Schema Example
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total DECIMAL(10,2),
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE order_items (
id SERIAL PRIMARY KEY,
order_id INTEGER REFERENCES orders(id),
product_id INTEGER REFERENCES products(id),
quantity INTEGER,
price DECIMAL(10,2)
);
SQL Operations
-- CRUD Operations
INSERT INTO users (name, email) VALUES ('Alice', 'a@b.com');
SELECT * FROM users WHERE id = 1;
UPDATE users SET name = 'Alice Smith' WHERE id = 1;
DELETE FROM users WHERE id = 1;
-- Joins
SELECT u.name, o.total
FROM users u
JOIN orders o ON u.id = o.user_id;
-- Aggregation
SELECT user_id, COUNT(*) as order_count, SUM(total) as total_spent
FROM orders
GROUP BY user_id
HAVING COUNT(*) > 5;
ACID Properties
ACID ensures reliable database transactions.
ACID Overview
ACID:
A - Atomicity: All or nothing
C - Consistency: Valid state transitions
I - Isolation: Concurrent transactions don't interfere
D - Durability: Committed data persists
Atomicity
Transaction: Transfer $100 from A to B
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
If either operation fails:
→ Both operations rolled back
→ Database returns to original state
Consistency
Constraint: balance >= 0
Before: A=200, B=100
Transfer: $150 from A to B
A=200-150=50 ✓
B=100+150=250 ✓
If A would go negative:
→ Transaction rejected
→ Constraint violated
Isolation
Concurrent transactions:
T1: Read balance = 100
T2: Read balance = 100
T1: Write balance = 150 (100+50)
T2: Write balance = 80 (100-20)
Without isolation: Lost update (T1's write lost)
With isolation: Correct result
Durability
After COMMIT:
- Data written to disk
- survives crash/power failure
- WAL (Write-Ahead Logging)
- Replication
Transaction Example
BEGIN TRANSACTION;
-- Debit account
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- Credit account
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- Log transaction
INSERT INTO transactions (from_id, to_id, amount) VALUES (1, 2, 100);
COMMIT;
-- If any operation fails, ROLLBACK
Popular SQL Databases
Different SQL databases have different strengths.
Database Comparison
| Database | Strengths | Use Case |
|---|---|---|
| PostgreSQL | Features, extensibility | Complex queries, GIS, JSON |
| MySQL | Simplicity, speed | Web applications |
| SQLite | Embedded, zero-config | Mobile, embedded |
| MariaDB | MySQL fork, open source | Drop-in MySQL replacement |
| SQL Server | Enterprise features | .NET ecosystem |
PostgreSQL
Features:
- Advanced SQL (CTEs, window functions)
- JSON/JSONB support
- Full-text search
- PostGIS (geospatial)
- Extensions (TimescaleDB, Citus)
- Strong ACID compliance
Use Cases:
- Complex queries
- Data warehousing
- Geospatial applications
- Systems requiring extensibility
MySQL
Features:
- Simple, fast
- Replication support
- Large ecosystem
- InnoDB (ACID)
- MyISAM (fast reads)
Use Cases:
- Web applications
- CMS (WordPress)
- Read-heavy workloads
When to Choose SQL
Choose SQL when:
- Data is structured and relational
- ACID transactions required
- Complex queries (JOINs, aggregations)
- Data integrity critical
- Schema is stable
Examples:
- Banking systems
- E-commerce (orders, inventory)
- User management
- Content management
SQL Scaling Options
Vertical Scaling:
- More CPU, RAM, storage
- Simple but limited
Read Replicas:
- Primary for writes
- Replicas for reads
- Async replication
Sharding:
- Split data across databases
- Complex but scalable
Connection Pooling:
- Reuse connections
- Reduce overhead
Practice Problems
Design a scalable SQL Databases system. Cover high-level architecture, data model, and API design.
Solution
// Complete system design:
// - Functional + Non-functional requirements
// - Capacity estimation
// - Data model (SQL/NoSQL choice)
// - API endpoints
// - Component architecture
// - Scaling strategy
// - Monitoring & reliabilityHow would you scale SQL Databases to handle 10x the current load? Identify bottlenecks and solutions.
Solution
// Scaling approach:
// 1. Load balancing
// 2. Database sharding/replication
// 3. Cache layer (Redis)
// 4. CDN for static assets
// 5. Async processing (queues)
// 6. Microservices decompositionAnalyze potential failure modes for SQL Databases and design mitigation strategies.
Solution
// Failure mitigation:
// 1. Redundancy (multi-AZ)
// 2. Circuit breakers
// 3. Retry with backoff
// 4. Dead letter queues
// 5. Health checks
// 6. Graceful degradationQuiz
1. What does ACID stand for?
2. When should you choose a SQL database?
3. What is atomicity in a database transaction?
4. What is the difference between PostgreSQL and MySQL?
Flashcards
Question
What is a relational database?
Click to reveal answer
Answer
Organizes data into tables (relations) with rows and columns. Tables have relationships via primary and foreign keys. Supports SQL for querying.
Question
What are ACID properties?
Click to reveal answer
Answer
Atomicity (all or nothing), Consistency (valid state), Isolation (concurrent safety), Durability (persists after commit). Ensures reliable transactions.
Question
When should you choose PostgreSQL?
Click to reveal answer
Answer
When you need advanced features: complex queries, JSON/JSONB, GIS, full-text search, extensibility. Best for complex, feature-rich applications.
Question
What are SQL scaling options?
Click to reveal answer
Answer
Vertical scaling (bigger server), Read replicas (reads), Sharding (horizontal split), Connection pooling (reuse connections).
Question
What is SQL Databases?
Click to reveal answer
Answer
SQL Databases is a key concept in system design.
Revision Notes
Key Takeaways
- 1.Relational databases organize data into tables with relationships
- 2.ACID ensures reliable transactions (Atomicity, Consistency, Isolation, Durability)
- 3.PostgreSQL for complex features, MySQL for simplicity
- 4.SQL is best for structured data with complex queries
- 5.Scaling options: vertical, read replicas, sharding, connection pooling
Interview Tips
- •Default to SQL unless you have specific NoSQL requirements
- •Discuss ACID requirements for financial/transactional data
- •Consider read replicas for read-heavy workloads
- •Mention sharding only when vertical scaling and replicas aren't enough
Cheat Sheet
SQL Databases - Cheat Sheet
Relational Model:
- Tables with rows and columns
- Primary keys (unique ID)
- Foreign keys (relationships)
- JOINs for combining tables
ACID:
A: Atomicity - All or nothing
C: Consistency - Valid state
I: Isolation - Concurrent safety
D: Durability - Persists after commit
Popular SQL Databases:
| Database | Strength |
|---|---|
| PostgreSQL | Features, extensibility |
| MySQL | Simplicity, speed |
| SQLite | Embedded, zero-config |
Choose SQL When:
- Structured, relational data
- ACID transactions needed
- Complex queries (JOINs)
- Data integrity critical