NullSector NullSector

Database Fundamentals

Data is the heart of every application. Understanding databases isn't just about storing informationβ€”it's about structuring knowledge, ensuring integrity, optimizing performance, and making data accessible across your entire stack.

Why Databases Exist: The Problem They Solve

Imagine you're building an e-commerce platform. You need to store products, users, orders, payment info, reviews, and more. You could use text files, JSON files, or keep everything in memoryβ€”but you'd quickly run into serious problems.

The Filing Cabinet Metaphor

Think of a database like a highly organized filing cabinet system in a massive office building. You could throw all your papers into cardboard boxes in a warehouse (text files), but finding a specific document would require searching through every box. A filing cabinet (database) gives you:

  • Organization - Papers are categorized, labeled, and indexed
  • Quick Access - You can find any document in seconds, not hours
  • Security - Drawers can be locked, access can be controlled
  • Concurrent Use - Multiple people can access different drawers simultaneously
  • Backup - You can photocopy the entire system for disaster recovery

The Problem with File Storage

Let's look at what happens when you try to build an application using simple files:

// Storing user data in a text file (DON'T DO THIS) users.txt: john,john@email.com,password123,premium jane,jane@email.com,pass456,free bob,bob@email.com,qwerty,premium // Problems: // 1. How do you find Bob's email quickly? // β†’ Must read entire file line by line // // 2. How do you update John's subscription? // β†’ Must read entire file, modify, write entire file back // // 3. What if two processes update simultaneously? // β†’ Data corruption, one update overwrites the other // // 4. How do you ensure passwords are unique? // β†’ Must check every line manually // // 5. What if the file is 10GB? // β†’ Loading into memory crashes your application // // 6. How do you relate users to their orders? // β†’ No built-in way to link data across files
// Using JSON files is slightly better, but still problematic { "users": [ { "id": 1, "name": "John", "email": "john@email.com", "subscription": "premium" } ] } // Problems: // - Still need to load entire file to query // - No indexing = slow searches // - No concurrency control // - No built-in relationships // - No data validation // - No atomic operations

The Problem with In-Memory Storage

// Storing everything in memory (Python dict/list) users = { 1: {"name": "John", "email": "john@email.com"}, 2: {"name": "Jane", "email": "jane@email.com"} } orders = { 1: {"user_id": 1, "product": "Laptop", "price": 1200}, 2: {"user_id": 1, "product": "Mouse", "price": 25} } // Problems: // 1. Data disappears when application restarts // 2. Can't store more data than available RAM // 3. Can't share data between multiple servers // 4. No persistence or backup // 5. Lost forever if application crashes

🎯 What Databases Provide

Databases solve all these problems by providing:

  • Persistence - Data survives application restarts
  • Concurrency - Multiple users can access data simultaneously
  • Efficient Querying - Find data instantly with indexes
  • Data Integrity - Enforce rules and relationships
  • Transactions - All-or-nothing operations
  • Scalability - Handle millions of records
  • Security - Built-in access control
  • Backup & Recovery - Never lose data

Database Types: A Complete Overview

Not all databases are created equal. Different types excel at different tasks. Here's the complete landscape:

πŸ—„οΈ Relational Databases (SQL)

Examples: PostgreSQL, MySQL, SQLite, Oracle, SQL Server

Structure: Tables with rows and columns, strict schemas, relationships via foreign keys

Best For: Financial systems, e-commerce, traditional web apps, anything requiring complex relationships and data integrity

Strengths: ACID compliance, powerful queries with JOIN operations, mature ecosystem, well-understood

Weaknesses: Rigid schemas, scaling horizontally is complex, can be slower for simple reads

πŸ“„ Document Databases

Examples: MongoDB, CouchDB, Firestore, DocumentDB

Structure: JSON-like documents, flexible schemas, nested data structures

Best For: Content management, catalogs, user profiles, real-time apps, rapid prototyping

Strengths: Schema flexibility, easy horizontal scaling, intuitive for developers, fast reads

Weaknesses: Less powerful queries, potential data duplication, eventual consistency

πŸ”‘ Key-Value Stores

Examples: Redis, Memcached, DynamoDB, Riak

Structure: Simple key β†’ value pairs, extremely fast lookups

Best For: Caching, session storage, real-time analytics, rate limiting, leaderboards

Strengths: Blazing fast, simple to use, excellent for caching, high performance

Weaknesses: Limited querying, no complex relationships, usually ephemeral data

πŸ•ΈοΈ Graph Databases

Examples: Neo4j, ArangoDB, Amazon Neptune, OrientDB

Structure: Nodes and edges representing entities and relationships

Best For: Social networks, recommendation engines, fraud detection, knowledge graphs, network analysis

Strengths: Excellent for relationship-heavy data, fast traversals, intuitive modeling

Weaknesses: Specialized use case, smaller ecosystem, steeper learning curve

⏰ Time-Series Databases

Examples: InfluxDB, TimescaleDB, Prometheus, OpenTSDB

Structure: Optimized for time-stamped data, automatic aggregation

Best For: IoT sensors, monitoring systems, financial tickers, analytics, metrics

Strengths: Optimized for time-range queries, excellent compression, built-in aggregations

Weaknesses: Specialized use case, not general-purpose, limited flexibility

πŸ” Search Engines

Examples: Elasticsearch, Solr, Meilisearch, Typesense

Structure: Inverted indexes for full-text search, document-oriented

Best For: Search functionality, log analysis, text analytics, autocomplete

Strengths: Powerful full-text search, relevance ranking, fast queries, faceted search

Weaknesses: Not suitable as primary database, eventual consistency, resource-intensive

πŸ“Š Column-Family Stores

Examples: Cassandra, HBase, ScyllaDB

Structure: Data organized by columns, optimized for write-heavy workloads

Best For: Time-series data at scale, messaging apps, sensor data, high write throughput

Strengths: Excellent write performance, horizontal scalability, handles massive datasets

Weaknesses: Complex to operate, limited query flexibility, eventual consistency

πŸ’Ύ Embedded Databases

Examples: SQLite, LevelDB, RocksDB, Berkeley DB

Structure: Runs in-process, no separate server, single file

Best For: Mobile apps, desktop applications, single-user apps, testing

Strengths: Zero configuration, no server needed, fast, portable

Weaknesses: Single-user typically, limited concurrency, not for distributed systems

When to Use What: The Decision Tree

Choosing the right database is critical. Here's a practical decision framework:

πŸ€” Decision Framework

Start with these questions:

  1. What's your primary access pattern? (How will you query the data?)
  2. How important is consistency? (Can you tolerate eventual consistency?)
  3. What's your scale? (Thousands or millions of users?)
  4. How structured is your data? (Fixed schema or evolving?)
  5. What's your team's expertise? (SQL vs NoSQL experience?)

The Tool Analogy

Choosing a database is like choosing tools for a job:

  • Relational DB = Swiss Army Knife - Versatile, reliable, handles 80% of use cases
  • Document DB = Power Drill - Excellent for specific tasks, fast when used correctly
  • Key-Value Store = Hammer - Simple, fast, perfect for its specific purpose
  • Graph DB = Specialized Saw - Perfect for specific cuts, overkill for general use

Most projects need multiple tools. Start with the Swiss Army Knife (PostgreSQL), add specialized tools as needed.

Real-World Scenario Decision Making

Scenario: E-Commerce Platform

Requirements:

  • Product catalog with categories
  • User accounts and orders
  • Shopping cart
  • Payment processing
  • Inventory management

Best Choice: PostgreSQL (Relational)

Why: Strong data relationships (users β†’ orders β†’ products), transactions are critical for payments, need ACID guarantees, inventory requires accurate counts

Additional: Add Redis for session storage and cart caching, Elasticsearch for product search

Scenario: Social Media App

Requirements:

  • User profiles with varied fields
  • Posts, comments, likes
  • Friend connections
  • News feed generation
  • Real-time updates

Best Choice: MongoDB + Neo4j

Why: MongoDB for flexible user profiles and posts (schema changes frequently), Neo4j for friend relationships and feed generation (graph traversal is perfect for "friends of friends")

Additional: Redis for real-time notifications and caching

Scenario: IoT Sensor Platform

Requirements:

  • Millions of sensor readings/hour
  • Time-based queries common
  • Aggregations (avg, max, min)
  • Data retention policies
  • Real-time dashboards

Best Choice: InfluxDB (Time-Series)

Why: Optimized for time-stamped data, excellent compression, built-in aggregations and downsampling, automatic retention policies

Additional: PostgreSQL for device metadata and user management

Scenario: Content Management System

Requirements:

  • Articles with varied structures
  • Media attachments
  • Categories and tags
  • Full-text search
  • Multi-language support

Best Choice: MongoDB + Elasticsearch

Why: MongoDB handles flexible article structures well, Elasticsearch provides powerful search with relevance ranking, multilingual support

Additional: CDN for media storage (not a database, but essential)

Scenario: Analytics Dashboard

Requirements:

  • Millions of events tracked
  • Complex aggregations
  • Historical analysis
  • Real-time metrics
  • Custom reports

Best Choice: ClickHouse or TimescaleDB

Why: Column-oriented storage for fast aggregations, optimized for analytical queries, handles massive write throughput

Additional: Redis for real-time counters, PostgreSQL for user management

Scenario: Gaming Leaderboard

Requirements:

  • Real-time score updates
  • Fast leaderboard retrieval
  • Millions of players
  • Rankings and scores
  • Sub-millisecond queries

Best Choice: Redis (Key-Value)

Why: In-memory speed, sorted sets perfect for leaderboards, atomic increments for scores, handles high concurrency

Additional: PostgreSQL for player profiles and game history

ACID Properties: The Foundation of Reliability

ACID is a set of properties that guarantee database transactions are processed reliably. This is what separates professional databases from amateur file storage.

The Bank Transfer Analogy

Imagine transferring $100 from your checking to savings account. ACID properties ensure:

  • Atomicity - Either both accounts are updated, or neither is (no money disappears)
  • Consistency - Your total balance stays the same (no money created from nothing)
  • Isolation - Other transactions don't see half-completed transfer
  • Durability - Once confirmed, the transfer survives power outages

Without ACID, your money could vanish, duplicate, or corrupt. The same applies to your application data.

A - Atomicity (All or Nothing)

What is Atomicity?

A transaction is atomic if it's treated as a single, indivisible operation. Either all steps succeed, or none do. There's no "partial success."

-- Example: Processing an order BEGIN TRANSACTION; -- Step 1: Deduct from inventory UPDATE products SET stock = stock - 1 WHERE id = 42; -- Step 2: Create order record INSERT INTO orders (user_id, product_id, price) VALUES (7, 42, 99.99); -- Step 3: Charge payment INSERT INTO payments (order_id, amount, status) VALUES (LAST_INSERT_ID(), 99.99, 'pending'); COMMIT; -- If ANY step fails: -- - Inventory is NOT deducted -- - Order is NOT created -- - Payment is NOT charged -- Everything rolls back automatically
// Without atomicity (dangerous!) // Step 1: Deduct inventory βœ“ // Step 2: Create order βœ“ // Step 3: Charge payment βœ— FAILS // Result: Customer charged nothing, but inventory decreased! // You lost a product and gained no money. // With atomicity: // Payment fails β†’ Entire transaction rolls back // Inventory unchanged, no order created // Database state is consistent

C - Consistency (Rules Always Apply)

What is Consistency?

The database enforces all defined rules (constraints, triggers, cascades). You can never put the database in an invalid state.

-- Define constraints that enforce business rules CREATE TABLE accounts ( id SERIAL PRIMARY KEY, balance DECIMAL(10,2) NOT NULL, CHECK (balance >= 0) -- Never allow negative balance ); CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INT NOT NULL, total DECIMAL(10,2) NOT NULL CHECK (total > 0), FOREIGN KEY (user_id) REFERENCES users(id) ); -- Consistency guarantees: -- 1. You cannot create an order with negative total -- 2. You cannot create an order for non-existent user -- 3. You cannot set account balance below zero -- 4. All foreign keys always point to valid records
-- Example of consistency in action BEGIN TRANSACTION; -- Try to set negative balance UPDATE accounts SET balance = -100 WHERE id = 1; -- ❌ ERROR: Constraint violation -- Transaction automatically rolled back -- Try to create order for non-existent user INSERT INTO orders (user_id, total) VALUES (99999, 50.00); -- ❌ ERROR: Foreign key violation -- Transaction automatically rolled back -- Database state remains consistent -- Invalid data never enters the system

I - Isolation (Transactions Don't Interfere)

What is Isolation?

Concurrent transactions don't interfere with each other. Each transaction acts as if it's the only one running, even when thousands execute simultaneously.

-- Without isolation (RACE CONDITION!) -- Product has 1 item in stock -- Two customers click "Buy" at the exact same time Customer A Transaction: Customer B Transaction: 1. Read stock: 1 1. Read stock: 1 2. Check if available: YES 2. Check if available: YES 3. Deduct: stock = 0 3. Deduct: stock = 0 4. Create order βœ“ 4. Create order βœ“ -- PROBLEM: Both got the same item! -- You oversold and now must disappoint a customer
-- With isolation (CORRECT!) -- Database uses locks or versioning Customer A Transaction: Customer B Transaction: 1. Lock row 1. Wait for lock... 2. Read stock: 1 3. Check: available 4. Deduct: stock = 0 5. Create order βœ“ 6. Unlock 2. Lock row 3. Read stock: 0 4. Check: NOT available 5. Return "Out of stock" 6. Unlock -- CORRECT: Only one customer gets the item -- No overselling, consistent state

D - Durability (Committed = Permanent)

What is Durability?

Once a transaction commits, the changes are permanent. Even if the server crashes, power fails, or database restarts, committed data survives.

-- When you see "Transaction committed" -- The database guarantees: BEGIN TRANSACTION; INSERT INTO orders (user_id, total) VALUES (42, 99.99); UPDATE inventory SET stock = stock - 1 WHERE id = 10; COMMIT; -- βœ“ "Transaction committed successfully" -- From this moment forward: -- 1. Data is written to persistent storage (disk) -- 2. Data survives server crash -- 3. Data survives power failure -- 4. Data is replicated to backups -- 5. You can safely tell the customer "Order confirmed" -- Even if the server explodes 1ms later, -- when it restarts, the order will be there

Why ACID Matters in Real Applications

Consider what happens without ACID:

  • Banking: Money disappears or duplicates during transfers
  • E-commerce: Orders created but inventory not deducted (overselling)
  • Social Media: Post counts don't match actual posts
  • Gaming: Player scores corrupt, achievements lost
  • Healthcare: Patient records inconsistent, prescriptions lost

ACID properties are why you trust databases with your critical data. NoSQL databases often sacrifice some ACID properties for speed or scalabilityβ€”understand the tradeoffs before choosing.

Database Terminology: Speaking the Language

Understanding database terminology is essential for effective communication and learning. Here are the fundamental concepts:

πŸ“Š Table (Relation)

A collection of related data organized in rows and columns. Like a spreadsheet, but with enforced structure and relationships.

users table: +----+-------+------------------+ | id | name | email | +----+-------+------------------+ | 1 | Alice | alice@email.com | | 2 | Bob | bob@email.com | +----+-------+------------------+

πŸ“ Row (Record/Tuple)

A single entry in a table representing one entity. Each row contains values for all columns defined in the table.

One row: id: 1 name: Alice email: alice@email.com created: 2024-01-15

πŸ“‹ Column (Field/Attribute)

A single piece of data stored in every row. Columns have a defined data type (integer, text, date, etc.)

email column: alice@email.com bob@email.com charlie@email.com Type: VARCHAR(255) Constraint: NOT NULL, UNIQUE

πŸ”‘ Primary Key

A unique identifier for each row. No two rows can have the same primary key. Usually an auto-incrementing ID.

CREATE TABLE users ( id SERIAL PRIMARY KEY, -- ensures id is unique -- prevents NULL values -- auto-increments name TEXT );

πŸ”— Foreign Key

A column that references the primary key of another table, creating relationships between tables.

CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INT, FOREIGN KEY (user_id) REFERENCES users(id) -- ensures user exists -- maintains referential integrity );

πŸ“‘ Index

A data structure that makes searching faster. Like a book's index, it lets you find data without scanning every row.

-- Without index: scan all rows SELECT * FROM users WHERE email = 'alice@email.com'; -- Time: O(n) -- With index: direct lookup CREATE INDEX idx_email ON users(email); -- Time: O(log n) or O(1)

πŸ—‚οΈ Schema

The blueprint of your database: all tables, columns, data types, relationships, and constraints. Defines the structure.

Database Schema: β”œβ”€β”€ users table β”‚ β”œβ”€β”€ id (PRIMARY KEY) β”‚ β”œβ”€β”€ email (UNIQUE) β”‚ └── created_at β”œβ”€β”€ orders table β”‚ β”œβ”€β”€ id (PRIMARY KEY) β”‚ β”œβ”€β”€ user_id (FOREIGN KEY) β”‚ └── total └── products table

⚑ Query

A request for data from the database. Written in SQL (for relational databases) or database-specific query language.

-- Select query SELECT name, email FROM users WHERE created_at > '2024-01-01'; -- Returns matching rows

πŸ”„ Transaction

A sequence of operations treated as a single unit. Either all succeed (COMMIT) or all fail (ROLLBACK).

BEGIN TRANSACTION; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- All or nothing

🧩 Join

Combining data from multiple tables based on relationships. Essential for working with relational data.

SELECT users.name, orders.total FROM users JOIN orders ON users.id = orders.user_id; -- Combines related data

🎯 Constraint

Rules that enforce data integrity. Prevent invalid data from entering the database.

CREATE TABLE products ( price DECIMAL CHECK (price > 0), stock INT CHECK (stock >= 0), name TEXT NOT NULL UNIQUE ); -- Enforces business rules

πŸ“Έ View

A virtual table based on a query. Acts like a table but doesn't store dataβ€”computed on demand.

CREATE VIEW active_users AS SELECT * FROM users WHERE last_login > NOW() - INTERVAL '30 days'; -- Query like a table SELECT * FROM active_users;

πŸ”’ Lock

Prevents concurrent transactions from interfering. Ensures isolation by blocking access to data being modified.

-- Row-level lock SELECT * FROM inventory WHERE id = 1 FOR UPDATE; -- Locks this row -- Others must wait

βš™οΈ Stored Procedure

Precompiled SQL code stored in the database. Functions that can be called to perform complex operations.

CREATE PROCEDURE process_order( IN user_id INT, IN product_id INT ) BEGIN -- Complex logic here END;

πŸŽͺ Trigger

Automatic actions that execute when certain events occur (INSERT, UPDATE, DELETE). Used for automation and auditing.

CREATE TRIGGER update_timestamp BEFORE UPDATE ON users FOR EACH ROW SET NEW.updated_at = NOW(); -- Auto-updates timestamp

πŸ“¦ Normalization

The process of organizing data to reduce redundancy and improve integrity. Breaking data into logical, related tables.

-- Unnormalized (bad) orders: [name, email, product] -- Normalized (good) users: [id, name, email] orders: [id, user_id, product_id] products: [id, name]

ASCII Diagram: How Databases Work Internally

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ CLIENT APPLICATION β”‚ β”‚ β”‚ β”‚ Python/Node.js/Java code making database requests β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ SQL Query / Connection β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ DATABASE MANAGEMENT SYSTEM β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Query Parser & Optimizer β”‚ β”‚ β”‚ β”‚ β€’ Parses SQL β”‚ β”‚ β”‚ β”‚ β€’ Creates execution plan β”‚ β”‚ β”‚ β”‚ β€’ Optimizes for performance β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Transaction Manager β”‚ β”‚ β”‚ β”‚ β€’ Ensures ACID properties β”‚ β”‚ β”‚ β”‚ β€’ Manages locks β”‚ β”‚ β”‚ β”‚ β€’ Handles concurrency β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ Storage Engine β”‚ β”‚ β”‚ β”‚ β€’ Reads/writes data β”‚ β”‚ β”‚ β”‚ β€’ Manages indexes β”‚ β”‚ β”‚ β”‚ β€’ Buffer pool (memory cache) β”‚ β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β” β”‚ Data Files β”‚ β”‚ Indexes β”‚ β”‚ Write-Ahead β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ Log β”‚ β”‚ (On Disk) β”‚ β”‚ (On Disk) β”‚ β”‚ (On Disk) β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ β”‚ users.dat β”‚ β”‚ idx_email β”‚ β”‚ transactionsβ”‚ β”‚ orders.dat β”‚ β”‚ idx_user β”‚ β”‚ logged β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Real-World Scenarios Deep Dive

πŸ›’ E-Commerce Platform Database Architecture

Core Requirements:

  • Product catalog with categories, images, specifications
  • User accounts with addresses, payment methods
  • Shopping cart (temporary)
  • Order processing with payment gateway integration
  • Inventory tracking with low-stock alerts
  • Reviews and ratings
  • Search functionality
-- E-Commerce Database Schema (PostgreSQL) -- Users table CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, name VARCHAR(100) NOT NULL, created_at TIMESTAMP DEFAULT NOW() ); -- Products table CREATE TABLE products ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, description TEXT, price DECIMAL(10,2) NOT NULL CHECK (price > 0), stock INT NOT NULL DEFAULT 0 CHECK (stock >= 0), category_id INT REFERENCES categories(id), created_at TIMESTAMP DEFAULT NOW(), INDEX idx_category (category_id), INDEX idx_name (name) -- For search ); -- Orders table CREATE TABLE orders ( id SERIAL PRIMARY KEY, user_id INT NOT NULL REFERENCES users(id), status VARCHAR(20) DEFAULT 'pending', total DECIMAL(10,2) NOT NULL, created_at TIMESTAMP DEFAULT NOW(), INDEX idx_user (user_id), INDEX idx_status (status) ); -- Order items (many-to-many relationship) CREATE TABLE order_items ( id SERIAL PRIMARY KEY, order_id INT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, product_id INT NOT NULL REFERENCES products(id), quantity INT NOT NULL CHECK (quantity > 0), price DECIMAL(10,2) NOT NULL -- Snapshot price at time of order ); -- Complementary databases: -- β€’ Redis for shopping cart (temporary, fast) -- β€’ Elasticsearch for product search -- β€’ PostgreSQL for everything else (ACID critical)

πŸ“± Social Media Platform Database Architecture

Core Requirements:

  • User profiles with dynamic fields (bio, interests, etc.)
  • Posts with text, images, videos
  • Comments and nested replies
  • Like/reaction system
  • Follow/friend relationships
  • News feed generation
  • Real-time notifications
// Social Media Architecture (Multi-Database) // MongoDB - User profiles and content { "_id": ObjectId("..."), "username": "alice", "bio": "Developer and coffee enthusiast", "profile_pic": "https://...", "interests": ["coding", "coffee", "hiking"], // Flexible schema "settings": { "theme": "dark", "notifications": true } } // Posts collection (MongoDB) { "_id": ObjectId("..."), "user_id": ObjectId("..."), "content": "Just deployed my first app!", "media": ["https://..."], "likes": 42, "comments": [ { "user_id": ObjectId("..."), "text": "Congrats!", "timestamp": ISODate("...") } ], "created_at": ISODate("...") } // Neo4j - Relationships (graph database) CREATE (alice:User {id: 1, name: "Alice"}) CREATE (bob:User {id: 2, name: "Bob"}) CREATE (charlie:User {id: 3, name: "Charlie"}) CREATE (alice)-[:FOLLOWS]->(bob) CREATE (bob)-[:FOLLOWS]->(charlie) CREATE (charlie)-[:FOLLOWS]->(alice) // Query: Find friends of friends MATCH (me:User {id: 1})-[:FOLLOWS]->()-[:FOLLOWS]->(suggested) WHERE NOT (me)-[:FOLLOWS]->(suggested) RETURN suggested // Redis - Real-time features SET user:1:notifications:count 5 LPUSH user:1:feed "post:12345" "post:12344" "post:12343" EXPIRE user:1:feed 3600 // Cache for 1 hour

πŸ“Š Analytics & Metrics Dashboard

Core Requirements:

  • Track millions of events per day
  • Page views, clicks, conversions
  • User behavior tracking
  • Real-time dashboards
  • Historical analysis and trends
  • Custom date range queries
-- Analytics with InfluxDB (Time-Series Database) -- Data structure optimized for time-series { "measurement": "page_views", "tags": { "page": "/products", "user_id": "12345", "country": "US", "device": "mobile" }, "fields": { "duration": 45.2, "bounce": false }, "timestamp": "2024-01-15T10:30:00Z" } -- Queries are optimized for time ranges SELECT COUNT(page) FROM page_views WHERE time > now() - 24h GROUP BY time(1h), page -- Automatic aggregations and downsampling CREATE RETENTION POLICY "one_month" ON analytics DURATION 30d REPLICATION 1 -- Compress old data automatically CREATE CONTINUOUS QUERY "daily_stats" ON analytics BEGIN SELECT MEAN(duration) as avg_duration INTO daily_page_stats FROM page_views GROUP BY time(1d), page END -- Why time-series DB? -- β€’ 10x faster for time-range queries -- β€’ 90% better compression -- β€’ Built-in aggregations -- β€’ Automatic data retention

Putting It All Together: The Modern Stack

Most real-world applications use multiple databases, each optimized for specific needs:

  • PostgreSQL - Primary data store (users, core business data)
  • Redis - Caching layer, session storage, real-time features
  • Elasticsearch - Full-text search, autocomplete
  • MongoDB - Flexible documents, rapidly changing schemas
  • S3/CDN - File storage (images, videos) - not a database but essential

This is called "Polyglot Persistence"β€”using the right database for each job. Start with PostgreSQL, add others as specific needs arise.

Key Takeaways

βœ… Start Simple

Begin with PostgreSQL or SQLite. Learn SQL deeply. 80% of applications only need a relational database. Don't over-engineer.

βœ… Understand ACID

Know when you need strict consistency (financial data, orders) vs when you can relax it (social media feeds, caching). The tradeoffs matter.

βœ… Choose Based on Access Patterns

How will you query the data? Relational data with complex joins? Use SQL. Simple key lookups? Use key-value. Graph traversal? Use graph DB.

βœ… Indexes Are Critical

Databases are only fast with proper indexes. An unindexed query on 1 million rows is slow. An indexed query is instant. Always index your query conditions.

βœ… Data Modeling Matters

Time spent on good database design saves months of pain later. Normalize your data, define relationships properly, enforce constraints at the database level.

βœ… Think About Scale Early

Even if you're small now, design for growth. Use proper data types, add indexes, plan for backups. It's harder to fix a poorly designed database later.

🎯 Next Steps

Now that you understand WHY databases exist and WHEN to use each type, you're ready to learn SQL in depth. The next section covers:

  • SQL syntax from basics to advanced
  • JOINs, subqueries, and complex queries
  • Query optimization and performance
  • Transactions and concurrency
  • Real-world query patterns

Master SQL, and you master the language of data. Let's dive in.

SQL Mastery

SQL is the universal language of data. Master queries, joins, subqueries, and advanced techniques that separate database users from database experts. Learn to think in sets and transform complex data requirements into elegant SQL statements.

🎯 The Language of Data

Think of SQL as the universal translator between you and your data. While programming languages tell computers how to do things step-by-step, SQL is declarativeβ€”you describe what you want, and the database figures out the most efficient way to get it. It's like ordering at a restaurant: you don't tell the chef every cooking step, you just say "I want the salmon," and they handle the rest. This is the power of SQLβ€”you focus on the result, not the process.

🎯 Part 1: SQL Basics - Your First Queries

Every SQL journey begins with SELECT. It's the foundation of everythingβ€”retrieving data from tables, filtering results, sorting output. Let's start from absolute zero and build up to complex queries that would make database administrators nod in approval.

πŸ“˜ The SELECT Statement Structure

Every SELECT query follows this pattern:

SELECT columns FROM table WHERE conditions ORDER BY columns LIMIT number;

You don't always need every part. The simplest query is just SELECT * FROM table. But understanding this structure lets you build increasingly sophisticated queries.

Example 1: The Simplest Query

Let's start with the absolute basics. Imagine you have a table called users:

-- See everything in the users table SELECT * FROM users;

This asterisk (*) means "give me all columns." You'll see this output:

β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ id β”‚ username β”‚ email β”‚ age β”‚ β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ alice β”‚ alice@email.com β”‚ 28 β”‚ β”‚ 2 β”‚ bob β”‚ bob@email.com β”‚ 34 β”‚ β”‚ 3 β”‚ charlie β”‚ charlie@email.com β”‚ 22 β”‚ β”‚ 4 β”‚ diana β”‚ diana@email.com β”‚ 31 β”‚ β”‚ 5 β”‚ eve β”‚ eve@email.com β”‚ 29 β”‚ β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 2: Select Specific Columns

Usually you don't need everything. Pick the columns you care about:

-- Just usernames and emails SELECT username, email FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ email β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ alice@email.com β”‚ β”‚ bob β”‚ bob@email.com β”‚ β”‚ charlie β”‚ charlie@email.com β”‚ β”‚ diana β”‚ diana@email.com β”‚ β”‚ eve β”‚ eve@email.com β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ’‘ Column Selection = Focusing Your Lens

Think of SELECT as a camera lens. SELECT * is a wide-angle lensβ€”you see everything but might miss details. Selecting specific columns is like zooming in on what matters. You get less data, which means faster queries and easier-to-read results. In production, selecting only what you need can turn a 10-second query into a 1-second query.

Example 3: Column Aliases

Give columns friendly names with AS:

-- Rename columns in output SELECT username AS user_name, email AS contact_email, age AS years_old FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ user_name β”‚ contact_email β”‚ years_old β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ alice@email.com β”‚ 28 β”‚ β”‚ bob β”‚ bob@email.com β”‚ 34 β”‚ β”‚ charlie β”‚ charlie@email.com β”‚ 22 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 4: Simple WHERE Clause

Filter rows with WHERE. Only rows matching your condition appear:

-- Only users over 30 SELECT username, age FROM users WHERE age > 30;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ bob β”‚ 34 β”‚ β”‚ diana β”‚ 31 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 5: Multiple Conditions (AND)

Combine conditionsβ€”all must be true:

-- Users over 25 AND under 30 SELECT username, age FROM users WHERE age > 25 AND age < 30;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 28 β”‚ β”‚ eve β”‚ 29 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 6: Multiple Conditions (OR)

OR means at least one condition must be true:

-- Users under 25 OR over 30 SELECT username, age FROM users WHERE age < 25 OR age > 30;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ bob β”‚ 34 β”‚ β”‚ charlie β”‚ 22 β”‚ β”‚ diana β”‚ 31 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 7: ORDER BY Ascending

Sort results. Default is ascending (smallest to largest):

-- Sort by age, youngest first SELECT username, age FROM users ORDER BY age;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ charlie β”‚ 22 β”‚ β”‚ alice β”‚ 28 β”‚ β”‚ eve β”‚ 29 β”‚ β”‚ diana β”‚ 31 β”‚ β”‚ bob β”‚ 34 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 8: ORDER BY Descending

Add DESC for descending order (largest to smallest):

-- Sort by age, oldest first SELECT username, age FROM users ORDER BY age DESC;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ bob β”‚ 34 β”‚ β”‚ diana β”‚ 31 β”‚ β”‚ eve β”‚ 29 β”‚ β”‚ alice β”‚ 28 β”‚ β”‚ charlie β”‚ 22 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 9: ORDER BY Multiple Columns

Sort by one column, then another as a tiebreaker:

-- Assume we have a country column SELECT username, country, age FROM users ORDER BY country, age DESC;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ country β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ bob β”‚ Canada β”‚ 34 β”‚ β”‚ alice β”‚ Canada β”‚ 28 β”‚ β”‚ diana β”‚ USA β”‚ 31 β”‚ β”‚ eve β”‚ USA β”‚ 29 β”‚ β”‚ charlie β”‚ USA β”‚ 22 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Notice how within each country, users are sorted by age descending.

Example 10: LIMIT - Restrict Row Count

LIMIT controls how many rows you get back:

-- Get only the first 3 users SELECT username, age FROM users LIMIT 3;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 28 β”‚ β”‚ bob β”‚ 34 β”‚ β”‚ charlie β”‚ 22 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 11: LIMIT with ORDER BY

Combine them to get "top N" results:

-- Get the 3 oldest users SELECT username, age FROM users ORDER BY age DESC LIMIT 3;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ bob β”‚ 34 β”‚ β”‚ diana β”‚ 31 β”‚ β”‚ eve β”‚ 29 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

Example 12: OFFSET for Pagination

Skip rows with OFFSET, perfect for pagination:

-- Skip first 2 users, get next 2 SELECT username, age FROM users ORDER BY age LIMIT 2 OFFSET 2;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€ β”‚ eve β”‚ 29 β”‚ β”‚ diana β”‚ 31 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”˜

This is page 2 if each page shows 2 users.

Example 13: DISTINCT - Remove Duplicates

Get unique values only:

-- Get all different countries (no duplicates) SELECT DISTINCT country FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ country β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Canada β”‚ β”‚ USA β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 14: Calculations in SELECT

SQL can do math right in your query:

-- Calculate age in months SELECT username, age, age * 12 AS age_in_months, age / 10.0 AS age_in_decades FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ age β”‚ age_in_months β”‚ age_in_decades β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 28 β”‚ 336 β”‚ 2.8 β”‚ β”‚ bob β”‚ 34 β”‚ 408 β”‚ 3.4 β”‚ β”‚ charlie β”‚ 22 β”‚ 264 β”‚ 2.2 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 15: String Concatenation

Combine text columns together:

-- Create full display name SELECT username || ' (' || email || ')' AS full_info FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ full_info β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice (alice@email.com) β”‚ β”‚ bob (bob@email.com) β”‚ β”‚ charlie (charlie@email.com) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

βœ… SQL Basics Checkpoint

You now know how to:

  • Retrieve all or specific columns from a table
  • Filter rows with WHERE conditions
  • Combine conditions with AND and OR
  • Sort results with ORDER BY (ascending or descending)
  • Limit results with LIMIT and OFFSET
  • Remove duplicates with DISTINCT
  • Perform calculations and string operations

These form the foundation of 80% of the queries you'll write. Master these patterns, and you're already more capable than most developers.

πŸ” Part 2: Filtering Data Like a Pro

WHERE is where SQL gets interesting. You've seen simple comparisons, but there's a whole world of operators and patterns that let you filter data with surgical precision. Let's explore the complete filtering toolkit.

Example 16: Comparison Operators

The full set of comparison tools:

-- Equal to SELECT * FROM products WHERE price = 99.99; -- Not equal to (two ways) SELECT * FROM products WHERE category != 'Books'; SELECT * FROM products WHERE category <> 'Books'; -- Greater than SELECT * FROM products WHERE stock > 100; -- Greater than or equal to SELECT * FROM products WHERE price >= 50.00; -- Less than SELECT * FROM products WHERE rating < 3.0; -- Less than or equal to SELECT * FROM products WHERE discount <= 0.10;

Example 17: BETWEEN - Range Queries

BETWEEN is inclusive (includes both boundaries):

-- Products priced between $20 and $50 SELECT name, price FROM products WHERE price BETWEEN 20 AND 50;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ USB Cable β”‚ 24.99 β”‚ β”‚ Mouse Pad β”‚ 29.99 β”‚ β”‚ Keyboard β”‚ 49.99 β”‚ β”‚ Webcam β”‚ 39.99 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

This is equivalent to:

WHERE price >= 20 AND price <= 50

Example 18: NOT BETWEEN

Everything outside a range:

-- Products NOT in the $20-50 range SELECT name, price FROM products WHERE price NOT BETWEEN 20 AND 50;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Phone Charger β”‚ 15.99 β”‚ β”‚ Laptop Stand β”‚ 89.99 β”‚ β”‚ Monitor β”‚ 299.99 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 19: IN - Match Multiple Values

Check if a column matches any value in a list:

-- Products in specific categories SELECT name, category FROM products WHERE category IN ('Electronics', 'Computers', 'Gaming');
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ category β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Laptop Stand β”‚ Computers β”‚ β”‚ Gaming Mouse β”‚ Gaming β”‚ β”‚ USB Cable β”‚ Electronics β”‚ β”‚ Monitor β”‚ Computers β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

This beats writing:

WHERE category = 'Electronics' OR category = 'Computers' OR category = 'Gaming'

Example 20: NOT IN

Exclude specific values:

-- Everything except these categories SELECT name, category FROM products WHERE category NOT IN ('Books', 'Clothing', 'Food');

πŸ’‘ IN vs OR: When to Use Which

Think of IN as a bouncer with a VIP list. Instead of checking "Are you John? Are you Sarah? Are you Mike?" (multiple OR conditions), the bouncer just checks "Are you on the list?" (single IN clause). It's cleaner to read and often faster to execute. Use OR when conditions are complex or involve different columns; use IN when checking one column against multiple values.

Example 21: LIKE - Pattern Matching Basics

LIKE uses wildcards for partial matches:

-- % matches any number of characters -- Names starting with 'Game' SELECT name FROM products WHERE name LIKE 'Game%';
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Gaming Mouse β”‚ β”‚ Gamepad Pro β”‚ β”‚ Game Controller β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 22: LIKE with Different Patterns

-- Ends with 'Cable' SELECT name FROM products WHERE name LIKE '%Cable'; -- Contains 'USB' anywhere SELECT name FROM products WHERE name LIKE '%USB%'; -- Starts with any char, then 'ouse' -- _ matches exactly one character SELECT name FROM products WHERE name LIKE '_ouse';
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Mouse β”‚ β”‚ House (if exists)β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 23: Case-Insensitive LIKE (ILIKE)

In PostgreSQL, ILIKE ignores case:

-- Finds 'usb', 'USB', 'Usb', etc. SELECT name FROM products WHERE name ILIKE '%usb%';
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ USB Cable β”‚ β”‚ usb drive β”‚ β”‚ USB-C Adapter β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 24: NOT LIKE

Exclude patterns:

-- Products NOT containing 'Pro' SELECT name FROM products WHERE name NOT LIKE '%Pro%';

Example 25: IS NULL - Finding Missing Data

NULL means "no value" or "unknown." It's specialβ€”you can't use = with it:

-- WRONG: This doesn't work! SELECT * FROM users WHERE email = NULL; -- RIGHT: Use IS NULL SELECT username, email FROM users WHERE email IS NULL;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ email β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ ghost β”‚ NULL β”‚ β”‚ mystery β”‚ NULL β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

Example 26: IS NOT NULL

Find rows with values present:

-- Users who have provided emails SELECT username, email FROM users WHERE email IS NOT NULL;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ email β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ alice@email.com β”‚ β”‚ bob β”‚ bob@email.com β”‚ β”‚ charlie β”‚ charlie@email.com β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚠️ NULL: The Tricky Value

NULL is not zero. It's not an empty string. It's "unknown" or "missing." Any comparison with NULL (except IS NULL) returns... NULL. Even NULL = NULL is NULL (not true!). This trips up beginners constantly. Remember: always use IS NULL or IS NOT NULL when checking for NULL values.

Example 27: Complex AND/OR Combinations

Use parentheses to control logic:

-- Electronics OR Computers, AND price under $100 SELECT name, category, price FROM products WHERE (category = 'Electronics' OR category = 'Computers') AND price < 100;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β” β”‚ name β”‚ category β”‚ price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ USB Cable β”‚ Electronics β”‚ 24.99 β”‚ β”‚ Laptop Stand β”‚ Computers β”‚ 89.99 β”‚ β”‚ Mouse Pad β”‚ Electronics β”‚ 29.99 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜

Example 28: Negating Complex Conditions

NOT can negate entire groups:

-- NOT (cheap Electronics) SELECT name, category, price FROM products WHERE NOT (category = 'Electronics' AND price < 50);

This returns everything except cheap electronics.

Example 29: Date/Time Filtering

Dates work with all comparison operators:

-- Orders from the last 7 days SELECT order_id, order_date FROM orders WHERE order_date >= CURRENT_DATE - INTERVAL '7 days'; -- Orders in 2024 SELECT order_id, order_date FROM orders WHERE order_date BETWEEN '2024-01-01' AND '2024-12-31'; -- Orders from specific month SELECT order_id, order_date FROM orders WHERE EXTRACT(MONTH FROM order_date) = 3;

Example 30: Combining Multiple Filtering Techniques

Real queries often mix many techniques:

-- Complex real-world filter SELECT product_id, name, category, price, stock FROM products WHERE category IN ('Electronics', 'Computers') AND price BETWEEN 50 AND 500 AND stock > 0 AND name NOT LIKE '%Refurbished%' AND discontinued_date IS NULL ORDER BY price DESC LIMIT 10;

This finds: top 10 most expensive in-stock electronics/computers, priced $50-500, not refurbished, not discontinued.

βœ… Filtering Mastery Checkpoint

You can now filter with:

  • All comparison operators (=, !=, >, <, >=, <=)
  • BETWEEN for ranges (inclusive on both ends)
  • IN and NOT IN for matching lists
  • LIKE and ILIKE for pattern matching (%, _ wildcards)
  • IS NULL and IS NOT NULL for missing data
  • Complex AND/OR logic with parentheses
  • Date and time comparisons

These techniques let you slice and dice data with precision. Most business questions translate directly into WHERE clauses using these tools.

πŸ“Š Part 3: Aggregate Functions - Turning Data into Insights

So far, you've retrieved and filtered individual rows. But what if you want to know "How many?" or "What's the average?" or "What's the total?" Aggregate functions transform many rows into single summary values. This is where data becomes information.

πŸ’‘ Aggregates: From Trees to Forest

Individual rows are trees; aggregates show you the forest. Instead of listing every sale, you see total revenue. Instead of every user, you see how many registered each month. Aggregates compress detail into insight. They answer business questions: COUNT tells you volume, SUM tells you total, AVG tells you typical, MIN/MAX tell you extremes.

Example 31: COUNT - How Many Rows

COUNT is the simplest aggregate:

-- How many users? SELECT COUNT(*) FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β” β”‚ count β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 150 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”˜

COUNT(*) counts all rows. Use COUNT(column) to count non-NULL values:

-- How many users have emails? SELECT COUNT(email) AS users_with_email FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ users_with_email β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 142 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 32: COUNT DISTINCT

Count unique values only:

-- How many different countries? SELECT COUNT(DISTINCT country) AS country_count FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ country_count β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 23 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 33: SUM - Add It Up

SUM totals numeric columns:

-- Total revenue from all orders SELECT SUM(amount) AS total_revenue FROM orders;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ total_revenue β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1,247,832.50 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 34: SUM with WHERE

Aggregate only filtered rows:

-- Revenue from completed orders only SELECT SUM(amount) AS completed_revenue FROM orders WHERE status = 'completed';
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ completed_revenue β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1,089,450.75 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 35: AVG - Average Value

AVG calculates mean (sum divided by count):

-- Average order amount SELECT AVG(amount) AS avg_order_value FROM orders;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ avg_order_value β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 127.45 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 36: MIN and MAX - Extremes

Find smallest and largest values:

-- Price range of products SELECT MIN(price) AS cheapest, MAX(price) AS most_expensive, MAX(price) - MIN(price) AS price_range FROM products;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ cheapest β”‚ most_expensive β”‚ price_range β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 5.99 β”‚ 2,499.99 β”‚ 2,494.00 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 37: Multiple Aggregates Together

Combine multiple aggregates in one query:

-- Complete user statistics SELECT COUNT(*) AS total_users, COUNT(email) AS users_with_email, COUNT(DISTINCT country) AS countries, AVG(age) AS average_age, MIN(age) AS youngest, MAX(age) AS oldest FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ total_users β”‚ users_with_email β”‚ countries β”‚ average_age β”‚ youngest β”‚ oldest β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 150 β”‚ 142 β”‚ 23 β”‚ 31.7 β”‚ 18 β”‚ 67 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

🎯 Aggregate Function Quick Reference

  • COUNT(*) - Count all rows
  • COUNT(column) - Count non-NULL values
  • COUNT(DISTINCT column) - Count unique values
  • SUM(column) - Add up values
  • AVG(column) - Calculate mean
  • MIN(column) - Find smallest value
  • MAX(column) - Find largest value

Example 38: GROUP BY - Category Breakdowns

This is where aggregates get powerful. GROUP BY splits data into groups, then aggregates each group separately:

-- Count users per country SELECT country, COUNT(*) AS user_count FROM users GROUP BY country;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ country β”‚ user_count β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ USA β”‚ 87 β”‚ β”‚ Canada β”‚ 34 β”‚ β”‚ UK β”‚ 19 β”‚ β”‚ Germany β”‚ 10 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Think of GROUP BY as creating buckets. Each unique country is a bucket, then COUNT counts items in each bucket.

Example 39: GROUP BY with Multiple Aggregates

-- Revenue statistics per product category SELECT category, COUNT(*) AS num_products, SUM(price * stock) AS inventory_value, AVG(price) AS avg_price, MIN(price) AS cheapest, MAX(price) AS most_expensive FROM products GROUP BY category ORDER BY inventory_value DESC;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ category β”‚ num_products β”‚ inventory_value β”‚ avg_price β”‚ cheapest β”‚ most_expensive β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Electronics β”‚ 145 β”‚ 487,234.50 β”‚ 156.89 β”‚ 9.99 β”‚ 2,499.99 β”‚ β”‚ Computers β”‚ 87 β”‚ 312,890.00 β”‚ 423.45 β”‚ 49.99 β”‚ 1,999.99 β”‚ β”‚ Gaming β”‚ 62 β”‚ 198,432.75 β”‚ 89.99 β”‚ 19.99 β”‚ 599.99 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 40: GROUP BY Multiple Columns

Group by combinations of values:

-- Orders per day per status SELECT DATE(order_date) AS order_day, status, COUNT(*) AS num_orders, SUM(amount) AS daily_revenue FROM orders GROUP BY DATE(order_date), status ORDER BY order_day DESC, status;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ order_day β”‚ status β”‚ num_orders β”‚ daily_revenue β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 2026-01-04 β”‚ completed β”‚ 23 β”‚ 3,456.78 β”‚ β”‚ 2026-01-04 β”‚ pending β”‚ 8 β”‚ 987.50 β”‚ β”‚ 2026-01-03 β”‚ completed β”‚ 31 β”‚ 4,123.90 β”‚ β”‚ 2026-01-03 β”‚ pending β”‚ 5 β”‚ 654.20 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 41: HAVING - Filtering Groups

WHERE filters rows before grouping. HAVING filters groups after aggregation:

-- Countries with more than 10 users SELECT country, COUNT(*) AS user_count FROM users GROUP BY country HAVING COUNT(*) > 10 ORDER BY user_count DESC;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ country β”‚ user_count β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ USA β”‚ 87 β”‚ β”‚ Canada β”‚ 34 β”‚ β”‚ UK β”‚ 19 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Germany (with 10 users) doesn't appear because HAVING requires > 10.

πŸ’‘ WHERE vs HAVING: The Difference

WHERE is a bouncer at the doorβ€”it decides which rows get in before any grouping happens. HAVING is a judge at the endβ€”it looks at the grouped results and decides which groups make the cut. Use WHERE for row-level filtering ("show me orders over $100"), use HAVING for group-level filtering ("show me customers with more than 5 orders").

Example 42: HAVING with Multiple Conditions

-- Categories with 20+ products AND avg price over $50 SELECT category, COUNT(*) AS num_products, AVG(price) AS avg_price FROM products GROUP BY category HAVING COUNT(*) >= 20 AND AVG(price) > 50 ORDER BY avg_price DESC;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ category β”‚ num_products β”‚ avg_price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Computers β”‚ 87 β”‚ 423.45 β”‚ β”‚ Electronics β”‚ 145 β”‚ 156.89 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 43: WHERE and HAVING Together

Filter rows first, then filter groups:

-- Categories with 10+ in-stock products, avg price > $100 SELECT category, COUNT(*) AS in_stock_count, AVG(price) AS avg_price FROM products WHERE stock > 0 -- Filter rows first GROUP BY category HAVING COUNT(*) >= 10 -- Filter groups after AND AVG(price) > 100 ORDER BY avg_price DESC;

Execution order: WHERE filters products to only in-stock β†’ GROUP BY creates category groups β†’ HAVING filters those groups.

Example 44: Percentage Calculations

Combine aggregates for insights:

-- What % of users have provided emails? SELECT COUNT(*) AS total_users, COUNT(email) AS users_with_email, ROUND(100.0 * COUNT(email) / COUNT(*), 2) AS email_percentage FROM users;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ total_users β”‚ users_with_email β”‚ email_percentage β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 150 β”‚ 142 β”‚ 94.67 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 45: Advanced Grouping Example

Real-world business question answered with SQL:

-- Monthly revenue by product category (2024) SELECT category, DATE_TRUNC('month', order_date) AS month, COUNT(DISTINCT order_id) AS num_orders, SUM(quantity * unit_price) AS revenue, AVG(quantity * unit_price) AS avg_order_value FROM orders o JOIN order_items oi ON o.order_id = oi.order_id JOIN products p ON oi.product_id = p.product_id WHERE EXTRACT(YEAR FROM order_date) = 2024 GROUP BY category, DATE_TRUNC('month', order_date) HAVING SUM(quantity * unit_price) > 10000 ORDER BY month DESC, revenue DESC;

This shows monthly category performance, but only for categories generating over $10k/month.

βœ… Aggregation Mastery Checkpoint

You now know how to:

  • Use COUNT, SUM, AVG, MIN, MAX to summarize data
  • Combine multiple aggregates in one query
  • Use GROUP BY to create category breakdowns
  • Group by multiple columns for detailed analysis
  • Filter groups with HAVING (vs filtering rows with WHERE)
  • Calculate percentages and derived metrics
  • Build complex analytical queries

Aggregates transform raw data into business intelligence. Master these, and you can answer almost any "how many" or "how much" question your organization asks.

πŸ”— Part 4: JOINS - Connecting the Dots

Real databases aren't one giant tableβ€”they're dozens or hundreds of tables connected by relationships. JOINS are how you stitch them back together to answer questions. This is where SQL becomes truly powerful, and where many developers struggle. Let's make it crystal clear.

πŸ’‘ JOINS: Assembling the Puzzle

Imagine each table as a separate stack of index cards. Customers on one stack, orders on another, products on a third. JOINS are how you lay them side-by-side and match them up. "Show me customers and their orders" means taking customer cards and matching order cards to them. Some customers might have no orders (LEFT JOIN includes them anyway), some orders might link to deleted customers (NULL appears). Understanding JOINS is understanding how data connects.

Example 46: The Setup - Understanding Table Relationships

Let's use three simple tables:

-- USERS table β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ id β”‚ username β”‚ email β”‚ β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ alice β”‚ alice@test.com β”‚ β”‚ 2 β”‚ bob β”‚ bob@test.com β”‚ β”‚ 3 β”‚ charlie β”‚ charlie@test.c β”‚ β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ -- ORDERS table β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ id β”‚ user_id β”‚ amount β”‚ status β”‚ β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1 β”‚ 1 β”‚ 99.99 β”‚ paid β”‚ β”‚ 2 β”‚ 1 β”‚ 149.50 β”‚ paid β”‚ β”‚ 3 β”‚ 2 β”‚ 75.00 β”‚ paid β”‚ β”‚ 4 β”‚ 4 β”‚ 200.00 β”‚ paid β”‚ ← user_id 4 doesn't exist! β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Notice: alice has 2 orders, bob has 1, charlie has 0, and there's an orphan order (user_id 4).

Example 47: INNER JOIN - The Most Common Join

INNER JOIN returns only rows where there's a match in BOTH tables:

-- Show users and their orders SELECT u.username, o.id AS order_id, o.amount, o.status FROM users u INNER JOIN orders o ON u.id = o.user_id;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ order_id β”‚ amount β”‚ status β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 1 β”‚ 99.99 β”‚ paid β”‚ β”‚ alice β”‚ 2 β”‚ 149.50 β”‚ paid β”‚ β”‚ bob β”‚ 3 β”‚ 75.00 β”‚ paid β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Missing: charlie (no orders), and the orphan order (no user). INNER JOIN = intersection only.

INNER JOIN (Intersection) Users Orders β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚ β”‚ β”‚ β”Œβ”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β” β”‚ β”‚ β”‚ Matched β”‚ β”‚ └─── Rows Only β”œβ”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 48: LEFT JOIN - Keep All Left Rows

LEFT JOIN returns all rows from the left table, with NULLs where there's no match:

-- Show all users, including those without orders SELECT u.username, o.id AS order_id, o.amount FROM users u LEFT JOIN orders o ON u.id = o.user_id;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ order_id β”‚ amount β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 1 β”‚ 99.99 β”‚ β”‚ alice β”‚ 2 β”‚ 149.50 β”‚ β”‚ bob β”‚ 3 β”‚ 75.00 β”‚ β”‚ charlie β”‚ NULL β”‚ NULL β”‚ ← No orders, but still included β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Charlie appears even with no orders. The orphan order (user_id 4) still doesn't showβ€”it has no matching user.

LEFT JOIN (All Left + Matches) Users Orders β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ”‚ β”‚ β”‚ β”‚β–ˆβ”Œβ”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β” β”‚ β”‚β–ˆβ”‚ Matched β”‚ β”‚ └── Rows β”œβ”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ^ All users shown

Example 49: RIGHT JOIN - Keep All Right Rows

RIGHT JOIN is the oppositeβ€”all right table rows, NULLs for non-matches:

-- Show all orders, including orphans SELECT u.username, o.id AS order_id, o.amount FROM users u RIGHT JOIN orders o ON u.id = o.user_id;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ order_id β”‚ amount β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 1 β”‚ 99.99 β”‚ β”‚ alice β”‚ 2 β”‚ 149.50 β”‚ β”‚ bob β”‚ 3 β”‚ 75.00 β”‚ β”‚ NULL β”‚ 4 β”‚ 200.00 β”‚ ← Orphan order included β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Now the orphan order appears (with NULL username). Charlie doesn't showβ€”he has no orders.

RIGHT JOIN (Matches + All Right) Users Orders β”Œβ”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β” β”‚ β”‚ β”‚β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ”‚ β”‚ β”Œβ”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”β–ˆβ”‚ β”‚ β”‚ Matched β”‚β–ˆβ”‚ └─── Rows β”œβ”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ All orders shown ^

Example 50: Finding Unmatched Rows with LEFT JOIN

A common pattern: find rows with no match:

-- Find users who have never ordered SELECT u.id, u.username, u.email FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.id IS NULL;
β”Œβ”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ id β”‚ username β”‚ email β”‚ β”œβ”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 3 β”‚ charlie β”‚ charlie@test.c β”‚ β””β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

LEFT JOIN gives us all users, WHERE o.id IS NULL filters to only those where the join found nothing.

Example 51: Multiple JOINS

Join more than two tables together:

-- Three tables: users, orders, order_items SELECT u.username, o.id AS order_id, oi.product_name, oi.quantity, oi.price FROM users u INNER JOIN orders o ON u.id = o.user_id INNER JOIN order_items oi ON o.id = oi.order_id WHERE u.username = 'alice';
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ order_id β”‚ product_name β”‚ quantity β”‚ price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 1 β”‚ Keyboard β”‚ 1 β”‚ 79.99 β”‚ β”‚ alice β”‚ 1 β”‚ Mouse β”‚ 2 β”‚ 19.99 β”‚ β”‚ alice β”‚ 2 β”‚ Monitor β”‚ 1 β”‚ 149.50 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Each JOIN adds another table to the chain. Order mattersβ€”join users to orders first, then orders to items.

Example 52: JOIN with Aggregate Functions

Combine JOINS and GROUP BY for powerful analytics:

-- Total spending per user SELECT u.username, u.email, COUNT(o.id) AS num_orders, SUM(o.amount) AS total_spent, AVG(o.amount) AS avg_order FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.username, u.email ORDER BY total_spent DESC NULLS LAST;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ email β”‚ num_orders β”‚ total_spent β”‚ avg_order β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ alice@test.com β”‚ 2 β”‚ 249.49 β”‚ 124.75 β”‚ β”‚ bob β”‚ bob@test.com β”‚ 1 β”‚ 75.00 β”‚ 75.00 β”‚ β”‚ charlie β”‚ charlie@test.c β”‚ 0 β”‚ NULL β”‚ NULL β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

LEFT JOIN ensures charlie appears. GROUP BY aggregates each user's orders.

Example 53: Self JOIN - Joining a Table to Itself

Sometimes you need to compare rows within the same table:

-- Find users from the same city SELECT u1.username AS user1, u2.username AS user2, u1.city FROM users u1 INNER JOIN users u2 ON u1.city = u2.city WHERE u1.id < u2.id -- Avoid duplicates and self-matches ORDER BY u1.city, u1.username;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ user1 β”‚ user2 β”‚ city β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ diana β”‚ New York β”‚ β”‚ bob β”‚ charlie β”‚ Seattle β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

The table is joined to itself (aliased as u1 and u2) to find pairs in the same city.

Example 54: CROSS JOIN - Every Combination

CROSS JOIN produces cartesian product (every row with every other row):

-- Not used often, but occasionally useful SELECT u.username, p.product_name FROM users u CROSS JOIN products p LIMIT 6;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ product_name β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ Keyboard β”‚ β”‚ alice β”‚ Mouse β”‚ β”‚ alice β”‚ Monitor β”‚ β”‚ bob β”‚ Keyboard β”‚ β”‚ bob β”‚ Mouse β”‚ β”‚ bob β”‚ Monitor β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Every user paired with every product. With 3 users and 100 products, you get 300 rows!

Example 55: JOIN with Subqueries

You can join to query results:

-- Join to a filtered dataset SELECT u.username, recent.order_count FROM users u INNER JOIN ( SELECT user_id, COUNT(*) AS order_count FROM orders WHERE order_date > CURRENT_DATE - INTERVAL '30 days' GROUP BY user_id ) recent ON u.id = recent.user_id;

The subquery (in parentheses) creates a virtual table of recent order counts, which we join to users.

Example 56: Complex Real-World JOIN Example

Bringing it all together:

-- Customer lifetime value with product details SELECT u.id AS customer_id, u.username, u.email, COUNT(DISTINCT o.id) AS total_orders, SUM(oi.quantity * oi.unit_price) AS lifetime_value, AVG(oi.quantity * oi.unit_price) AS avg_item_value, STRING_AGG(DISTINCT p.category, ', ') AS categories_purchased FROM users u LEFT JOIN orders o ON u.id = o.user_id AND o.status = 'completed' LEFT JOIN order_items oi ON o.id = oi.order_id LEFT JOIN products p ON oi.product_id = p.product_id GROUP BY u.id, u.username, u.email HAVING SUM(oi.quantity * oi.unit_price) > 1000 ORDER BY lifetime_value DESC;

This shows high-value customers (over $1000 lifetime spend) with their order counts and categories purchased.

Example 57: JOIN Performance - Using Indexes

JOINS are fast when columns have indexes:

-- Create indexes on foreign keys (typically done once) CREATE INDEX idx_orders_user_id ON orders(user_id); CREATE INDEX idx_order_items_order_id ON order_items(order_id); CREATE INDEX idx_order_items_product_id ON order_items(product_id); -- Now this JOIN will be lightning fast even with millions of rows SELECT u.username, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.username;

Without indexes, databases scan entire tables. With indexes, they jump directly to matching rowsβ€”difference between seconds and milliseconds.

Example 58: USING Shorthand

When join columns have the same name, USING is cleaner:

-- These are equivalent: SELECT * FROM users u INNER JOIN orders o ON u.id = o.user_id; -- vs shorter USING syntax (if column is named 'id' in both): SELECT * FROM users u INNER JOIN orders o USING (user_id);

Example 59: Natural Join (Use Sparingly)

NATURAL JOIN automatically joins on all columns with matching names:

-- Joins on any columns with same name (risky!) SELECT * FROM users NATURAL JOIN orders;

Avoid thisβ€”it's implicit and can break if schema changes. Explicit JOINs are clearer.

Example 60: LEFT JOIN vs NOT EXISTS

Two ways to find rows without matches:

-- Method 1: LEFT JOIN with WHERE NULL SELECT u.username FROM users u LEFT JOIN orders o ON u.id = o.user_id WHERE o.id IS NULL; -- Method 2: NOT EXISTS subquery SELECT u.username FROM users u WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id );

Both find users without orders. NOT EXISTS is often faster on large datasets.

βœ… JOIN Mastery Checkpoint

You now understand:

  • INNER JOIN - Only matched rows from both tables
  • LEFT JOIN - All left table rows + matches (NULLs for non-matches)
  • RIGHT JOIN - All right table rows + matches
  • Finding unmatched rows with LEFT JOIN ... WHERE ... IS NULL
  • Chaining multiple JOINs together
  • Combining JOINs with GROUP BY and aggregates
  • Self-joins and cross joins
  • Performance considerations (indexes)
  • Alternative patterns (NOT EXISTS, subqueries)

JOINS unlock relational database power. Most complex queries are really just clever combinations of JOINs and aggregates. Master these patterns, and you can answer any question your data can answer.

🎯 SQL So Far: The Four Pillars

You've conquered the fundamentals:

  • SELECT/WHERE/ORDER BY/LIMIT - Retrieve and filter individual rows
  • Advanced Filtering - BETWEEN, IN, LIKE, NULL checks, complex logic
  • Aggregates & GROUP BY - Transform rows into insights, answer "how many" questions
  • JOINS - Connect related tables, reconstruct relationships

These four skills form the foundation of 90% of SQL work. Everything else builds on these patterns. You're now dangerous with a databaseβ€”next, we'll explore even more advanced techniques...

πŸ” Part 5: Subqueries - Queries Within Queries

Subqueries let you nest one query inside another, enabling multi-step logic in a single statement. They're like function calls in programmingβ€”you compute something, then use that result in the outer query. Subqueries can return single values (scalar), single rows, or entire result sets. Master these, and you can express incredibly complex logic elegantly.

πŸ’‘ Subqueries: Nested Thinking

Imagine asking "Who are the customers who spent more than the average?" You can't answer this in one stepβ€”first you need to calculate the average (step 1), then compare each customer to that average (step 2). Subqueries let you do both in one query. The inner query runs first and produces a result, which the outer query then uses. It's like solving a math problem: solve the parentheses first, then use that answer in the main equation.

Example 61: Scalar Subquery - Returns Single Value

The most common subquery type returns one value:

-- Find products more expensive than average SELECT product_name, price FROM products WHERE price > (SELECT AVG(price) FROM products) ORDER BY price DESC;

The subquery (SELECT AVG(price) FROM products) runs first, returning something like 49.99. Then the outer query uses that number.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ product_name β”‚ price β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Laptop β”‚ 1299.99β”‚ β”‚ Monitor β”‚ 399.99 β”‚ β”‚ Keyboard β”‚ 89.99 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 62: Subquery in SELECT - Correlated Subquery

Subqueries can appear in the SELECT clause, running once per row:

-- Show each user's order count inline SELECT u.username, u.email, (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count, (SELECT MAX(order_date) FROM orders o WHERE o.user_id = u.id) AS last_order_date FROM users u ORDER BY order_count DESC;

For each user, the subqueries run, counting their orders and finding their most recent order. This is called a correlated subqueryβ€”it references the outer query (u.id).

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ email β”‚ order_count β”‚ last_order_date β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ alice@email.com β”‚ 23 β”‚ 2025-12-30 β”‚ β”‚ bob β”‚ bob@email.com β”‚ 15 β”‚ 2025-11-22 β”‚ β”‚ charlie β”‚ charlie@mail.com β”‚ 0 β”‚ NULL β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⚠️ Performance Warning: Correlated Subqueries

Correlated subqueries (those referencing outer query) run once PER ROW. With 10,000 users, that's 10,000 subquery executions. This example would be faster rewritten with LEFT JOINs and GROUP BY. Use correlated subqueries when data is small or for readability, but watch performance on large tables.

Example 63: Subquery in FROM - Inline View

Subqueries can act as temporary tables:

-- Calculate stats per category, then filter SELECT category, product_count, avg_price FROM ( SELECT category, COUNT(*) AS product_count, AVG(price) AS avg_price FROM products GROUP BY category ) AS category_stats WHERE product_count > 5 ORDER BY avg_price DESC;

The subquery creates a virtual table called category_stats, which we then query. This is cleaner than trying to do everything in one level.

Example 64: Subquery with IN - Row Subquery

Find rows matching values from another query:

-- Users who placed orders in the last 30 days SELECT username, email FROM users WHERE id IN ( SELECT DISTINCT user_id FROM orders WHERE order_date > CURRENT_DATE - INTERVAL '30 days' );

The subquery returns a list of user IDs, and IN checks if each user's ID is in that list.

Example 65: NOT IN - Exclusion Pattern

Find rows NOT in a set:

-- Products never ordered SELECT product_name, price FROM products WHERE id NOT IN ( SELECT DISTINCT product_id FROM order_items );

This finds products with no sales. Be careful: if the subquery contains NULL, NOT IN can return unexpected results (use NOT EXISTS instead for NULL-safe logic).

Example 66: EXISTS - Check for Existence

EXISTS returns true if subquery returns any rows:

-- Find users with at least one completed order SELECT username, email FROM users u WHERE EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.status = 'completed' );

EXISTS stops searching as soon as it finds one matchβ€”efficient for "at least one" checks.

Example 67: NOT EXISTS - Absence Pattern

The oppositeβ€”find rows where something doesn't exist:

-- Users who never completed an order SELECT username, email FROM users u WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id AND o.status = 'completed' );

NOT EXISTS is often faster than NOT IN and handles NULLs correctly.

Example 68: Subquery with ALL/ANY

Compare against all or any values from a subquery:

-- Products more expensive than ALL electronics SELECT product_name, price, category FROM products WHERE price > ALL ( SELECT price FROM products WHERE category = 'Electronics' ); -- Products more expensive than ANY electronics SELECT product_name, price, category FROM products WHERE price > ANY ( SELECT price FROM products WHERE category = 'Electronics' );

ALL = greater than the maximum. ANY = greater than the minimum. Rarely used but powerful for set comparisons.

Example 69: Complex Nested Subqueries

You can nest subqueries multiple levels deep:

-- Users in cities with above-average user count SELECT username, city FROM users WHERE city IN ( SELECT city FROM ( SELECT city, COUNT(*) AS user_count FROM users GROUP BY city ) AS city_stats WHERE user_count > ( SELECT AVG(user_count) FROM ( SELECT COUNT(*) AS user_count FROM users GROUP BY city ) AS city_counts ) );

This is getting complexβ€”sometimes breaking into CTEs (Common Table Expressions, covered next) is clearer.

Example 70: Common Table Expressions (CTE) - WITH Clause

CTEs make complex queries readable by naming subqueries:

-- Same query as above, but readable WITH city_user_counts AS ( SELECT city, COUNT(*) AS user_count FROM users GROUP BY city ), average_count AS ( SELECT AVG(user_count) AS avg_users FROM city_user_counts ) SELECT username, city FROM users WHERE city IN ( SELECT city FROM city_user_counts WHERE user_count > (SELECT avg_users FROM average_count) );

CTEs are like temporary named tables that exist for the duration of one query. Far more readable than nested subqueries.

🎨 Part 6: Advanced SQL - Power Techniques

Now we enter advanced territoryβ€”set operations, conditional logic, and window functions that enable SQL wizardry. These techniques separate SQL novices from experts.

Example 71: UNION - Combine Result Sets

UNION merges results from multiple queries, removing duplicates:

-- All email addresses from users and newsletter subscribers SELECT email FROM users UNION SELECT email FROM newsletter_subscribers; -- If you want duplicates kept, use UNION ALL (faster) SELECT email FROM users UNION ALL SELECT email FROM newsletter_subscribers;

Requirements: same number of columns, compatible types. UNION removes duplicates (slower), UNION ALL keeps all rows (faster).

Example 72: INTERSECT & EXCEPT

Set operations for overlaps and differences:

-- Emails in BOTH tables (intersection) SELECT email FROM users INTERSECT SELECT email FROM newsletter_subscribers; -- Emails in users but NOT in newsletter (difference) SELECT email FROM users EXCEPT SELECT email FROM newsletter_subscribers;

INTERSECT finds common rows. EXCEPT finds rows in first query but not second. Useful for data comparisons.

Example 73: CASE - Conditional Logic

CASE is SQL's if/elseβ€”compute values conditionally:

-- Categorize products by price SELECT product_name, price, CASE WHEN price < 50 THEN 'Budget' WHEN price < 200 THEN 'Mid-Range' WHEN price < 1000 THEN 'Premium' ELSE 'Luxury' END AS price_category FROM products;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ product_name β”‚ price β”‚ price_category β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Mouse β”‚ 29.99 β”‚ Budget β”‚ β”‚ Keyboard β”‚ 89.99 β”‚ Mid-Range β”‚ β”‚ Monitor β”‚ 399.99 β”‚ Premium β”‚ β”‚ Laptop β”‚ 1299.99β”‚ Luxury β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Example 74: CASE in Aggregates - Conditional Counting

Combine CASE with aggregates for powerful analytics:

-- Count orders by status in one query SELECT user_id, COUNT(*) AS total_orders, COUNT(CASE WHEN status = 'completed' THEN 1 END) AS completed, COUNT(CASE WHEN status = 'pending' THEN 1 END) AS pending, COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled FROM orders GROUP BY user_id;

This pivots dataβ€”instead of multiple queries, we count different conditions in one pass.

Example 75: COALESCE - Handle NULLs Gracefully

COALESCE returns the first non-NULL value:

-- Show user's preferred name, fallback to username SELECT COALESCE(preferred_name, username, 'Guest') AS display_name, email FROM users;

Checks preferred_name first, if NULL tries username, if still NULL uses 'Guest'. Essential for clean data presentation.

Example 76: NULLIF - Create NULLs Conditionally

NULLIF returns NULL if two values are equal:

-- Avoid division by zero SELECT product_name, total_revenue, total_units_sold, total_revenue / NULLIF(total_units_sold, 0) AS revenue_per_unit FROM product_stats;

If total_units_sold is 0, NULLIF returns NULL, avoiding divide-by-zero error (NULL / anything = NULL).

Example 77: Window Functions - ROW_NUMBER()

Window functions perform calculations across rows without collapsing them (like GROUP BY does):

-- Rank products by price within each category SELECT product_name, category, price, ROW_NUMBER() OVER (PARTITION BY category ORDER BY price DESC) AS price_rank FROM products;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ product_name β”‚ category β”‚ price β”‚ price_rank β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Laptop β”‚ Electronics β”‚ 1299.99β”‚ 1 β”‚ β”‚ Monitor β”‚ Electronics β”‚ 399.99 β”‚ 2 β”‚ β”‚ Mouse β”‚ Electronics β”‚ 29.99 β”‚ 3 β”‚ β”‚ Office Chair β”‚ Furniture β”‚ 499.99 β”‚ 1 β”‚ β”‚ Desk β”‚ Furniture β”‚ 299.99 β”‚ 2 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

PARTITION BY creates groups, ORDER BY defines ranking within each group. Each row keeps its identityβ€”no collapsing.

Example 78: Window Functions - RANK() and DENSE_RANK()

Handle ties differently:

SELECT username, score, ROW_NUMBER() OVER (ORDER BY score DESC) AS row_num, RANK() OVER (ORDER BY score DESC) AS rank, DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank FROM game_scores;
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ username β”‚ score β”‚ row_num β”‚ rank β”‚ dense_rank β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ alice β”‚ 1000 β”‚ 1 β”‚ 1 β”‚ 1 β”‚ β”‚ bob β”‚ 1000 β”‚ 2 β”‚ 1 β”‚ 1 β”‚ β”‚ charlie β”‚ 950 β”‚ 3 β”‚ 3 β”‚ 2 β”‚ β”‚ diana β”‚ 900 β”‚ 4 β”‚ 4 β”‚ 3 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

ROW_NUMBER: always unique. RANK: ties get same rank, next rank skips. DENSE_RANK: no gaps after ties.

Example 79: Window Functions - Aggregates

Run aggregates without GROUP BY:

-- Show each order with running total SELECT order_id, order_date, amount, SUM(amount) OVER (ORDER BY order_date) AS running_total, AVG(amount) OVER (ORDER BY order_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS moving_avg_3 FROM orders ORDER BY order_date;

running_total accumulates as you go down. moving_avg_3 calculates average of current row + 2 previous rows. Powerful for time-series analysis.

Example 80: Window Functions - LAG and LEAD

Access previous or next row values:

-- Compare each month's revenue to previous month SELECT month, revenue, LAG(revenue) OVER (ORDER BY month) AS prev_month_revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS revenue_change, LEAD(revenue) OVER (ORDER BY month) AS next_month_revenue FROM monthly_revenue;

LAG looks backward, LEAD looks forward. Essential for calculating changes, growth rates, deltas.

πŸ“ Part 7: Data Manipulation - INSERT, UPDATE, DELETE

So far we've queried dataβ€”now let's modify it. These are the CRUD operations (Create, Read, Update, Delete) that power applications.

Example 81: INSERT - Adding Rows

Insert single row:

-- Basic insert INSERT INTO users (username, email, created_at) VALUES ('alice', 'alice@email.com', CURRENT_TIMESTAMP); -- Insert multiple rows at once (faster) INSERT INTO users (username, email, created_at) VALUES ('bob', 'bob@email.com', CURRENT_TIMESTAMP), ('charlie', 'charlie@email.com', CURRENT_TIMESTAMP), ('diana', 'diana@email.com', CURRENT_TIMESTAMP);

Always specify column namesβ€”table structure may change. Inserting multiple rows in one statement is much faster than separate INSERTs.

Example 82: INSERT with SELECT - Copy Data

Insert query results into a table:

-- Copy high-value customers to VIP table INSERT INTO vip_customers (user_id, username, total_spent) SELECT u.id, u.username, SUM(o.amount) AS total_spent FROM users u INNER JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.username HAVING SUM(o.amount) > 10000;

No VALUES clauseβ€”results from SELECT go directly into table.

Example 83: INSERT RETURNING - Get Inserted IDs

PostgreSQL and some databases support RETURNING:

-- Insert and immediately get the generated ID INSERT INTO orders (user_id, amount, status) VALUES (42, 299.99, 'pending') RETURNING id, created_at;

Returns the auto-generated ID and timestamp without a separate SELECT. Useful in applications.

Example 84: UPDATE - Modify Existing Rows

Update with WHERE clause:

-- Update one user's email UPDATE users SET email = 'newemail@example.com', updated_at = CURRENT_TIMESTAMP WHERE username = 'alice'; -- Give 10% discount to premium members UPDATE products SET price = price * 0.90 WHERE category = 'Electronics' AND in_stock = TRUE;

🚨 Critical Warning: UPDATE Without WHERE

UPDATE without WHERE modifies EVERY row in the table. UPDATE users SET password = 'reset' would reset EVERYONE's password. Always include WHERE unless you truly mean to update all rows. Test with SELECT first: SELECT * FROM users WHERE username = 'alice' to confirm you're targeting the right rows.

Example 85: UPDATE with JOIN

Update based on data from another table:

-- Mark users as VIP if they spent over $10k UPDATE users u SET account_type = 'VIP' FROM ( SELECT user_id, SUM(amount) AS total FROM orders GROUP BY user_id HAVING SUM(amount) > 10000 ) AS high_spenders WHERE u.id = high_spenders.user_id;

Syntax varies by database (MySQL uses JOIN directly, PostgreSQL uses FROM).

Example 86: UPDATE RETURNING

See what was updated:

UPDATE products SET in_stock = FALSE WHERE quantity = 0 RETURNING product_name, category;

Returns names and categories of out-of-stock products that were just marked unavailable.

Example 87: DELETE - Remove Rows

Delete with WHERE clause:

-- Delete one specific user DELETE FROM users WHERE id = 42; -- Delete old logs (common cleanup pattern) DELETE FROM access_logs WHERE log_date < CURRENT_DATE - INTERVAL '90 days';

🚨 Critical Warning: DELETE Without WHERE

DELETE without WHERE removes EVERY row. DELETE FROM users empties the entire table (data gone forever unless backed up). ALWAYS use WHERE. Test with SELECT first. Enable transactions (covered next) so you can ROLLBACK mistakes.

Example 88: DELETE with JOIN

Delete based on related data:

-- Delete users who never placed an order DELETE FROM users WHERE id NOT IN (SELECT DISTINCT user_id FROM orders); -- Or using NOT EXISTS (often faster) DELETE FROM users u WHERE NOT EXISTS ( SELECT 1 FROM orders o WHERE o.user_id = u.id );

Example 89: TRUNCATE - Fast Table Clear

Remove all rows quickly:

-- Much faster than DELETE for clearing entire table TRUNCATE TABLE access_logs;

TRUNCATE is faster than DELETE (doesn't log individual row deletions) but can't use WHERE. Use for clearing entire tables only.

Example 90: ON CONFLICT / UPSERT - Insert or Update

PostgreSQL's powerful upsert syntax:

-- Insert, but if email already exists, update instead INSERT INTO users (username, email, login_count) VALUES ('alice', 'alice@email.com', 1) ON CONFLICT (email) DO UPDATE SET login_count = users.login_count + 1, last_login = CURRENT_TIMESTAMP;

If email constraint violated (user exists), update their login count instead of failing. MySQL uses ON DUPLICATE KEY UPDATE.

⚑ Part 8: Indexes & Performance - Making Queries Fast

The difference between a query that takes 0.01 seconds and one that takes 10 seconds is usually indexes. Understanding how databases find data is crucial for building fast applications.

πŸ’‘ Indexes: The Book Analogy

Imagine finding a topic in a 1000-page book. Without an index, you'd read page-by-page (slow). With an index at the back, you jump directly to page 347 (fast). Database indexes work the same way. A table scan reads every row (like reading every page). An index scan jumps directly to matching rows. Creating an index means building that "back-of-the-book index" structureβ€”takes storage space but makes lookups lightning fast.

Example 91: Creating Indexes

Index frequently queried columns:

-- Index on single column CREATE INDEX idx_users_email ON users(email); -- Composite index (multiple columns) CREATE INDEX idx_orders_user_date ON orders(user_id, order_date); -- Unique index (enforces uniqueness) CREATE UNIQUE INDEX idx_users_username ON users(username);

Indexes speed up WHERE clauses, JOINs, and ORDER BY. But they slow down writes (INSERT/UPDATE/DELETE must update indexes too).

Example 92: When to Use Indexes

Index these scenarios:

-- Foreign keys (used in JOINs) CREATE INDEX idx_orders_user_id ON orders(user_id); -- WHERE clause columns (frequent filters) CREATE INDEX idx_users_created_at ON users(created_at); -- ORDER BY columns (sorting) CREATE INDEX idx_products_price ON products(price); -- UNIQUE constraints (usernames, emails) CREATE UNIQUE INDEX idx_users_email ON users(email);

βœ… Index Best Practices

  • Index foreign keys - JOIN performance depends on this
  • Index WHERE clause columns - If you filter by it often, index it
  • Composite indexes - Order matters! (user_id, order_date) helps WHERE user_id = X AND order_date > Y but not WHERE order_date > Y alone
  • Don't over-index - Every index slows writes and uses disk space
  • Monitor query plans - Use EXPLAIN to see if indexes are used

Example 93: EXPLAIN - See Query Execution Plan

EXPLAIN shows how database will execute a query:

-- Without EXPLAIN (actually runs query) SELECT * FROM orders WHERE user_id = 42; -- With EXPLAIN (shows plan, doesn't run) EXPLAIN SELECT * FROM orders WHERE user_id = 42;

Output shows "Seq Scan" (bad, table scan) or "Index Scan" (good, using index). Use this to diagnose slow queries.

Example 94: EXPLAIN ANALYZE - Actual Execution Stats

See real execution times:

EXPLAIN ANALYZE SELECT u.username, COUNT(o.id) AS order_count FROM users u LEFT JOIN orders o ON u.id = o.user_id GROUP BY u.id, u.username ORDER BY order_count DESC LIMIT 10;

Shows estimated vs actual rows, execution time for each step, and where bottlenecks are. Essential for optimization.

Example 95: Query Optimization Patterns

Common slow query fixes:

-- ❌ SLOW: Wildcard at start defeats index SELECT * FROM users WHERE email LIKE '%@gmail.com'; -- βœ… FAST: Wildcard at end uses index SELECT * FROM users WHERE email LIKE 'alice%'; -- ❌ SLOW: Function on indexed column prevents index use SELECT * FROM users WHERE LOWER(email) = 'alice@email.com'; -- βœ… FAST: Store lowercase version or use case-insensitive index SELECT * FROM users WHERE email = 'alice@email.com'; -- ❌ SLOW: OR conditions can't use single index well SELECT * FROM products WHERE category = 'Electronics' OR price > 1000; -- βœ… FAST: UNION two indexed queries SELECT * FROM products WHERE category = 'Electronics' UNION SELECT * FROM products WHERE price > 1000;

Example 96: Covering Indexes

Index includes all queried columns (no table lookup needed):

-- Query only needs id and username SELECT id, username FROM users WHERE email = 'alice@email.com'; -- Create covering index (includes all selected columns) CREATE INDEX idx_users_email_covering ON users(email, id, username);

Database can answer query entirely from index, never touching the table. Fastest possible query.

Example 97: Partial Indexes

Index only subset of rows (saves space):

-- Only index active users CREATE INDEX idx_users_active_email ON users(email) WHERE active = TRUE; -- Only index recent orders CREATE INDEX idx_orders_recent ON orders(order_date) WHERE order_date > CURRENT_DATE - INTERVAL '90 days';

If you mostly query active users, why index inactive ones? Partial indexes are smaller and faster.

πŸ”’ Part 9: Transactions - Keeping Data Consistent

Transactions ensure multiple operations succeed or fail togetherβ€”no half-finished states. Critical for maintaining data integrity in applications.

πŸ’‘ Transactions: All or Nothing

Imagine transferring money between bank accounts. Subtract $100 from Alice, add $100 to Bob. If the database crashes between these steps, money disappears (Alice deducted, Bob never credited). Transactions prevent thisβ€”both steps happen, or neither does. It's like a contract: "Do these operations as one unit, and if anything fails, undo everything." This is ACID compliance: Atomicity (all or nothing), Consistency (rules maintained), Isolation (transactions don't interfere), Durability (committed data survives crashes).

Example 98: Basic Transaction - BEGIN, COMMIT, ROLLBACK

Wrap operations in a transaction:

-- Start transaction BEGIN; -- Deduct from Alice UPDATE accounts SET balance = balance - 100 WHERE user_id = 1; -- Add to Bob UPDATE accounts SET balance = balance + 100 WHERE user_id = 2; -- Everything worked? Save changes COMMIT; -- Or if something went wrong: -- ROLLBACK; -- undoes everything since BEGIN

If any statement between BEGIN and COMMIT fails, ROLLBACK undoes all changes. Money transfer is atomicβ€”happens completely or not at all.

Example 99: Transactions in Application Code

Python example with psycopg2:

import psycopg2 conn = psycopg2.connect("dbname=mydb user=postgres") cur = conn.cursor() try: # Transactions start automatically cur.execute("UPDATE accounts SET balance = balance - 100 WHERE user_id = 1") cur.execute("UPDATE accounts SET balance = balance + 100 WHERE user_id = 2") # Commit if both succeeded conn.commit() print("Transfer completed") except Exception as e: # Rollback if anything failed conn.rollback() print(f"Transfer failed: {e}") finally: cur.close() conn.close()

Example 100: Transaction Isolation Levels

Control how transactions see each other's changes:

-- Default: READ COMMITTED (see only committed data) BEGIN; SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- Your queries here COMMIT; -- Stricter: REPEATABLE READ (queries see snapshot from transaction start) BEGIN; SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; -- Your queries here COMMIT; -- Strictest: SERIALIZABLE (transactions appear sequential, slowest) BEGIN; SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; -- Your queries here COMMIT;

Higher isolation = more consistency but slower performance. Most apps use READ COMMITTED (default).

Example 101: Deadlocks - When Transactions Clash

Two transactions waiting for each other create deadlock:

-- Transaction 1 BEGIN; UPDATE accounts SET balance = balance - 50 WHERE user_id = 1; -- waits for lock on user_id = 2... UPDATE accounts SET balance = balance + 50 WHERE user_id = 2; COMMIT; -- Transaction 2 (running simultaneously) BEGIN; UPDATE accounts SET balance = balance - 50 WHERE user_id = 2; -- waits for lock on user_id = 1... UPDATE accounts SET balance = balance + 50 WHERE user_id = 1; COMMIT;

Transaction 1 locks row 1, waits for row 2. Transaction 2 locks row 2, waits for row 1. Deadlock! Database detects this and aborts one transaction. Solution: always lock rows in consistent order (by ID).

Example 102: FOR UPDATE - Explicit Row Locking

Lock rows during SELECT to prevent concurrent modifications:

BEGIN; -- Lock Alice's account for update (other transactions wait) SELECT balance FROM accounts WHERE user_id = 1 FOR UPDATE; -- Now we can safely read, calculate, and update UPDATE accounts SET balance = balance - 100 WHERE user_id = 1; COMMIT;

FOR UPDATE prevents other transactions from modifying these rows until COMMIT. Use for read-then-write patterns.

Example 103: Savepoints - Partial Rollback

Rollback to specific point without aborting entire transaction:

BEGIN; UPDATE accounts SET balance = balance - 100 WHERE user_id = 1; SAVEPOINT transfer_deducted; UPDATE accounts SET balance = balance + 100 WHERE user_id = 2; -- Oops, Bob's account doesn't exist -- Roll back just the second update, keep the first ROLLBACK TO SAVEPOINT transfer_deducted; -- Fix and retry UPDATE accounts SET balance = balance + 100 WHERE user_id = 3; COMMIT;

Savepoints enable complex error handling within transactions.

Example 104: Transaction Best Practices

Rules for reliable transactions:

βœ… Transaction Guidelines

  • Keep transactions short - Long transactions lock rows, blocking other users
  • Don't do external I/O in transactions - No API calls, file writes, or long computations between BEGIN and COMMIT
  • Always handle errors - Use try/except with ROLLBACK in application code
  • Consistent lock order - Always update rows in same order (e.g., by ID ascending) to prevent deadlocks
  • Use appropriate isolation - READ COMMITTED is usually fine; only use SERIALIZABLE when necessary
  • Indexes reduce lock contention - Fast queries mean shorter lock times

πŸŽ“ SQL Mastery Complete!

You've now learned:

  • Subqueries - Scalar, row, and table subqueries; correlated queries; CTEs
  • Advanced SQL - UNION, CASE, window functions (ROW_NUMBER, RANK, LAG/LEAD)
  • Data Manipulation - INSERT, UPDATE, DELETE, UPSERT patterns
  • Performance - Indexes, EXPLAIN, query optimization techniques
  • Transactions - ACID compliance, isolation levels, deadlock prevention

These are professional-level SQL skills. You can now design schemas, write complex queries, optimize performance, and maintain data integrity. The next sections will show you how to apply this SQL mastery in real databases (PostgreSQL, MySQL) and programming languages (Python with SQLAlchemy).

PostgreSQL & MySQL

These industry-standard relational databases power millions of applications. Learn their unique features, performance characteristics, and when to choose each one. Master installation, configuration, and production-ready deployment strategies.

PostgreSQL: The Advanced Open-Source Database

PostgreSQL is often called "the world's most advanced open-source relational database." It's known for strict standards compliance, advanced features, and extensibility. PostgreSQL excels at complex queries, data integrity, and sophisticated data types.

The Swiss Army Knife Metaphor: If MySQL is a reliable hammer, PostgreSQL is a Swiss Army knife. It has tools for almost every database scenarioβ€”from simple CRUD operations to advanced geospatial queries, full-text search, and JSON document storage. It's the database that says "yes" to complex requirements.

PostgreSQL Key Features

πŸ”’ Advanced Data Types

Arrays, JSON/JSONB, hstore, UUID, geometric types, network addresses, ranges, and custom types. Store complex data natively without serialization overhead.

πŸ” Full-Text Search

Built-in full-text search capabilities with multiple languages, ranking, highlighting, and stemming support. No need for external search engines for basic needs.

🎯 ACID Compliance

Strict adherence to ACID principles with MVCC (Multi-Version Concurrency Control) for excellent concurrent performance without locking readers.

🧩 Extensibility

Custom functions, operators, data types, and extensions like PostGIS for geospatial data. You can extend PostgreSQL to fit your exact needs.

PostgreSQL Advanced Data Types

PostgreSQL's rich type system lets you model complex data structures directly in the database:

-- Array Types CREATE TABLE products ( id SERIAL PRIMARY KEY, name VARCHAR(100), tags TEXT[], -- Array of text prices NUMERIC(10,2)[] -- Array of decimals ); INSERT INTO products (name, tags, prices) VALUES ( 'Laptop', ARRAY['electronics', 'computer', 'portable'], ARRAY[999.99, 1299.99, 1499.99] ); -- Query arrays SELECT * FROM products WHERE 'electronics' = ANY(tags); SELECT * FROM products WHERE tags @> ARRAY['computer', 'portable']; -- Contains both -- Unnest arrays SELECT name, unnest(tags) as tag FROM products;
-- JSON and JSONB CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(100), profile JSONB, -- Binary JSON - faster and indexable metadata JSON -- Text JSON ); INSERT INTO users (email, profile) VALUES ( 'alice@example.com', '{ "name": "Alice Johnson", "age": 28, "interests": ["coding", "gaming", "music"], "address": { "city": "San Francisco", "country": "USA" } }'::JSONB ); -- Query JSON fields SELECT * FROM users WHERE profile->>'name' = 'Alice Johnson'; SELECT * FROM users WHERE profile->'address'->>'city' = 'San Francisco'; SELECT * FROM users WHERE profile->'interests' ? 'coding'; -- Contains key -- JSON operators SELECT email, profile->'name' as name, -- Returns JSON profile->>'name' as name_text, -- Returns text profile->'interests'->0 as first_interest, jsonb_array_length(profile->'interests') as interest_count FROM users; -- Update JSON UPDATE users SET profile = jsonb_set( profile, '{age}', '29'::jsonb ) WHERE email = 'alice@example.com'; -- Add to JSON array UPDATE users SET profile = jsonb_set( profile, '{interests}', profile->'interests' || '"photography"'::jsonb );
-- UUID Type CREATE TABLE sessions ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id INTEGER, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); INSERT INTO sessions (user_id) VALUES (1); -- Automatically generates UUID like: 550e8400-e29b-41d4-a716-446655440000 -- Range Types CREATE TABLE room_reservations ( id SERIAL PRIMARY KEY, room_number INTEGER, reserved_period TSTZRANGE -- Timestamp with timezone range ); INSERT INTO room_reservations (room_number, reserved_period) VALUES ( 101, '[2024-01-15 14:00, 2024-01-15 16:00)' ); -- Check for overlaps SELECT * FROM room_reservations WHERE reserved_period && '[2024-01-15 15:00, 2024-01-15 17:00)'::TSTZRANGE; -- Custom composite types CREATE TYPE address AS ( street VARCHAR(100), city VARCHAR(50), zip VARCHAR(10) ); CREATE TABLE companies ( id SERIAL PRIMARY KEY, name VARCHAR(100), headquarters address ); INSERT INTO companies (name, headquarters) VALUES ( 'TechCorp', ROW('123 Main St', 'San Francisco', '94105') );

PostgreSQL Full-Text Search

PostgreSQL includes powerful built-in full-text search capabilities:

-- Create table with full-text search CREATE TABLE articles ( id SERIAL PRIMARY KEY, title TEXT, content TEXT, search_vector TSVECTOR -- Stores searchable text ); -- Create a function to update search vector CREATE FUNCTION articles_search_trigger() RETURNS trigger AS $$ BEGIN NEW.search_vector := setweight(to_tsvector('english', COALESCE(NEW.title, '')), 'A') || setweight(to_tsvector('english', COALESCE(NEW.content, '')), 'B'); RETURN NEW; END; $$ LANGUAGE plpgsql; -- Create trigger CREATE TRIGGER tsvector_update BEFORE INSERT OR UPDATE ON articles FOR EACH ROW EXECUTE FUNCTION articles_search_trigger(); -- Create GIN index for fast searching CREATE INDEX articles_search_idx ON articles USING GIN(search_vector); -- Insert sample data INSERT INTO articles (title, content) VALUES ('PostgreSQL Advanced Features', 'PostgreSQL offers many advanced features including full-text search.'), ('Database Performance Tuning', 'Learn how to optimize database queries and indexes for better performance.'); -- Search with ranking SELECT id, title, ts_rank(search_vector, query) AS rank FROM articles, to_tsquery('english', 'postgresql & features') AS query WHERE search_vector @@ query ORDER BY rank DESC; -- Search with highlighting SELECT id, title, ts_headline('english', content, query, 'MaxWords=50, MinWords=25') AS snippet FROM articles, to_tsquery('english', 'database | performance') AS query WHERE search_vector @@ query;

MySQL: The Reliable Workhorse

MySQL is the world's most popular open-source database, powering everything from small websites to massive web applications. It's known for speed, reliability, and ease of use. MySQL excels at read-heavy workloads and simple to moderate complexity queries.

The Reliable Truck Metaphor: MySQL is like a reliable pickup truck. It's fast, straightforward, and gets the job done efficiently for most tasks. It might not have all the advanced features of luxury vehicles, but it's incredibly dependable and easy to maintain.

MySQL Key Features

⚑ Performance

Extremely fast for read operations and simple queries. Optimized for web workloads with excellent caching mechanisms.

πŸ”„ Replication

Built-in master-slave and master-master replication. Easy to scale horizontally with read replicas.

πŸ—‚οΈ Storage Engines

Multiple storage engines (InnoDB, MyISAM) for different use cases. InnoDB for transactions, MyISAM for speed.

🌐 Web-Optimized

Perfect for web applications. Powers WordPress, Drupal, and countless PHP applications. LAMP stack standard.

MySQL Storage Engines

MySQL's pluggable storage engine architecture lets you choose the right engine for each table:

-- InnoDB: Default engine, ACID-compliant with transactions CREATE TABLE orders ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, total DECIMAL(10,2), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id) ) ENGINE=InnoDB; -- Features: Transactions, foreign keys, row-level locking START TRANSACTION; INSERT INTO orders (user_id, total) VALUES (1, 99.99); INSERT INTO order_items (order_id, product_id, quantity) VALUES (LAST_INSERT_ID(), 5, 2); COMMIT; -- MyISAM: Fast for read-heavy operations, no transactions CREATE TABLE page_views ( id INT AUTO_INCREMENT PRIMARY KEY, page VARCHAR(255), views INT DEFAULT 0, last_viewed DATETIME ) ENGINE=MyISAM; -- Features: Fast INSERT, full-text search (before MySQL 5.6), table-level locking -- Good for: Logging, read-mostly data, simple operations -- MEMORY: Data stored in RAM CREATE TABLE session_data ( session_id VARCHAR(32) PRIMARY KEY, data TEXT, expires INT ) ENGINE=MEMORY; -- Use for: Session storage, temporary data, caching -- Limitation: Data lost on restart -- Check engine for existing table SHOW TABLE STATUS WHERE Name = 'orders'; -- Convert engine ALTER TABLE old_table ENGINE=InnoDB;

MySQL Replication

MySQL makes it easy to set up replication for scaling and high availability:

-- MASTER SERVER CONFIGURATION -- Edit my.cnf or my.ini [mysqld] server-id = 1 log-bin = mysql-bin binlog-do-db = production_db binlog-ignore-db = test_db -- Create replication user on master CREATE USER 'replicator'@'%' IDENTIFIED BY 'strong_password'; GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%'; FLUSH PRIVILEGES; -- Get master status SHOW MASTER STATUS; -- Note: File name and Position -- SLAVE SERVER CONFIGURATION -- Edit my.cnf or my.ini [mysqld] server-id = 2 relay-log = mysql-relay-bin read-only = 1 -- Configure slave to connect to master CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='replicator', MASTER_PASSWORD='strong_password', MASTER_LOG_FILE='mysql-bin.000001', -- From SHOW MASTER STATUS MASTER_LOG_POS=12345; -- From SHOW MASTER STATUS -- Start replication START SLAVE; -- Check replication status SHOW SLAVE STATUS\G -- Important fields to monitor: -- Slave_IO_Running: Yes -- Slave_SQL_Running: Yes -- Seconds_Behind_Master: Should be low -- Read queries go to slaves, writes go to master -- Application configuration example: -- WRITE_DB_HOST = 'master.example.com' -- READ_DB_HOST = 'slave1.example.com'

PostgreSQL vs MySQL: Key Differences

Understanding the differences helps you choose the right database for your needs:

Feature PostgreSQL MySQL
Data Types Extensive: JSON, arrays, ranges, UUID, custom types Basic: Standard SQL types, limited JSON support
Standards Compliance Strict SQL standard compliance More flexible, some non-standard behavior
Concurrency MVCC - readers never block writers InnoDB uses row-level locking
Performance Better for complex queries, writes, analytics Better for simple reads, web workloads
Replication Streaming, logical, sync/async options Master-slave, master-master built-in
Full-Text Search Advanced built-in FTS with ranking Basic FTS in InnoDB
JSON Support Native JSONB type, indexable, rich operators JSON type, limited querying capabilities
Window Functions Full support since 8.4 Added in MySQL 8.0
CTEs (WITH queries) Full support, including recursive Added in MySQL 8.0
Stored Procedures PL/pgSQL, PL/Python, PL/Perl, etc. Proprietary syntax
Extensions PostGIS, pg_trgm, hstore, many more Limited plugin system
License PostgreSQL License (MIT-like) GPL (Oracle-owned) / Commercial

Installation and Setup

PostgreSQL Installation

### Ubuntu/Debian sudo apt update sudo apt install postgresql postgresql-contrib # Start service sudo systemctl start postgresql sudo systemctl enable postgresql # Switch to postgres user sudo -i -u postgres # Access PostgreSQL prompt psql # Create database and user CREATE DATABASE myapp_db; CREATE USER myapp_user WITH PASSWORD 'secure_password'; GRANT ALL PRIVILEGES ON DATABASE myapp_db TO myapp_user; ### macOS (with Homebrew) brew install postgresql@15 brew services start postgresql@15 # Initialize and start initdb /usr/local/var/postgres pg_ctl -D /usr/local/var/postgres start ### Windows # Download installer from postgresql.org # Use Stack Builder for additional tools ### Docker docker run --name postgres-dev \ -e POSTGRES_PASSWORD=mysecretpassword \ -e POSTGRES_DB=myapp \ -p 5432:5432 \ -d postgres:15 # Connect to Docker PostgreSQL docker exec -it postgres-dev psql -U postgres

MySQL Installation

### Ubuntu/Debian sudo apt update sudo apt install mysql-server # Secure installation sudo mysql_secure_installation # Start service sudo systemctl start mysql sudo systemctl enable mysql # Access MySQL sudo mysql # Create database and user CREATE DATABASE myapp_db; CREATE USER 'myapp_user'@'localhost' IDENTIFIED BY 'secure_password'; GRANT ALL PRIVILEGES ON myapp_db.* TO 'myapp_user'@'localhost'; FLUSH PRIVILEGES; ### macOS (with Homebrew) brew install mysql brew services start mysql # Secure installation mysql_secure_installation ### Windows # Download installer from mysql.com # Use MySQL Installer for complete setup ### Docker docker run --name mysql-dev \ -e MYSQL_ROOT_PASSWORD=rootpassword \ -e MYSQL_DATABASE=myapp \ -e MYSQL_USER=myapp_user \ -e MYSQL_PASSWORD=userpassword \ -p 3306:3306 \ -d mysql:8.0 # Connect to Docker MySQL docker exec -it mysql-dev mysql -u root -p

Connection Configuration

# PostgreSQL connection strings postgresql://user:password@localhost:5432/database postgresql://user:password@localhost/database?sslmode=require # Python with psycopg2 import psycopg2 conn = psycopg2.connect( host="localhost", port=5432, database="myapp_db", user="myapp_user", password="secure_password" ) # Python with SQLAlchemy from sqlalchemy import create_engine engine = create_engine( 'postgresql://myapp_user:secure_password@localhost:5432/myapp_db' ) # MySQL connection strings mysql://user:password@localhost:3306/database mysql://user:password@localhost/database?charset=utf8mb4 # Python with mysql-connector import mysql.connector conn = mysql.connector.connect( host="localhost", port=3306, database="myapp_db", user="myapp_user", password="secure_password" ) # Python with SQLAlchemy from sqlalchemy import create_engine engine = create_engine( 'mysql+mysqlconnector://myapp_user:secure_password@localhost:3306/myapp_db' )

Advanced PostgreSQL: CTEs and Window Functions

Common Table Expressions (CTEs) and window functions enable complex analytical queries:

-- Common Table Expressions (WITH queries) -- Simple CTE WITH high_value_customers AS ( SELECT customer_id, SUM(total) as total_spent FROM orders WHERE order_date >= '2024-01-01' GROUP BY customer_id HAVING SUM(total) > 1000 ) SELECT c.name, c.email, hvc.total_spent FROM customers c JOIN high_value_customers hvc ON c.id = hvc.customer_id ORDER BY hvc.total_spent DESC; -- Multiple CTEs WITH customer_orders AS ( SELECT customer_id, COUNT(*) as order_count, SUM(total) as total_spent FROM orders GROUP BY customer_id ), customer_segments AS ( SELECT customer_id, order_count, total_spent, CASE WHEN total_spent > 1000 THEN 'Premium' WHEN total_spent > 500 THEN 'Regular' ELSE 'Basic' END as segment FROM customer_orders ) SELECT segment, COUNT(*) as customer_count, AVG(total_spent) as avg_spent, AVG(order_count) as avg_orders FROM customer_segments GROUP BY segment ORDER BY avg_spent DESC; -- Recursive CTE (for hierarchical data) CREATE TABLE employees ( id SERIAL PRIMARY KEY, name VARCHAR(100), manager_id INTEGER REFERENCES employees(id) ); -- Find all subordinates of a manager WITH RECURSIVE subordinates AS ( -- Base case: direct reports SELECT id, name, manager_id, 1 as level FROM employees WHERE manager_id = 1 -- Manager's ID UNION ALL -- Recursive case: reports of reports SELECT e.id, e.name, e.manager_id, s.level + 1 FROM employees e JOIN subordinates s ON e.manager_id = s.id ) SELECT * FROM subordinates ORDER BY level, name;
-- Window Functions -- Running totals SELECT order_date, customer_id, total, SUM(total) OVER (ORDER BY order_date) as running_total FROM orders ORDER BY order_date; -- Rank customers by spending SELECT customer_id, total_spent, RANK() OVER (ORDER BY total_spent DESC) as rank, DENSE_RANK() OVER (ORDER BY total_spent DESC) as dense_rank, ROW_NUMBER() OVER (ORDER BY total_spent DESC) as row_num FROM ( SELECT customer_id, SUM(total) as total_spent FROM orders GROUP BY customer_id ) customer_totals; -- Moving average SELECT order_date, total, AVG(total) OVER ( ORDER BY order_date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) as moving_avg_7days FROM orders ORDER BY order_date; -- Partition by groups SELECT category, product_name, price, AVG(price) OVER (PARTITION BY category) as category_avg, price - AVG(price) OVER (PARTITION BY category) as diff_from_avg, RANK() OVER (PARTITION BY category ORDER BY price DESC) as rank_in_category FROM products ORDER BY category, rank_in_category; -- Lag and Lead (compare with previous/next rows) SELECT order_date, total, LAG(total, 1) OVER (ORDER BY order_date) as previous_order, LEAD(total, 1) OVER (ORDER BY order_date) as next_order, total - LAG(total, 1) OVER (ORDER BY order_date) as difference FROM orders ORDER BY order_date;

PostgreSQL Materialized Views

Materialized views cache complex query results for faster access:

-- Create a materialized view CREATE MATERIALIZED VIEW customer_summary AS SELECT c.id, c.name, c.email, COUNT(o.id) as total_orders, SUM(o.total) as total_spent, MAX(o.order_date) as last_order_date, AVG(o.total) as avg_order_value FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.id, c.name, c.email; -- Create index on materialized view CREATE INDEX idx_customer_summary_spent ON customer_summary(total_spent DESC); -- Query the materialized view (fast!) SELECT * FROM customer_summary WHERE total_spent > 1000 ORDER BY total_spent DESC; -- Refresh the materialized view REFRESH MATERIALIZED VIEW customer_summary; -- Concurrent refresh (doesn't lock reads) REFRESH MATERIALIZED VIEW CONCURRENTLY customer_summary; -- Drop materialized view DROP MATERIALIZED VIEW customer_summary; -- Materialized view with no data initially CREATE MATERIALIZED VIEW sales_by_month AS SELECT DATE_TRUNC('month', order_date) as month, COUNT(*) as order_count, SUM(total) as revenue FROM orders GROUP BY DATE_TRUNC('month', order_date) WITH NO DATA; -- Populate it later REFRESH MATERIALIZED VIEW sales_by_month;

Advanced MySQL: Stored Procedures and Triggers

Stored procedures encapsulate business logic in the database:

-- MySQL Stored Procedure DELIMITER // CREATE PROCEDURE GetCustomerOrders( IN customer_id INT, OUT order_count INT, OUT total_spent DECIMAL(10,2) ) BEGIN SELECT COUNT(*), COALESCE(SUM(total), 0) INTO order_count, total_spent FROM orders WHERE user_id = customer_id; END // DELIMITER ; -- Call the procedure CALL GetCustomerOrders(1, @count, @spent); SELECT @count, @spent; -- Procedure with control flow DELIMITER // CREATE PROCEDURE ProcessOrder( IN p_customer_id INT, IN p_total DECIMAL(10,2) ) BEGIN DECLARE customer_exists INT; DECLARE discount DECIMAL(5,2) DEFAULT 0; -- Check if customer exists SELECT COUNT(*) INTO customer_exists FROM customers WHERE id = p_customer_id; IF customer_exists = 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Customer not found'; END IF; -- Calculate discount for high-value orders IF p_total > 1000 THEN SET discount = 0.10; ELSEIF p_total > 500 THEN SET discount = 0.05; END IF; -- Insert order INSERT INTO orders (customer_id, total, discount) VALUES (p_customer_id, p_total, discount); -- Update customer statistics UPDATE customer_stats SET total_orders = total_orders + 1, total_spent = total_spent + p_total WHERE customer_id = p_customer_id; SELECT 'Order processed successfully' AS status; END // DELIMITER ; -- Procedure with cursor (loop through results) DELIMITER // CREATE PROCEDURE ArchiveOldOrders() BEGIN DECLARE done INT DEFAULT FALSE; DECLARE order_id INT; DECLARE cur CURSOR FOR SELECT id FROM orders WHERE order_date < DATE_SUB(CURDATE(), INTERVAL 1 YEAR); DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur; read_loop: LOOP FETCH cur INTO order_id; IF done THEN LEAVE read_loop; END IF; INSERT INTO archived_orders SELECT * FROM orders WHERE id = order_id; DELETE FROM orders WHERE id = order_id; END LOOP; CLOSE cur; END // DELIMITER ;
-- MySQL Triggers -- After insert trigger DELIMITER // CREATE TRIGGER after_order_insert AFTER INSERT ON orders FOR EACH ROW BEGIN -- Update customer total UPDATE customers SET total_orders = total_orders + 1, last_order_date = NEW.order_date WHERE id = NEW.customer_id; -- Log the action INSERT INTO order_audit (order_id, action, timestamp) VALUES (NEW.id, 'INSERT', NOW()); END // DELIMITER ; -- Before update trigger (validation) DELIMITER // CREATE TRIGGER before_product_update BEFORE UPDATE ON products FOR EACH ROW BEGIN IF NEW.price < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Price cannot be negative'; END IF; IF NEW.stock < 0 THEN SET NEW.stock = 0; END IF; -- Track who made the change SET NEW.updated_by = USER(); SET NEW.updated_at = NOW(); END // DELIMITER ; -- After delete trigger DELIMITER // CREATE TRIGGER after_order_delete AFTER DELETE ON orders FOR EACH ROW BEGIN -- Archive deleted order INSERT INTO deleted_orders ( original_id, customer_id, total, deleted_at ) VALUES ( OLD.id, OLD.customer_id, OLD.total, NOW() ); -- Update customer stats UPDATE customers SET total_orders = total_orders - 1 WHERE id = OLD.customer_id; END // DELIMITER ; -- View all triggers SHOW TRIGGERS; -- Drop trigger DROP TRIGGER IF EXISTS after_order_insert;

Performance Tuning: PostgreSQL

Optimize PostgreSQL for maximum performance:

-- Check query performance with EXPLAIN EXPLAIN ANALYZE SELECT c.name, COUNT(o.id) as order_count FROM customers c LEFT JOIN orders o ON c.id = o.customer_id GROUP BY c.name ORDER BY order_count DESC; -- Create indexes CREATE INDEX idx_orders_customer ON orders(customer_id); CREATE INDEX idx_orders_date ON orders(order_date); CREATE INDEX idx_orders_customer_date ON orders(customer_id, order_date); -- Partial index (index subset of rows) CREATE INDEX idx_active_orders ON orders(customer_id) WHERE status = 'active'; -- Index on expression CREATE INDEX idx_email_lower ON customers(LOWER(email)); -- GIN index for full-text search and JSONB CREATE INDEX idx_products_search ON products USING GIN(search_vector); CREATE INDEX idx_users_profile ON users USING GIN(profile); -- Check index usage SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes ORDER BY idx_scan DESC; -- Find unused indexes SELECT schemaname, tablename, indexname, pg_size_pretty(pg_relation_size(indexrelid)) as size FROM pg_stat_user_indexes WHERE idx_scan = 0 ORDER BY pg_relation_size(indexrelid) DESC;
-- PostgreSQL configuration tuning -- Edit postgresql.conf # Memory settings (adjust based on available RAM) shared_buffers = 256MB # 25% of RAM effective_cache_size = 1GB # 50-75% of RAM work_mem = 16MB # Per-operation memory maintenance_work_mem = 128MB # For VACUUM, CREATE INDEX # Connection settings max_connections = 100 max_prepared_transactions = 100 # Query planning random_page_cost = 1.1 # Lower for SSD effective_io_concurrency = 200 # Higher for SSD # Logging log_min_duration_statement = 1000 # Log slow queries (ms) log_line_prefix = '%t [%p]: [%l-1] ' # Autovacuum (keep statistics up to date) autovacuum = on autovacuum_max_workers = 3 -- Vacuum and analyze VACUUM ANALYZE customers; VACUUM FULL; -- Reclaim space (locks table) -- Check table bloat SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS size FROM pg_tables WHERE schemaname = 'public' ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;

Performance Tuning: MySQL

Optimize MySQL for your workload:

-- Check query performance EXPLAIN SELECT c.name, COUNT(o.id) as order_count FROM customers c LEFT JOIN orders o ON c.customer_id = c.id GROUP BY c.name ORDER BY order_count DESC; -- Use extended explain EXPLAIN FORMAT=JSON SELECT * FROM orders WHERE customer_id = 1; -- Create indexes CREATE INDEX idx_orders_customer ON orders(customer_id); CREATE INDEX idx_orders_date ON orders(order_date); -- Composite index CREATE INDEX idx_orders_customer_status ON orders(customer_id, status); -- Full-text index CREATE FULLTEXT INDEX idx_articles_content ON articles(title, content); -- Check index usage SELECT TABLE_NAME, INDEX_NAME, CARDINALITY FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = 'myapp_db' ORDER BY TABLE_NAME, INDEX_NAME; -- Show slow queries SHOW VARIABLES LIKE 'slow_query_log'; SET GLOBAL slow_query_log = 'ON'; SET GLOBAL long_query_time = 2; -- Log queries > 2 seconds -- Analyze table statistics ANALYZE TABLE orders; -- Optimize table (defragment) OPTIMIZE TABLE orders;
-- MySQL configuration tuning -- Edit my.cnf or my.ini [mysqld] # Memory settings innodb_buffer_pool_size = 1G # 70-80% of RAM for InnoDB innodb_log_file_size = 256M innodb_log_buffer_size = 16M # Connection settings max_connections = 200 max_allowed_packet = 64M # Query cache (deprecated in MySQL 8.0) query_cache_type = 1 query_cache_size = 128M # InnoDB settings innodb_flush_log_at_trx_commit = 2 # Better performance, slightly less durable innodb_file_per_table = 1 innodb_flush_method = O_DIRECT # Temporary tables tmp_table_size = 64M max_heap_table_size = 64M # Slow query log slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow-query.log long_query_time = 2 -- Check InnoDB status SHOW ENGINE INNODB STATUS; -- Monitor server performance SHOW GLOBAL STATUS LIKE 'Threads%'; SHOW GLOBAL STATUS LIKE 'Questions%'; SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool%'; -- Check table sizes SELECT TABLE_NAME, ROUND(DATA_LENGTH / 1024 / 1024, 2) AS 'Data Size (MB)', ROUND(INDEX_LENGTH / 1024 / 1024, 2) AS 'Index Size (MB)', ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) AS 'Total (MB)' FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'myapp_db' ORDER BY (DATA_LENGTH + INDEX_LENGTH) DESC;

When to Use PostgreSQL

Choose PostgreSQL when you need:

βœ… PostgreSQL is Best For:

  • Complex queries: Analytical workloads, complex joins, subqueries, CTEs
  • Data integrity: Strict ACID compliance, foreign keys, constraints absolutely required
  • Advanced features: JSON storage, full-text search, arrays, geospatial data (PostGIS)
  • Extensibility: Need custom data types, functions, or extensions
  • Concurrent writes: Many simultaneous write operations (MVCC shines here)
  • Standards compliance: Need portable SQL that follows standards strictly
  • Read and write balance: Applications with roughly equal read/write loads
  • Data warehousing: Analytics, reporting, OLAP workloads
  • Scientific/research data: Complex data types, array operations
  • Future-proofing: Want access to cutting-edge database features

🎯 Perfect Use Cases

Financial systems, data analytics platforms, geospatial applications, complex SaaS products, research databases, data warehouses

🏒 Who Uses It

Instagram, Reddit, Spotify, Twitch, Apple, Cisco, IMDB - companies that need reliability and advanced features

When to Use MySQL

Choose MySQL when you need:

βœ… MySQL is Best For:

  • Web applications: LAMP stack, PHP applications, WordPress, Drupal
  • Read-heavy workloads: High read-to-write ratio (10:1 or higher)
  • Simplicity: Straightforward relational data, simple queries
  • Replication: Easy master-slave setup for scaling reads
  • Speed: Simple queries need to be extremely fast
  • Maturity: Established patterns, extensive documentation, large community
  • Hosting compatibility: Widely supported by shared hosting providers
  • MySQL ecosystem: Need tools built specifically for MySQL
  • Resource constraints: Smaller footprint, less memory required
  • Legacy compatibility: Existing MySQL codebase or team expertise

🎯 Perfect Use Cases

Content management systems, e-commerce sites, web forums, blogging platforms, simple CRUD applications, read-heavy APIs

🏒 Who Uses It

Facebook, Twitter, YouTube, Netflix (for some services), Airbnb, Uber - companies with massive read-heavy workloads

Migration Considerations

Switching between PostgreSQL and MySQL requires careful planning:

-- Common MySQL to PostgreSQL syntax differences -- Auto-increment -- MySQL: CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY); -- PostgreSQL: CREATE TABLE users (id SERIAL PRIMARY KEY); -- String concatenation -- MySQL: SELECT CONCAT(first_name, ' ', last_name) FROM users; -- PostgreSQL: SELECT first_name || ' ' || last_name FROM users; -- Date functions -- MySQL: SELECT NOW(), CURDATE(), DATE_ADD(NOW(), INTERVAL 1 DAY); -- PostgreSQL: SELECT NOW(), CURRENT_DATE, NOW() + INTERVAL '1 day'; -- LIMIT/OFFSET -- MySQL: SELECT * FROM users LIMIT 10 OFFSET 20; -- PostgreSQL: (same, but also supports) SELECT * FROM users OFFSET 20 LIMIT 10; SELECT * FROM users OFFSET 20 FETCH FIRST 10 ROWS ONLY; -- Case-insensitive comparison -- MySQL: SELECT * FROM users WHERE email = 'test@example.com'; -- case-insensitive by default -- PostgreSQL: SELECT * FROM users WHERE LOWER(email) = LOWER('test@example.com'); SELECT * FROM users WHERE email ILIKE 'test@example.com'; -- Boolean values -- MySQL: SELECT * FROM users WHERE is_active = 1; -- PostgreSQL: SELECT * FROM users WHERE is_active = TRUE;

πŸ”„ Migration Tools

  • pgloader: Powerful tool for migrating MySQL to PostgreSQL
  • AWS DMS: Database Migration Service for cloud migrations
  • mysqldump/pg_dump: Native tools for backup and restore
  • Custom scripts: Python scripts using SQLAlchemy for complex migrations

Best Practices for Both Databases

πŸ” Security

Use SSL/TLS connections, strong passwords, limited user privileges, parameter binding to prevent SQL injection, regular security updates

πŸ’Ύ Backups

Automated daily backups, test restore procedures, point-in-time recovery, offsite backup storage, document recovery procedures

πŸ“Š Monitoring

Track slow queries, monitor connection count, watch disk usage, set up alerts, analyze query patterns, track growth trends

🎯 Optimization

Index frequently queried columns, analyze query plans, normalize data appropriately, use connection pooling, cache when possible

The Restaurant Kitchen Metaphor: PostgreSQL is like a professional kitchen with specialized equipment for every taskβ€”sous vide machines, molecular gastronomy tools, wood-fired ovens. It can handle any recipe but requires more expertise. MySQL is like a well-equipped home kitchenβ€”has everything you need for great meals, faster to learn, perfect for most cooking needs. Choose based on your menu (use case) and chef's skills (team expertise).

Practice Exercise: Multi-Database Project

# Exercise: Build a blog with both databases # PostgreSQL version (advanced features) CREATE TABLE posts ( id SERIAL PRIMARY KEY, title VARCHAR(200), content TEXT, tags TEXT[], -- Array of tags metadata JSONB, -- Author info, settings search_vector TSVECTOR, -- Full-text search published_at TIMESTAMP ); CREATE INDEX idx_posts_tags ON posts USING GIN(tags); CREATE INDEX idx_posts_search ON posts USING GIN(search_vector); # MySQL version (simple and fast) CREATE TABLE posts ( id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200), content TEXT, published_at TIMESTAMP, INDEX idx_published (published_at) ) ENGINE=InnoDB; CREATE TABLE post_tags ( post_id INT, tag VARCHAR(50), PRIMARY KEY (post_id, tag), FOREIGN KEY (post_id) REFERENCES posts(id) ) ENGINE=InnoDB; # Challenge: Implement the same blog functionality in both # databases and compare performance, code complexity, and features

πŸŽ“ Key Takeaways

  • Both PostgreSQL and MySQL are excellent databasesβ€”choose based on your specific needs
  • PostgreSQL excels at complex queries, data integrity, and advanced features
  • MySQL excels at simple queries, read-heavy workloads, and ease of use
  • Modern versions of both have adopted features from each other
  • Your team's expertise and existing infrastructure matter as much as technical features
  • Performance tuning is crucial for bothβ€”proper indexes and configuration make huge differences
  • Start simple, optimize when needed, and choose the tool that fits your requirements

NoSQL (MongoDB/Redis)

Not all data fits in tables. Document databases, key-value stores, and caching layers offer flexibility and performance for modern applications. Understand when to break from relational models and embrace schemaless design.

Why NoSQL?

Traditional relational databases are powerful, but they're not always the best tool for every job. NoSQL databases emerged to solve specific problems that SQL databases struggle with.

πŸ“š The Library Metaphor

SQL databases are like traditional libraries with strict cataloging systemsβ€”every book must follow the Dewey Decimal System. NoSQL is like a modern bookstore where books can be organized by genre, author, popularity, or any system that makes sense for your customers. Sometimes you need the rigor of the library; sometimes you need the flexibility of the bookstore.

The Problems NoSQL Solves

πŸš€ Scalability

SQL databases scale vertically (bigger servers). NoSQL databases scale horizontally (more servers). When you're serving millions of users, horizontal scaling is often the only economical option.

πŸ“Š Flexible Schema

Not all data has the same shape. User profiles might have different fields, product catalogs might have category-specific attributes. NoSQL lets you store heterogeneous data without forcing everything into rigid tables.

⚑ Performance

When you need millisecond response times for simple queries, NoSQL databases optimized for specific access patterns can be orders of magnitude faster than SQL with complex joins.

🌍 Distributed Systems

Modern applications run across multiple data centers globally. NoSQL databases are built from the ground up for distributed, eventually-consistent architectures.

The Four Types of NoSQL Databases

Type Data Model Examples Best For
Document Store JSON-like documents with nested structures MongoDB, CouchDB, Couchbase Content management, user profiles, catalogs
Key-Value Store Simple key β†’ value mappings Redis, Memcached, DynamoDB Caching, sessions, real-time data
Column-Family Wide columns, optimized for write-heavy workloads Cassandra, HBase, ScyllaDB Time-series, analytics, IoT data
Graph Database Nodes and edges representing relationships Neo4j, Amazon Neptune, ArangoDB Social networks, recommendation engines

The CAP Theorem: Choose Two

The CAP theorem states that distributed databases can only guarantee two of three properties:

CAP Theorem Properties

  • Consistency (C): Every read receives the most recent write or an error
  • Availability (A): Every request receives a response (without guarantee it's the most recent)
  • Partition Tolerance (P): System continues operating despite network partitions

In reality, network partitions will happen in distributed systems, so you're really choosing between CP (Consistency + Partition Tolerance) or AP (Availability + Partition Tolerance).

Database CAP Classification Trade-off Decision
MongoDB CP (configurable to AP) Prefers consistency, but you can configure for availability
Redis CP (single node) / AP (cluster) Consistency in single-node, eventual consistency in cluster
Cassandra AP Always available, eventually consistent
PostgreSQL CA (traditional RDBMS) Consistent & available, but not partition-tolerant

🏦 The Banking Metaphor

Imagine a bank with branches worldwide. CP systems are like requiring every branch to check with headquarters before completing a transactionβ€”slow but always consistent. AP systems are like letting branches operate independently even if headquarters is unreachableβ€”fast and always available, but they might not have the latest balance until they sync up.

MongoDB: Complete Guide

MongoDB is the most popular document database. It stores data in JSON-like documents (BSON format), making it natural to work with from JavaScript, Python, and other modern languages.

MongoDB Core Concepts

// MongoDB stores data in documents (like JSON objects) // Documents are grouped into collections (like SQL tables) // Collections are stored in databases // A MongoDB document - flexible, nested structure { "_id": ObjectId("507f1f77bcf86cd799439011"), "username": "alice_2026", "email": "alice@example.com", "profile": { "firstName": "Alice", "lastName": "Johnson", "bio": "Software engineer & coffee enthusiast", "avatar": "https://cdn.example.com/avatars/alice.jpg" }, "interests": ["coding", "machine learning", "hiking"], "followers": 1247, "following": 892, "createdAt": ISODate("2025-01-15T10:30:00Z"), "lastLogin": ISODate("2026-01-04T08:15:22Z"), "settings": { "notifications": true, "theme": "dark", "language": "en" } }

Installing and Running MongoDB

# Install MongoDB Community Edition (macOS with Homebrew) brew tap mongodb/brew brew install mongodb-community # Start MongoDB service brew services start mongodb-community # Or run manually mongod --config /usr/local/etc/mongod.conf # Install MongoDB Shell (mongosh) brew install mongosh # Connect to MongoDB mongosh # For Ubuntu/Debian sudo apt-get install -y mongodb-org # For Windows, download from mongodb.com and install # Then start as a Windows service

MongoDB CRUD Operations

// Connect to MongoDB shell (mongosh) // Switch to (or create) a database use socialapp // INSERT - Create documents // Insert one document db.users.insertOne({ username: "alice_2026", email: "alice@example.com", age: 28, location: "San Francisco", interests: ["coding", "hiking", "photography"] }) // Insert multiple documents db.users.insertMany([ { username: "bob_dev", email: "bob@example.com", age: 32, location: "New York", interests: ["coding", "gaming"] }, { username: "charlie_ml", email: "charlie@example.com", age: 27, location: "London", interests: ["AI", "research", "chess"] } ]) // FIND - Read documents // Find all documents db.users.find() // Find with pretty formatting db.users.find().pretty() // Find one document db.users.findOne({ username: "alice_2026" }) // Find with conditions db.users.find({ age: { $gte: 30 } }) // age >= 30 db.users.find({ location: "San Francisco" }) db.users.find({ interests: "coding" }) // Array contains "coding" // Multiple conditions (AND) db.users.find({ age: { $gte: 25 }, location: "San Francisco" }) // OR conditions db.users.find({ $or: [ { location: "New York" }, { location: "London" } ] }) // Complex queries db.users.find({ age: { $gte: 25, $lte: 35 }, interests: { $in: ["coding", "AI"] } }) // Projection - Select specific fields db.users.find( { location: "San Francisco" }, { username: 1, email: 1, _id: 0 } // 1 = include, 0 = exclude ) // UPDATE - Modify documents // Update one document db.users.updateOne( { username: "alice_2026" }, { $set: { age: 29, lastLogin: new Date() } } ) // Update multiple documents db.users.updateMany( { location: "San Francisco" }, { $set: { timezone: "PST" } } ) // Array operations db.users.updateOne( { username: "alice_2026" }, { $push: { interests: "yoga" } } // Add to array ) db.users.updateOne( { username: "alice_2026" }, { $pull: { interests: "hiking" } } // Remove from array ) // Increment/decrement db.users.updateOne( { username: "alice_2026" }, { $inc: { followers: 1 } } // Increment by 1 ) // Upsert - Update or insert if not exists db.users.updateOne( { username: "diana_new" }, { $set: { email: "diana@example.com", age: 24 } }, { upsert: true } ) // DELETE - Remove documents // Delete one document db.users.deleteOne({ username: "bob_dev" }) // Delete multiple documents db.users.deleteMany({ age: { $lt: 18 } }) // Delete all documents in collection db.users.deleteMany({})

MongoDB Query Operators

Operator Description Example
$eq Equal to { age: { $eq: 25 } }
$ne Not equal to { status: { $ne: "banned" } }
$gt, $gte Greater than, greater than or equal { age: { $gte: 18 } }
$lt, $lte Less than, less than or equal { price: { $lt: 100 } }
$in Value in array { status: { $in: ["active", "pending"] } }
$nin Value not in array { role: { $nin: ["admin", "moderator"] } }
$exists Field exists { phone: { $exists: true } }
$regex Regular expression match { email: { $regex: /@gmail\.com$/ } }

MongoDB Indexes

Indexes make queries fast. Without indexes, MongoDB must scan every document (collection scan). With indexes, it can jump directly to matching documents.

// Create index on single field db.users.createIndex({ username: 1 }) // 1 = ascending, -1 = descending // Create compound index (multiple fields) db.users.createIndex({ location: 1, age: -1 }) // Create unique index (prevents duplicates) db.users.createIndex({ email: 1 }, { unique: true }) // Create text index for full-text search db.posts.createIndex({ title: "text", content: "text" }) // Text search with text index db.posts.find({ $text: { $search: "mongodb tutorial" } }) // Create index on array field db.users.createIndex({ interests: 1 }) // Create TTL index (auto-delete after expiry) db.sessions.createIndex( { createdAt: 1 }, { expireAfterSeconds: 3600 } // Delete after 1 hour ) // View all indexes db.users.getIndexes() // Drop index db.users.dropIndex("username_1") // Explain query (see if index is used) db.users.find({ username: "alice_2026" }).explain("executionStats")

⚑ Index Best Practices

  • Index fields you query frequently
  • Compound indexes should match your query patterns (field order matters!)
  • Indexes speed up reads but slow down writes (they must be updated on every insert/update)
  • Don't over-indexβ€”each index uses memory and disk space
  • Use .explain() to verify your queries use indexes

MongoDB Aggregation Pipeline

Aggregation is MongoDB's equivalent of SQL's GROUP BY, JOIN, and complex calculations. It processes documents through a pipeline of stages.

// Sample data: e-commerce orders db.orders.insertMany([ { orderId: "ORD001", customer: "alice@example.com", items: [ { product: "Laptop", quantity: 1, price: 1200 }, { product: "Mouse", quantity: 2, price: 25 } ], status: "delivered", orderDate: ISODate("2026-01-01") }, { orderId: "ORD002", customer: "bob@example.com", items: [ { product: "Keyboard", quantity: 1, price: 80 }, { product: "Monitor", quantity: 1, price: 300 } ], status: "delivered", orderDate: ISODate("2026-01-02") }, { orderId: "ORD003", customer: "alice@example.com", items: [ { product: "USB Cable", quantity: 3, price: 10 } ], status: "pending", orderDate: ISODate("2026-01-03") } ]) // AGGREGATION EXAMPLE 1: Calculate total sales per customer db.orders.aggregate([ // Stage 1: Unwind items array (create document per item) { $unwind: "$items" }, // Stage 2: Calculate subtotal for each item { $addFields: { itemTotal: { $multiply: ["$items.quantity", "$items.price"] } } }, // Stage 3: Group by customer and sum totals { $group: { _id: "$customer", totalSpent: { $sum: "$itemTotal" }, orderCount: { $sum: 1 } } }, // Stage 4: Sort by total spent (descending) { $sort: { totalSpent: -1 } } ]) // Output: // [ // { _id: "alice@example.com", totalSpent: 1280, orderCount: 4 }, // { _id: "bob@example.com", totalSpent: 380, orderCount: 2 } // ] // AGGREGATION EXAMPLE 2: Product sales report db.orders.aggregate([ { $unwind: "$items" }, { $group: { _id: "$items.product", totalQuantity: { $sum: "$items.quantity" }, totalRevenue: { $sum: { $multiply: ["$items.quantity", "$items.price"] } }, avgPrice: { $avg: "$items.price" } } }, { $sort: { totalRevenue: -1 } }, { $project: { product: "$_id", totalQuantity: 1, totalRevenue: 1, avgPrice: { $round: ["$avgPrice", 2] }, _id: 0 } } ]) // AGGREGATION EXAMPLE 3: Filter, lookup (join), and analyze // Assume we have a customers collection db.customers.insertMany([ { email: "alice@example.com", name: "Alice Johnson", segment: "premium" }, { email: "bob@example.com", name: "Bob Smith", segment: "standard" } ]) db.orders.aggregate([ // Filter: Only delivered orders { $match: { status: "delivered" } }, // Lookup (join) with customers collection { $lookup: { from: "customers", localField: "customer", foreignField: "email", as: "customerInfo" } }, // Unwind the joined array { $unwind: "$customerInfo" }, // Calculate order total { $unwind: "$items" }, { $group: { _id: { orderId: "$orderId", customer: "$customer", segment: "$customerInfo.segment" }, orderTotal: { $sum: { $multiply: ["$items.quantity", "$items.price"] } } } }, // Group by segment { $group: { _id: "$_id.segment", avgOrderValue: { $avg: "$orderTotal" }, orderCount: { $sum: 1 } } } ])

Common Aggregation Stages

Stage Purpose SQL Equivalent
$match Filter documents WHERE
$group Group documents and perform aggregations GROUP BY
$project Select/reshape fields SELECT
$sort Sort documents ORDER BY
$limit Limit number of documents LIMIT
$skip Skip documents (pagination) OFFSET
$unwind Deconstruct array field Unnest/lateral join
$lookup Join with another collection JOIN

Working with MongoDB from Python

# Install pymongo pip install pymongo # Python MongoDB client from pymongo import MongoClient from datetime import datetime # Connect to MongoDB client = MongoClient('mongodb://localhost:27017/') # Access database db = client['socialapp'] # Access collection users = db['users'] # Insert document user = { 'username': 'python_user', 'email': 'python@example.com', 'age': 30, 'interests': ['python', 'data science'], 'createdAt': datetime.utcnow() } result = users.insert_one(user) print(f"Inserted user with ID: {result.inserted_id}") # Insert multiple documents new_users = [ {'username': 'alice', 'email': 'alice@ex.com', 'age': 28}, {'username': 'bob', 'email': 'bob@ex.com', 'age': 32} ] users.insert_many(new_users) # Find documents user = users.find_one({'username': 'python_user'}) print(user) # Find multiple with conditions young_users = users.find({'age': {'$lt': 30}}) for user in young_users: print(user['username'], user['age']) # Update document users.update_one( {'username': 'python_user'}, {'$set': {'age': 31}, '$push': {'interests': 'mongodb'}} ) # Update multiple users.update_many( {'age': {'$gte': 30}}, {'$set': {'verified': True}} ) # Delete document users.delete_one({'username': 'bob'}) # Aggregation from Python pipeline = [ {'$match': {'age': {'$gte': 25}}}, {'$group': { '_id': None, 'avgAge': {'$avg': '$age'}, 'count': {'$sum': 1} }} ] result = list(users.aggregate(pipeline)) print(result) # Create index users.create_index('username', unique=True) users.create_index([('age', 1), ('location', -1)]) # Close connection client.close()

Redis: Complete Guide

Redis is an in-memory data store that's blazingly fast. It's used for caching, session storage, real-time analytics, message queues, and more. Think of it as a sophisticated key-value store on steroids.

Installing and Running Redis

# Install Redis (macOS with Homebrew) brew install redis # Start Redis server redis-server # Or start as background service brew services start redis # Connect to Redis CLI redis-cli # For Ubuntu/Debian sudo apt-get install redis-server sudo systemctl start redis # For Windows, use WSL or download from redis.io

Redis Data Types

Redis supports multiple data structures, each optimized for different use cases.

# STRING - Simple key-value pairs SET user:1000:name "Alice Johnson" GET user:1000:name # Returns: "Alice Johnson" # Set with expiration (TTL) SET session:abc123 "user_data" EX 3600 # Expires in 3600 seconds (1 hour) # Increment/decrement (atomic operations) SET page:views 100 INCR page:views # 101 INCRBY page:views 10 # 111 DECR page:views # 110 # Multiple operations MSET user:1:name "Alice" user:1:email "alice@example.com" user:1:age "28" MGET user:1:name user:1:email user:1:age # Returns: ["Alice", "alice@example.com", "28"] # Check if key exists EXISTS user:1:name # Returns 1 (true) or 0 (false) # Delete key DEL user:1:name # Set expiration on existing key EXPIRE user:1:email 3600 # Check time to live TTL user:1:email # LIST - Ordered collections (like arrays) # Push to list LPUSH tasks "Write documentation" # Push to left (beginning) RPUSH tasks "Review code" # Push to right (end) LPUSH tasks "Fix bug #123" # Get list range LRANGE tasks 0 -1 # Get all items (0 to end) # Returns: ["Fix bug #123", "Write documentation", "Review code"] # List length LLEN tasks # Returns: 3 # Pop from list LPOP tasks # Removes and returns "Fix bug #123" RPOP tasks # Removes and returns "Review code" # Use case: Queue system RPUSH queue:emails "email1@example.com" RPUSH queue:emails "email2@example.com" LPOP queue:emails # Process oldest email (FIFO) # Use case: Recent activity feed LPUSH user:1000:activity "Logged in" LPUSH user:1000:activity "Updated profile" LPUSH user:1000:activity "Posted comment" LRANGE user:1000:activity 0 9 # Get 10 most recent activities # SET - Unordered unique collections SADD tags:post:1 "python" "redis" "tutorial" SADD tags:post:2 "python" "django" "web" # Check membership SISMEMBER tags:post:1 "python" # Returns 1 (true) # Get all members SMEMBERS tags:post:1 # Returns: ["python", "redis", "tutorial"] # Set operations SINTER tags:post:1 tags:post:2 # Intersection (common tags) # Returns: ["python"] SUNION tags:post:1 tags:post:2 # Union (all unique tags) # Returns: ["python", "redis", "tutorial", "django", "web"] SDIFF tags:post:1 tags:post:2 # Difference (in post:1 but not post:2) # Returns: ["redis", "tutorial"] # Use case: Track unique visitors SADD visitors:2026-01-04 "user:1000" SADD visitors:2026-01-04 "user:1001" SADD visitors:2026-01-04 "user:1000" # Duplicate, won't be added SCARD visitors:2026-01-04 # Count unique visitors: 2 # SORTED SET - Ordered by score ZADD leaderboard 1500 "alice" # score 1500 ZADD leaderboard 2200 "bob" # score 2200 ZADD leaderboard 1800 "charlie" # score 1800 # Get range by rank (position) ZRANGE leaderboard 0 -1 WITHSCORES # Returns: ["alice", "1500", "charlie", "1800", "bob", "2200"] # Get top 3 players (reverse order) ZREVRANGE leaderboard 0 2 WITHSCORES # Returns: ["bob", "2200", "charlie", "1800", "alice", "1500"] # Get rank of member ZRANK leaderboard "alice" # Returns: 0 (lowest score = rank 0) ZREVRANK leaderboard "alice" # Returns: 2 (in descending order) # Increment score ZINCRBY leaderboard 100 "alice" # Alice's score now 1600 # Get score ZSCORE leaderboard "alice" # Returns: "1600" # Use case: Trending posts (sort by engagement score) ZADD trending 150 "post:1001" ZADD trending 340 "post:1002" ZADD trending 89 "post:1003" ZREVRANGE trending 0 9 # Top 10 trending posts # HASH - Field-value pairs (like objects/dictionaries) HSET user:1000 name "Alice Johnson" HSET user:1000 email "alice@example.com" HSET user:1000 age "28" # Set multiple fields HMSET user:1001 name "Bob Smith" email "bob@example.com" age "32" # Get field HGET user:1000 name # Returns: "Alice Johnson" # Get all fields HGETALL user:1000 # Returns: ["name", "Alice Johnson", "email", "alice@example.com", "age", "28"] # Get multiple fields HMGET user:1000 name email # Returns: ["Alice Johnson", "alice@example.com"] # Increment numeric field HINCRBY user:1000 loginCount 1 # Check if field exists HEXISTS user:1000 name # Returns 1 # Delete field HDEL user:1000 age # Use case: Store user session data HMSET session:xyz123 userId "1000" loginTime "2026-01-04T10:30:00Z" ipAddress "192.168.1.1" EXPIRE session:xyz123 3600 # Session expires in 1 hour

Redis Use Case: Caching

The most common use of Redis is caching expensive database queries or API calls.

# Python caching example with Redis import redis import json import time from functools import wraps # Connect to Redis r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) def cache_result(expiration=300): """Decorator to cache function results in Redis""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): # Create cache key from function name and arguments cache_key = f"{func.__name__}:{str(args)}:{str(kwargs)}" # Check if result is in cache cached_result = r.get(cache_key) if cached_result: print(f"Cache HIT for {cache_key}") return json.loads(cached_result) # Cache miss - execute function print(f"Cache MISS for {cache_key}") result = func(*args, **kwargs) # Store in cache with expiration r.setex(cache_key, expiration, json.dumps(result)) return result return wrapper return decorator @cache_result(expiration=600) # Cache for 10 minutes def get_user_profile(user_id): """Simulate expensive database query""" print(f"Fetching user {user_id} from database...") time.sleep(2) # Simulate slow query return { 'id': user_id, 'name': 'Alice Johnson', 'email': 'alice@example.com' } # First call - cache miss (slow) profile = get_user_profile(1000) # Takes 2 seconds print(profile) # Second call - cache hit (instant) profile = get_user_profile(1000) # Returns immediately from Redis print(profile) # Caching pattern: Look-aside cache def get_product(product_id): cache_key = f"product:{product_id}" # Try cache first product = r.get(cache_key) if product: return json.loads(product) # Cache miss - query database product = db.query(f"SELECT * FROM products WHERE id = {product_id}") # Store in cache r.setex(cache_key, 3600, json.dumps(product)) return product # Cache invalidation (when data changes) def update_product(product_id, data): # Update database db.update(product_id, data) # Invalidate cache r.delete(f"product:{product_id}") # Cache warming (preload cache) def warm_cache(): """Preload popular products into cache""" popular_products = db.query("SELECT * FROM products ORDER BY views DESC LIMIT 100") pipe = r.pipeline() for product in popular_products: cache_key = f"product:{product['id']}" pipe.setex(cache_key, 3600, json.dumps(product)) pipe.execute() print("Cache warmed with 100 popular products")

Redis Pub/Sub (Publish/Subscribe)

Redis can act as a message broker for real-time communication between services.

# Publisher (sends messages) import redis r = redis.Redis(host='localhost', port=6379) # Publish message to channel r.publish('notifications', 'New user registered: alice@example.com') r.publish('notifications', 'New order placed: ORD12345') # Subscriber (receives messages) import redis r = redis.Redis(host='localhost', port=6379, decode_responses=True) # Subscribe to channel pubsub = r.pubsub() pubsub.subscribe('notifications') print("Listening for messages on 'notifications' channel...") for message in pubsub.listen(): if message['type'] == 'message': print(f"Received: {message['data']}") # Real-world example: Real-time chat application # User sends message -> Published to channel -> All subscribers receive it # Chat server class ChatRoom: def __init__(self, room_name): self.room_name = room_name self.redis = redis.Redis(decode_responses=True) self.pubsub = self.redis.pubsub() self.pubsub.subscribe(f"chat:{room_name}") def send_message(self, username, message): """Send message to chat room""" data = json.dumps({ 'username': username, 'message': message, 'timestamp': time.time() }) self.redis.publish(f"chat:{self.room_name}", data) def listen(self): """Listen for messages""" for message in self.pubsub.listen(): if message['type'] == 'message': data = json.loads(message['data']) print(f"[{data['username']}]: {data['message']}") # Usage room = ChatRoom('general') room.send_message('Alice', 'Hello everyone!') room.listen() # Start listening for messages

Redis Persistence

Redis is in-memory, but it can persist data to disk to survive restarts.

Two Persistence Options

  • RDB (Redis Database Backup): Periodic snapshots of the dataset. Fast, compact, but you can lose data between snapshots. Configure with SAVE directives in redis.conf.
  • AOF (Append-Only File): Logs every write operation. More durable (can recover almost all data), but slower and larger files. Enable with appendonly yes in redis.conf.
  • Hybrid: Use both RDB + AOF for best balance of speed and durability.

When to Use NoSQL vs SQL

This is the million-dollar question. Here's a decision framework based on real-world constraints.

Factor Use SQL Use NoSQL
Data Structure Structured, relational data with defined schema Unstructured, semi-structured, or rapidly changing schema
Relationships Complex relationships, many JOINs Simple relationships, denormalized data
Transactions Need ACID transactions (banking, inventory) Can tolerate eventual consistency
Scale Vertical scaling (bigger servers) Horizontal scaling (more servers)
Query Pattern Complex ad-hoc queries, analytics Simple queries by key, known access patterns
Speed Consistency more important than speed Speed more important than consistency

Use Case Examples

πŸ“Š Use PostgreSQL

E-commerce platform: Orders, inventory, payments need ACID transactions. Complex queries for reports. Strict data integrity requirements.

πŸ“„ Use MongoDB

Content Management System: Articles, pages, media have varying structures. Nested comments and tags. Flexible schema for different content types.

⚑ Use Redis

Session storage & caching: High-speed access to frequently read data. Real-time leaderboards. Rate limiting. Message queues.

πŸ”„ Use Both (Polyglot Persistence)

Social network: PostgreSQL for user accounts & relationships. MongoDB for posts & activity feeds. Redis for caching & real-time notifications.

MongoDB vs PostgreSQL: Direct Comparison

/* POSTGRESQL: Blog system with relational design */ -- Users table CREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Posts table CREATE TABLE posts ( id SERIAL PRIMARY KEY, user_id INTEGER REFERENCES users(id), title VARCHAR(200) NOT NULL, content TEXT, published_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Tags table CREATE TABLE tags ( id SERIAL PRIMARY KEY, name VARCHAR(50) UNIQUE NOT NULL ); -- Junction table for many-to-many relationship CREATE TABLE post_tags ( post_id INTEGER REFERENCES posts(id), tag_id INTEGER REFERENCES tags(id), PRIMARY KEY (post_id, tag_id) ); -- Comments table CREATE TABLE comments ( id SERIAL PRIMARY KEY, post_id INTEGER REFERENCES posts(id), user_id INTEGER REFERENCES users(id), content TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Query: Get post with author, tags, and comments SELECT p.id, p.title, p.content, u.username as author, ARRAY_AGG(DISTINCT t.name) as tags, JSON_AGG(JSON_BUILD_OBJECT( 'username', cu.username, 'comment', c.content, 'created_at', c.created_at )) as comments FROM posts p JOIN users u ON p.user_id = u.id LEFT JOIN post_tags pt ON p.id = pt.post_id LEFT JOIN tags t ON pt.tag_id = t.id LEFT JOIN comments c ON p.id = c.post_id LEFT JOIN users cu ON c.user_id = cu.id WHERE p.id = 1 GROUP BY p.id, p.title, p.content, u.username;
/* MONGODB: Same blog system with document design */ // Everything in one document (denormalized) db.posts.insertOne({ _id: ObjectId("..."), title: "Introduction to NoSQL", content: "NoSQL databases are...", author: { username: "alice_2026", email: "alice@example.com" }, tags: ["nosql", "mongodb", "databases"], comments: [ { username: "bob_dev", content: "Great article!", createdAt: ISODate("2026-01-04T10:30:00Z") }, { username: "charlie_ml", content: "Very helpful, thanks!", createdAt: ISODate("2026-01-04T11:15:00Z") } ], publishedAt: ISODate("2026-01-03T14:20:00Z"), views: 1523, likes: 87 }) // Query: Get post with everything (single query, no joins!) db.posts.findOne({ _id: ObjectId("...") }) // Query: Find posts by tag db.posts.find({ tags: "mongodb" }) // Query: Find posts with comments from specific user db.posts.find({ "comments.username": "bob_dev" }) // Add comment (array push) db.posts.updateOne( { _id: ObjectId("...") }, { $push: { comments: { username: "diana_new", content: "Excellent explanation!", createdAt: new Date() } }, $inc: { commentCount: 1 } } )

Key Differences in the Example

  • PostgreSQL: Normalized design (5 tables), complex JOIN query, strict relationships, enforced referential integrity
  • MongoDB: Denormalized design (1 collection), simple query with no joins, flexible schema, embedded documents
  • Trade-off: PostgreSQL prevents data duplication but requires complex queries. MongoDB duplicates data (author info in each post) but queries are faster and simpler.

Performance & Scaling Strategies

MongoDB Sharding (Horizontal Scaling)

Sharding distributes data across multiple servers. When your data is too large for one server, MongoDB automatically splits it across shards.

// Sharding architecture // mongos (router) β†’ Config Servers β†’ Shard 1, Shard 2, Shard 3... // Enable sharding on database sh.enableSharding("socialapp") // Shard a collection by shard key sh.shardCollection("socialapp.users", { userId: 1 }) // MongoDB distributes users across shards based on userId // Users 1-1000 β†’ Shard 1 // Users 1001-2000 β†’ Shard 2 // Users 2001-3000 β†’ Shard 3 // Queries route to appropriate shard db.users.find({ userId: 1500 }) // Routes to Shard 2 only // Choose shard key wisely! // Good: High cardinality (many unique values), evenly distributed // Bad: Low cardinality, monotonically increasing (_id), hot spots

MongoDB Replication (High Availability)

// Replica Set: Primary + Secondary nodes // Primary: Handles all writes // Secondaries: Replicate data from Primary, handle reads // Replica Set Configuration rs.initiate({ _id: "myReplicaSet", members: [ { _id: 0, host: "mongodb1.example.com:27017" }, { _id: 1, host: "mongodb2.example.com:27017" }, { _id: 2, host: "mongodb3.example.com:27017" } ] }) // If Primary fails, automatic failover elects new Primary // Write concern: How many nodes must acknowledge write db.users.insertOne( { username: "alice" }, { writeConcern: { w: "majority" } } // Wait for majority of nodes ) // Read preference: Where to read from // primary (default), primaryPreferred, secondary, secondaryPreferred, nearest

Redis Cluster (Scaling Redis)

# Redis Cluster distributes keys across nodes # 16384 hash slots distributed among nodes # Create Redis cluster (6 nodes: 3 masters + 3 replicas) redis-cli --cluster create \ 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 \ 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 \ --cluster-replicas 1 # Redis automatically assigns hash slots # Node 1: slots 0-5460 # Node 2: slots 5461-10922 # Node 3: slots 10923-16383 # Keys are distributed based on CRC16 hash # Key "user:1000" β†’ hash β†’ slot 9842 β†’ Node 2

Caching Strategies

Strategy How It Works Pros/Cons
Cache-Aside (Lazy Loading) App checks cache first, loads from DB on miss, then caches it βœ… Only caches what's needed
❌ Initial request is slow
Write-Through App writes to cache and DB simultaneously βœ… Cache always up-to-date
❌ Write latency (2 operations)
Write-Behind (Write-Back) App writes to cache, cache writes to DB asynchronously βœ… Fast writes
❌ Risk of data loss if cache fails
Read-Through Cache loads from DB automatically on miss (cache is smart layer) βœ… Simplified app code
❌ Cache must know DB schema

Performance Best Practices

MongoDB Performance Tips

  • Create indexes on fields you query frequently
  • Use compound indexes that match your query patterns
  • Use .explain() to analyze query performance
  • Limit returned fields with projection
  • Use aggregation pipeline instead of client-side processing
  • Denormalize data to avoid lookups (embed when data is read together)
  • Use capped collections for logs and time-series data
  • Monitor with mongostat and mongotop

Redis Performance Tips

  • Use pipelining to send multiple commands in one network round-trip
  • Use Redis transactions (MULTI/EXEC) for atomic operations
  • Set appropriate expiration times on keys (don't let cache grow forever)
  • Use Redis connection pooling in applications
  • Monitor memory usage with INFO memory
  • Use Redis Cluster for horizontal scaling
  • Avoid large keys (split into smaller keys if needed)
  • Use appropriate data structures (don't use SET when HASH would be better)

🏁 The Right Tool for the Job

Databases are like vehicles. PostgreSQL is a reliable truckβ€”it hauls anything, handles complex cargo (relationships), and follows all the rules (ACID). MongoDB is a sports carβ€”fast, flexible, great for specific routes (known access patterns). Redis is a motorcycleβ€”incredibly fast for short trips (caching), but you can't fit much on it. Choose based on your journey, not on what looks coolest.

Putting It All Together: Real-World Architecture

""" Modern web application with polyglot persistence Architecture: - PostgreSQL: User accounts, transactions, critical data - MongoDB: Content (posts, articles, logs) - Redis: Caching, sessions, real-time features """ import psycopg2 import pymongo import redis import json from datetime import datetime class UserService: """Handle user authentication and critical data""" def __init__(self): self.pg = psycopg2.connect("postgresql://localhost/myapp") self.redis = redis.Redis(decode_responses=True) def create_user(self, username, email, password_hash): """Store in PostgreSQL (ACID compliance for user data)""" cursor = self.pg.cursor() cursor.execute( "INSERT INTO users (username, email, password_hash) VALUES (%s, %s, %s) RETURNING id", (username, email, password_hash) ) user_id = cursor.fetchone()[0] self.pg.commit() return user_id def get_user(self, user_id): """Check cache first, then database""" cache_key = f"user:{user_id}" # Try cache cached = self.redis.get(cache_key) if cached: return json.loads(cached) # Cache miss - query PostgreSQL cursor = self.pg.cursor() cursor.execute("SELECT id, username, email FROM users WHERE id = %s", (user_id,)) user = cursor.fetchone() if user: user_data = {'id': user[0], 'username': user[1], 'email': user[2]} # Cache for 1 hour self.redis.setex(cache_key, 3600, json.dumps(user_data)) return user_data return None class ContentService: """Handle flexible content with MongoDB""" def __init__(self): self.mongo = pymongo.MongoClient('mongodb://localhost:27017/') self.db = self.mongo['myapp'] self.redis = redis.Redis(decode_responses=True) def create_post(self, user_id, title, content, tags): """Store in MongoDB (flexible schema for content)""" post = { 'userId': user_id, 'title': title, 'content': content, 'tags': tags, 'createdAt': datetime.utcnow(), 'views': 0, 'likes': 0 } result = self.db.posts.insert_one(post) return str(result.inserted_id) def get_post(self, post_id): """MongoDB for content, Redis for view counting""" post = self.db.posts.find_one({'_id': ObjectId(post_id)}) if post: # Increment view count in Redis (fast) self.redis.incr(f"post:{post_id}:views") # Update MongoDB view count periodically (batch) view_count = int(self.redis.get(f"post:{post_id}:views") or 0) if view_count % 10 == 0: # Update DB every 10 views self.db.posts.update_one( {'_id': ObjectId(post_id)}, {'$set': {'views': view_count}} ) return post class RealtimeService: """Handle real-time features with Redis""" def __init__(self): self.redis = redis.Redis(decode_responses=True) def update_leaderboard(self, user_id, score): """Update game leaderboard""" self.redis.zadd('leaderboard:global', {user_id: score}) def get_top_players(self, count=10): """Get top N players""" return self.redis.zrevrange('leaderboard:global', 0, count-1, withscores=True) def publish_notification(self, user_id, message): """Real-time notifications via pub/sub""" self.redis.publish(f'notifications:{user_id}', json.dumps({ 'message': message, 'timestamp': datetime.utcnow().isoformat() })) # Usage user_service = UserService() content_service = ContentService() realtime_service = RealtimeService() # Create user (PostgreSQL) user_id = user_service.create_user('alice_2026', 'alice@example.com', 'hash...') # Create post (MongoDB) post_id = content_service.create_post(user_id, 'My First Post', 'Content...', ['intro', 'hello']) # Update leaderboard (Redis) realtime_service.update_leaderboard(user_id, 1500) # Send real-time notification (Redis pub/sub) realtime_service.publish_notification(user_id, 'Welcome to the platform!')

🎯 Key Takeaways

  • NoSQL complements SQL, doesn't replace it β€” Most modern applications use both
  • MongoDB excels at flexible, document-based data β€” Use for content, catalogs, logs
  • Redis is the ultimate speed demon β€” Use for caching, sessions, real-time features
  • Understand CAP theorem trade-offs β€” You can't have everything; choose wisely
  • Scale horizontally with sharding and replication β€” NoSQL databases are built for distributed systems
  • Cache intelligently β€” Proper caching can make your app 100x faster
  • Use the right tool for each job β€” Polyglot persistence is the modern approach

Python Database Programming

Connect Python applications to databases with confidence. Learn connection pooling, parameterized queries, transaction management, and how to write secure, efficient database code that scales.

SQLite3 Module - Complete Guide

Python's built-in sqlite3 module provides a lightweight disk-based database that doesn't require a separate server process. It's perfect for prototyping, small applications, and embedded systems.

πŸ—ƒοΈ SQLite Advantages

Zero Configuration: No server setup required, database is a single file
Portable: Cross-platform compatibility, easy backup and sharing
Fast: Excellent performance for read-heavy workloads and small to medium datasets
ACID Compliant: Full transaction support with atomic operations
Perfect for: Local storage, testing, embedded systems, desktop applications

Basic Connection and Query

The simplest way to interact with a SQLite database involves connecting, executing queries, and properly closing connections:

import sqlite3 # Connect to database (creates if doesn't exist) conn = sqlite3.connect('example.db') # Create a cursor object to execute SQL cursor = conn.cursor() # Create a table cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, email TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # Insert data cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", ('alice', 'alice@example.com') ) # Commit changes conn.commit() # Query data cursor.execute("SELECT * FROM users") rows = cursor.fetchall() for row in rows: print(row) # Clean up cursor.close() conn.close()
Database as a Filing Cabinet: Think of a database connection as opening a filing cabinet drawer. The cursor is your hand reaching in to file or retrieve documents. Just as you must close the drawer when done, you must close connections to free resources and ensure all changes are saved.

Row Factories - Better Data Access

By default, SQLite returns tuples, which can be confusing. Row factories let you access columns by name:

import sqlite3 conn = sqlite3.connect('example.db') # Use Row factory for dictionary-like access conn.row_factory = sqlite3.Row cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE username = ?", ('alice',)) user = cursor.fetchone() if user: # Access by column name print(f"Username: {user['username']}") print(f"Email: {user['email']}") print(f"Created: {user['created_at']}") # Also works like a tuple print(f"Row data: {tuple(user)}") conn.close()

Custom Row Factory

Create custom objects from database rows for cleaner code:

import sqlite3 from dataclasses import dataclass from typing import Optional @dataclass class User: id: int username: str email: str created_at: str def user_factory(cursor, row): """Convert database row to User object""" fields = [column[0] for column in cursor.description] return User(**{k: v for k, v in zip(fields, row)}) conn = sqlite3.connect('example.db') conn.row_factory = user_factory cursor = conn.cursor() cursor.execute("SELECT * FROM users") users = cursor.fetchall() for user in users: print(f"{user.username} <{user.email}>") # Full IDE autocomplete support! conn.close()

Bulk Operations

Efficiently insert or update multiple records at once:

import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() # executemany() for bulk inserts users_data = [ ('bob', 'bob@example.com'), ('charlie', 'charlie@example.com'), ('diana', 'diana@example.com'), ('eve', 'eve@example.com'), ] cursor.executemany( "INSERT INTO users (username, email) VALUES (?, ?)", users_data ) conn.commit() print(f"Inserted {cursor.rowcount} rows") # Bulk update cursor.executemany( "UPDATE users SET email = ? WHERE username = ?", [ ('newemail@example.com', 'bob'), ('updated@example.com', 'charlie'), ] ) conn.commit() conn.close()

Fetching Data Efficiently

Different methods for retrieving query results:

import sqlite3 conn = sqlite3.connect('example.db') conn.row_factory = sqlite3.Row cursor = conn.cursor() # fetchone() - Get single row cursor.execute("SELECT * FROM users WHERE id = ?", (1,)) user = cursor.fetchone() print(user['username'] if user else "Not found") # fetchall() - Get all rows (loads into memory) cursor.execute("SELECT * FROM users") all_users = cursor.fetchall() print(f"Total users: {len(all_users)}") # fetchmany() - Get specific number of rows cursor.execute("SELECT * FROM users") batch = cursor.fetchmany(5) print(f"First batch: {len(batch)} users") # Iterate cursor directly (memory efficient) cursor.execute("SELECT * FROM users") for row in cursor: print(f"Processing: {row['username']}") conn.close()

Database Connection Patterns

Proper connection management prevents resource leaks and ensures data integrity. Context managers automate cleanup even when errors occur.

Context Manager Pattern

The best practice for managing database connections:

import sqlite3 from contextlib import contextmanager # Using built-in context manager def save_user(username, email): with sqlite3.connect('example.db') as conn: cursor = conn.cursor() cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) # Automatic commit on success # Automatic rollback on exception # Connection automatically closed # Custom context manager for more control @contextmanager def get_db_cursor(db_path): """Context manager that yields a cursor""" conn = sqlite3.connect(db_path) conn.row_factory = sqlite3.Row cursor = conn.cursor() try: yield cursor conn.commit() except Exception: conn.rollback() raise finally: cursor.close() conn.close() # Usage with get_db_cursor('example.db') as cursor: cursor.execute("SELECT * FROM users") users = cursor.fetchall() for user in users: print(user['username'])

Connection Pooling

Reuse connections to avoid overhead of creating new connections. Critical for high-performance applications:

import sqlite3 import threading from queue import Queue, Empty from contextlib import contextmanager class SQLitePool: """Simple connection pool for SQLite""" def __init__(self, database, pool_size=5): self.database = database self.pool_size = pool_size self.pool = Queue(maxsize=pool_size) self._local = threading.local() # Pre-create connections for _ in range(pool_size): conn = sqlite3.connect(database, check_same_thread=False) conn.row_factory = sqlite3.Row self.pool.put(conn) @contextmanager def get_connection(self): """Get connection from pool""" conn = None try: conn = self.pool.get(timeout=5) yield conn finally: if conn: self.pool.put(conn) def close_all(self): """Close all connections in pool""" while not self.pool.empty(): try: conn = self.pool.get_nowait() conn.close() except Empty: break # Usage pool = SQLitePool('example.db', pool_size=10) def query_users(): with pool.get_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users LIMIT 10") return cursor.fetchall() # Multiple threads can share the pool users = query_users() # Cleanup when done pool.close_all()

Thread-Safe Connections

SQLite connections are not thread-safe by default. Use one connection per thread or proper locking:

import sqlite3 import threading class ThreadSafeDB: """Thread-local database connections""" def __init__(self, database): self.database = database self._local = threading.local() def get_connection(self): """Get thread-local connection""" if not hasattr(self._local, 'conn'): self._local.conn = sqlite3.connect(self.database) self._local.conn.row_factory = sqlite3.Row return self._local.conn def close(self): """Close thread-local connection""" if hasattr(self._local, 'conn'): self._local.conn.close() del self._local.conn # Global instance db = ThreadSafeDB('example.db') def worker_task(user_id): """Each thread gets its own connection""" conn = db.get_connection() cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) user = cursor.fetchone() print(f"Thread {threading.current_thread().name}: {user['username']}") # Spawn multiple threads threads = [] for i in range(1, 6): t = threading.Thread(target=worker_task, args=(i,)) threads.append(t) t.start() for t in threads: t.join()

Parameterized Queries - SQL Injection Prevention

Never use string formatting to build SQL queries. Parameterized queries prevent SQL injection attacks and handle escaping automatically.

⚠️ Security Critical

Never do this: cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
Always do this: cursor.execute("SELECT * FROM users WHERE username = ?", (username,))

SQL injection is one of the most common and dangerous vulnerabilities. An attacker could pass ' OR '1'='1 to bypass authentication or '; DROP TABLE users; -- to delete data.

Proper Parameterization

import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() # βœ… SAFE: Using placeholders username = input("Enter username: ") cursor.execute("SELECT * FROM users WHERE username = ?", (username,)) # βœ… SAFE: Multiple parameters email = input("Enter email: ") cursor.execute( "SELECT * FROM users WHERE username = ? AND email = ?", (username, email) ) # βœ… SAFE: Named parameters (more readable) cursor.execute( "SELECT * FROM users WHERE username = :user AND email = :email", {'user': username, 'email': email} ) # ❌ UNSAFE: String formatting # cursor.execute(f"SELECT * FROM users WHERE username = '{username}'") # This allows SQL injection attacks! # ❌ UNSAFE: String concatenation # query = "SELECT * FROM users WHERE username = '" + username + "'" # cursor.execute(query) conn.close()

Complex Query Parameterization

import sqlite3 def search_users(conn, filters): """Dynamic query building with parameters""" query = "SELECT * FROM users WHERE 1=1" params = [] if filters.get('username'): query += " AND username LIKE ?" params.append(f"%{filters['username']}%") if filters.get('email_domain'): query += " AND email LIKE ?" params.append(f"%@{filters['email_domain']}") if filters.get('created_after'): query += " AND created_at > ?" params.append(filters['created_after']) cursor = conn.cursor() cursor.execute(query, params) return cursor.fetchall() # Usage conn = sqlite3.connect('example.db') conn.row_factory = sqlite3.Row results = search_users(conn, { 'username': 'alice', 'email_domain': 'example.com', 'created_after': '2024-01-01' }) for user in results: print(f"{user['username']}: {user['email']}") conn.close()

IN Clause with Parameters

import sqlite3 def get_users_by_ids(conn, user_ids): """Safe handling of IN clause""" if not user_ids: return [] # Create placeholders: (?, ?, ?) placeholders = ', '.join('?' * len(user_ids)) query = f"SELECT * FROM users WHERE id IN ({placeholders})" cursor = conn.cursor() cursor.execute(query, user_ids) return cursor.fetchall() conn = sqlite3.connect('example.db') conn.row_factory = sqlite3.Row # Get multiple users by ID user_ids = [1, 3, 5, 7] users = get_users_by_ids(conn, user_ids) for user in users: print(f"ID {user['id']}: {user['username']}") conn.close()

Transaction Management

Transactions ensure data consistency by grouping operations into atomic units. Either all operations succeed, or none do.

Transactions as Bank Transfers: When transferring money between accounts, you must debit one account and credit another. Both operations must succeed togetherβ€”if one fails, the other must be undone. This is exactly what transactions do: they ensure all-or-nothing execution.

Manual Transaction Control

import sqlite3 def transfer_funds(from_user_id, to_user_id, amount): """Transfer funds between users (example)""" conn = sqlite3.connect('bank.db') cursor = conn.cursor() try: # Start transaction (implicit after first execute) # Deduct from sender cursor.execute( "UPDATE accounts SET balance = balance - ? WHERE user_id = ?", (amount, from_user_id) ) # Verify sender has sufficient balance cursor.execute( "SELECT balance FROM accounts WHERE user_id = ?", (from_user_id,) ) balance = cursor.fetchone()[0] if balance < 0: raise ValueError("Insufficient funds") # Add to receiver cursor.execute( "UPDATE accounts SET balance = balance + ? WHERE user_id = ?", (amount, to_user_id) ) # Commit transaction conn.commit() print(f"Transferred ${amount} from user {from_user_id} to {to_user_id}") except Exception as e: # Rollback on any error conn.rollback() print(f"Transfer failed: {e}") raise finally: conn.close() # Usage transfer_funds(1, 2, 100.00)

Transaction Isolation Levels

import sqlite3 # SQLite isolation levels conn = sqlite3.connect('example.db', isolation_level='DEFERRED') # Options: None (autocommit), 'DEFERRED', 'IMMEDIATE', 'EXCLUSIVE' # DEFERRED (default): Lock acquired on first write # IMMEDIATE: Lock acquired at BEGIN # EXCLUSIVE: Lock acquired at BEGIN, no other connections can read/write def demo_isolation_levels(): # Autocommit mode (isolation_level=None) conn = sqlite3.connect('example.db', isolation_level=None) cursor = conn.cursor() cursor.execute("INSERT INTO users (username, email) VALUES ('test', 'test@example.com')") # Committed immediately, no need to call commit() conn.close() # IMMEDIATE transaction conn = sqlite3.connect('example.db', isolation_level='IMMEDIATE') cursor = conn.cursor() cursor.execute("BEGIN IMMEDIATE") cursor.execute("UPDATE users SET email = 'new@example.com' WHERE username = 'test'") # Hold lock until commit conn.commit() conn.close() demo_isolation_levels()

Savepoints for Nested Transactions

import sqlite3 def complex_operation_with_savepoints(): """Use savepoints for partial rollbacks""" conn = sqlite3.connect('example.db') cursor = conn.cursor() try: # Begin transaction cursor.execute("INSERT INTO users (username, email) VALUES ('user1', 'user1@example.com')") # Create savepoint cursor.execute("SAVEPOINT sp1") try: cursor.execute("INSERT INTO users (username, email) VALUES ('user2', 'user2@example.com')") cursor.execute("INSERT INTO users (username, email) VALUES ('invalid', NULL)") # Fails except sqlite3.IntegrityError: # Rollback to savepoint (user2 insert undone, user1 remains) cursor.execute("ROLLBACK TO SAVEPOINT sp1") print("Rolled back to savepoint") # Release savepoint (commits savepoint) cursor.execute("RELEASE SAVEPOINT sp1") # Commit main transaction conn.commit() print("Transaction committed") except Exception as e: conn.rollback() print(f"Full rollback: {e}") finally: conn.close() complex_operation_with_savepoints()

Transaction Context Manager

import sqlite3 from contextlib import contextmanager @contextmanager def transaction(conn): """Context manager for transactions with proper error handling""" cursor = conn.cursor() try: yield cursor conn.commit() except Exception: conn.rollback() raise def batch_insert_users(users_data): """Insert multiple users in a single transaction""" conn = sqlite3.connect('example.db') with transaction(conn) as cursor: for username, email in users_data: cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) # Auto-commit if no errors, auto-rollback on exception conn.close() # Usage users = [ ('alice', 'alice@example.com'), ('bob', 'bob@example.com'), ('charlie', 'charlie@example.com'), ] try: batch_insert_users(users) print("All users inserted successfully") except sqlite3.IntegrityError as e: print(f"Insert failed, all rolled back: {e}")

Error Handling

Robust error handling prevents data corruption and provides meaningful feedback when operations fail.

SQLite Exception Hierarchy

import sqlite3 """ sqlite3.Error (base class) β”œβ”€β”€ sqlite3.DatabaseError β”‚ β”œβ”€β”€ sqlite3.IntegrityError (constraint violations) β”‚ β”œβ”€β”€ sqlite3.ProgrammingError (SQL syntax errors) β”‚ β”œβ”€β”€ sqlite3.OperationalError (database locked, etc) β”‚ └── sqlite3.NotSupportedError β”œβ”€β”€ sqlite3.DataError (data processing issues) └── sqlite3.InterfaceError (interface errors) """ def demonstrate_error_handling(): conn = sqlite3.connect('example.db') cursor = conn.cursor() try: # This will fail if username already exists (UNIQUE constraint) cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", ('alice', 'alice@example.com') ) conn.commit() except sqlite3.IntegrityError as e: print(f"Integrity constraint violated: {e}") # Handle duplicate entry except sqlite3.OperationalError as e: print(f"Operational error (database locked?): {e}") # Retry logic here except sqlite3.ProgrammingError as e: print(f"Programming error (SQL syntax?): {e}") # Fix the SQL query except sqlite3.Error as e: print(f"General database error: {e}") conn.rollback() finally: conn.close() demonstrate_error_handling()

Retry Logic for Locked Database

import sqlite3 import time from functools import wraps def retry_on_locked(max_retries=3, delay=0.1): """Decorator to retry on database locked errors""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): for attempt in range(max_retries): try: return func(*args, **kwargs) except sqlite3.OperationalError as e: if 'locked' in str(e).lower() and attempt < max_retries - 1: time.sleep(delay * (2 ** attempt)) # Exponential backoff continue raise return None return wrapper return decorator @retry_on_locked(max_retries=5, delay=0.2) def insert_user_with_retry(username, email): """Insert user with automatic retry on lock""" conn = sqlite3.connect('example.db', timeout=10.0) try: cursor = conn.cursor() cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) conn.commit() return cursor.lastrowid finally: conn.close() # Usage try: user_id = insert_user_with_retry('newuser', 'new@example.com') print(f"Inserted user with ID: {user_id}") except sqlite3.OperationalError as e: print(f"Failed after retries: {e}")

Comprehensive Error Handling Pattern

import sqlite3 import logging from typing import Optional, List logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class DatabaseError(Exception): """Custom database exception""" pass class UserRepository: """Database access layer with comprehensive error handling""" def __init__(self, db_path: str): self.db_path = db_path def _get_connection(self): """Get database connection with error handling""" try: conn = sqlite3.connect(self.db_path, timeout=10.0) conn.row_factory = sqlite3.Row return conn except sqlite3.Error as e: logger.error(f"Failed to connect to database: {e}") raise DatabaseError(f"Database connection failed: {e}") def create_user(self, username: str, email: str) -> Optional[int]: """Create user with comprehensive error handling""" conn = None try: conn = self._get_connection() cursor = conn.cursor() cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) conn.commit() user_id = cursor.lastrowid logger.info(f"Created user: {username} (ID: {user_id})") return user_id except sqlite3.IntegrityError as e: logger.warning(f"User already exists: {username}") if conn: conn.rollback() return None except sqlite3.OperationalError as e: logger.error(f"Database operation failed: {e}") if conn: conn.rollback() raise DatabaseError(f"Failed to create user: {e}") except Exception as e: logger.exception(f"Unexpected error creating user: {e}") if conn: conn.rollback() raise finally: if conn: conn.close() def get_user(self, username: str) -> Optional[dict]: """Get user by username""" conn = None try: conn = self._get_connection() cursor = conn.cursor() cursor.execute( "SELECT * FROM users WHERE username = ?", (username,) ) row = cursor.fetchone() return dict(row) if row else None except sqlite3.Error as e: logger.error(f"Failed to fetch user {username}: {e}") return None finally: if conn: conn.close() # Usage repo = UserRepository('example.db') user_id = repo.create_user('alice', 'alice@example.com') if user_id: user = repo.get_user('alice') print(f"User: {user}")

Async Database Access

Asynchronous database operations prevent blocking in async applications. Use aiosqlite for SQLite or asyncpg for PostgreSQL.

Installing Async Database Libraries

# For SQLite pip install aiosqlite # For PostgreSQL pip install asyncpg # For MySQL pip install aiomysql

aiosqlite - Async SQLite

import asyncio import aiosqlite async def create_user_async(username: str, email: str): """Async user creation""" async with aiosqlite.connect('example.db') as conn: await conn.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) await conn.commit() print(f"Created user: {username}") async def get_all_users_async(): """Async query with proper cursor handling""" async with aiosqlite.connect('example.db') as conn: # Set row factory for dict-like access conn.row_factory = aiosqlite.Row async with conn.execute("SELECT * FROM users") as cursor: async for row in cursor: print(f"User: {row['username']} <{row['email']}>") async def bulk_operations_async(): """Async bulk operations""" async with aiosqlite.connect('example.db') as conn: users_data = [ ('user1', 'user1@example.com'), ('user2', 'user2@example.com'), ('user3', 'user3@example.com'), ] await conn.executemany( "INSERT INTO users (username, email) VALUES (?, ?)", users_data ) await conn.commit() # Run async functions async def main(): await create_user_async('async_user', 'async@example.com') await get_all_users_async() await bulk_operations_async() # Execute asyncio.run(main())

Async Connection Pool

import asyncio import aiosqlite from contextlib import asynccontextmanager class AsyncSQLitePool: """Simple async connection pool for SQLite""" def __init__(self, database: str, pool_size: int = 5): self.database = database self.pool_size = pool_size self._pool = asyncio.Queue(maxsize=pool_size) self._initialized = False async def initialize(self): """Initialize connection pool""" if self._initialized: return for _ in range(self.pool_size): conn = await aiosqlite.connect(self.database) conn.row_factory = aiosqlite.Row await self._pool.put(conn) self._initialized = True @asynccontextmanager async def acquire(self): """Acquire connection from pool""" if not self._initialized: await self.initialize() conn = await self._pool.get() try: yield conn finally: await self._pool.put(conn) async def close(self): """Close all connections""" while not self._pool.empty(): conn = await self._pool.get() await conn.close() # Usage pool = AsyncSQLitePool('example.db', pool_size=10) async def query_with_pool(user_id: int): async with pool.acquire() as conn: async with conn.execute( "SELECT * FROM users WHERE id = ?", (user_id,) ) as cursor: row = await cursor.fetchone() return dict(row) if row else None async def main(): # Run multiple concurrent queries tasks = [query_with_pool(i) for i in range(1, 11)] results = await asyncio.gather(*tasks) for user in results: if user: print(f"User: {user['username']}") await pool.close() asyncio.run(main())

asyncpg - High-Performance PostgreSQL

import asyncio import asyncpg async def create_pool(): """Create PostgreSQL connection pool""" return await asyncpg.create_pool( host='localhost', port=5432, user='postgres', password='password', database='mydb', min_size=10, max_size=20, command_timeout=60 ) async def insert_user(pool, username: str, email: str): """Insert user using connection pool""" async with pool.acquire() as conn: user_id = await conn.fetchval( "INSERT INTO users (username, email) VALUES ($1, $2) RETURNING id", username, email ) return user_id async def get_users(pool): """Fetch multiple users""" async with pool.acquire() as conn: rows = await conn.fetch("SELECT * FROM users LIMIT 10") return [dict(row) for row in rows] async def transaction_example(pool): """Transaction with asyncpg""" async with pool.acquire() as conn: async with conn.transaction(): # Multiple operations in transaction await conn.execute( "UPDATE accounts SET balance = balance - $1 WHERE user_id = $2", 100, 1 ) await conn.execute( "UPDATE accounts SET balance = balance + $1 WHERE user_id = $2", 100, 2 ) # Auto-commit on success, auto-rollback on exception async def main(): pool = await create_pool() try: # Insert user user_id = await insert_user(pool, 'async_user', 'async@example.com') print(f"Created user ID: {user_id}") # Fetch users users = await get_users(pool) for user in users: print(f"User: {user['username']}") # Transaction await transaction_example(pool) finally: await pool.close() asyncio.run(main())

Async Error Handling

import asyncio import aiosqlite import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class AsyncDatabaseError(Exception): """Async database exception""" pass async def safe_database_operation(operation_name: str, operation_func): """Wrapper for safe async database operations""" max_retries = 3 retry_delay = 0.5 for attempt in range(max_retries): try: return await operation_func() except aiosqlite.IntegrityError as e: logger.warning(f"{operation_name}: Integrity error: {e}") raise # Don't retry integrity errors except aiosqlite.OperationalError as e: if 'locked' in str(e).lower() and attempt < max_retries - 1: logger.warning(f"{operation_name}: Database locked, retrying...") await asyncio.sleep(retry_delay * (2 ** attempt)) continue logger.error(f"{operation_name}: Operational error: {e}") raise AsyncDatabaseError(f"Database operation failed: {e}") except Exception as e: logger.exception(f"{operation_name}: Unexpected error: {e}") raise raise AsyncDatabaseError(f"{operation_name}: Max retries exceeded") async def create_user_safe(username: str, email: str): """Create user with comprehensive error handling""" async def _operation(): async with aiosqlite.connect('example.db') as conn: await conn.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) await conn.commit() return await safe_database_operation("create_user", _operation) # Usage async def main(): try: await create_user_safe('safe_user', 'safe@example.com') print("User created successfully") except AsyncDatabaseError as e: print(f"Failed to create user: {e}") asyncio.run(main())

Async Batch Processing

import asyncio import aiosqlite from typing import List, Tuple async def batch_process_users( users_data: List[Tuple[str, str]], batch_size: int = 100 ): """Process large datasets in batches""" async with aiosqlite.connect('example.db') as conn: total_processed = 0 for i in range(0, len(users_data), batch_size): batch = users_data[i:i + batch_size] async with conn.executemany( "INSERT INTO users (username, email) VALUES (?, ?)", batch ): pass await conn.commit() total_processed += len(batch) print(f"Processed {total_processed}/{len(users_data)} users") # Yield control to event loop await asyncio.sleep(0) return total_processed async def concurrent_queries(user_ids: List[int]): """Execute multiple queries concurrently""" async def fetch_user(user_id: int): async with aiosqlite.connect('example.db') as conn: conn.row_factory = aiosqlite.Row async with conn.execute( "SELECT * FROM users WHERE id = ?", (user_id,) ) as cursor: row = await cursor.fetchone() return dict(row) if row else None # Fetch all users concurrently results = await asyncio.gather(*[fetch_user(uid) for uid in user_ids]) return [r for r in results if r is not None] # Usage async def main(): # Generate test data users_data = [ (f'user{i}', f'user{i}@example.com') for i in range(1000) ] # Batch insert count = await batch_process_users(users_data, batch_size=100) print(f"Inserted {count} users") # Concurrent fetch users = await concurrent_queries(list(range(1, 51))) print(f"Fetched {len(users)} users concurrently") asyncio.run(main())

πŸš€ Best Practices Summary

Always use parameterized queries to prevent SQL injection
Use context managers for automatic resource cleanup
Implement proper error handling with specific exception types
Use transactions for operations that must succeed or fail together
Consider connection pooling for high-performance applications
Use async operations in async applications to prevent blocking
Log database operations for debugging and monitoring
Set appropriate timeouts to prevent indefinite blocking
Test error scenarios including database locks and constraint violations
Use row factories for better data access patterns

Complete Example - User Management System

import sqlite3 import logging from contextlib import contextmanager from typing import Optional, List, Dict from dataclasses import dataclass from datetime import datetime logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @dataclass class User: id: int username: str email: str created_at: str class DatabaseManager: """Complete database management with best practices""" def __init__(self, db_path: str = 'users.db'): self.db_path = db_path self._initialize_database() def _initialize_database(self): """Create tables if they don't exist""" with self._get_connection() as conn: cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL UNIQUE, email TEXT NOT NULL UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') cursor.execute(''' CREATE INDEX IF NOT EXISTS idx_username ON users(username) ''') conn.commit() @contextmanager def _get_connection(self): """Context manager for database connections""" conn = sqlite3.connect(self.db_path, timeout=10.0) conn.row_factory = sqlite3.Row try: yield conn except Exception: conn.rollback() raise finally: conn.close() def create_user(self, username: str, email: str) -> Optional[User]: """Create a new user""" try: with self._get_connection() as conn: cursor = conn.cursor() cursor.execute( "INSERT INTO users (username, email) VALUES (?, ?)", (username, email) ) conn.commit() user_id = cursor.lastrowid logger.info(f"Created user: {username} (ID: {user_id})") return self.get_user_by_id(user_id) except sqlite3.IntegrityError as e: logger.warning(f"User creation failed: {e}") return None def get_user_by_id(self, user_id: int) -> Optional[User]: """Get user by ID""" with self._get_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) row = cursor.fetchone() if row: return User(**dict(row)) return None def get_user_by_username(self, username: str) -> Optional[User]: """Get user by username""" with self._get_connection() as conn: cursor = conn.cursor() cursor.execute( "SELECT * FROM users WHERE username = ?", (username,) ) row = cursor.fetchone() if row: return User(**dict(row)) return None def get_all_users(self, limit: int = 100) -> List[User]: """Get all users with limit""" with self._get_connection() as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM users LIMIT ?", (limit,)) rows = cursor.fetchall() return [User(**dict(row)) for row in rows] def update_user_email(self, user_id: int, new_email: str) -> bool: """Update user email""" try: with self._get_connection() as conn: cursor = conn.cursor() cursor.execute( "UPDATE users SET email = ? WHERE id = ?", (new_email, user_id) ) conn.commit() if cursor.rowcount > 0: logger.info(f"Updated email for user ID {user_id}") return True return False except sqlite3.IntegrityError: logger.warning(f"Email {new_email} already exists") return False def delete_user(self, user_id: int) -> bool: """Delete user by ID""" with self._get_connection() as conn: cursor = conn.cursor() cursor.execute("DELETE FROM users WHERE id = ?", (user_id,)) conn.commit() if cursor.rowcount > 0: logger.info(f"Deleted user ID {user_id}") return True return False def search_users(self, query: str) -> List[User]: """Search users by username or email""" with self._get_connection() as conn: cursor = conn.cursor() search_pattern = f"%{query}%" cursor.execute( """SELECT * FROM users WHERE username LIKE ? OR email LIKE ? LIMIT 50""", (search_pattern, search_pattern) ) rows = cursor.fetchall() return [User(**dict(row)) for row in rows] # Usage example def main(): db = DatabaseManager('users.db') # Create users user1 = db.create_user('alice', 'alice@example.com') user2 = db.create_user('bob', 'bob@example.com') if user1: print(f"Created: {user1.username}") # Get user alice = db.get_user_by_username('alice') if alice: print(f"Found: {alice.username} <{alice.email}>") # Update email if user1: success = db.update_user_email(user1.id, 'newalice@example.com') print(f"Email updated: {success}") # Search users results = db.search_users('alice') print(f"Search results: {len(results)}") # Get all users all_users = db.get_all_users() for user in all_users: print(f"User: {user.username} <{user.email}>") if __name__ == '__main__': main()

SQLAlchemy ORM

Object-Relational Mapping bridges the gap between Python objects and database tables. SQLAlchemy is Python's most powerful ORMβ€”learn to define models, relationships, and write database-agnostic code that's both elegant and performant.

Understanding SQLAlchemy: Core vs ORM

SQLAlchemy is a comprehensive database toolkit for Python with two distinct layers. SQLAlchemy Core provides a low-level SQL abstraction with explicit query building. SQLAlchemy ORM sits on top of Core and provides object-relational mappingβ€”working with Python classes and objects rather than raw SQL.

The Car Metaphor: SQLAlchemy Core is like a manual transmissionβ€”you have complete control over every gear shift (SQL statement). SQLAlchemy ORM is like an automatic transmissionβ€”you focus on driving (business logic) while it handles the gear changes (SQL generation).

SQLAlchemy Core

β€’ Direct SQL expression language
β€’ Maximum control and performance
β€’ Schema definition with Table objects
β€’ Connection pooling and transactions
β€’ Best for complex queries and bulk operations

SQLAlchemy ORM

β€’ Python class-based data modeling
β€’ Automatic SQL generation
β€’ Relationship management
β€’ Unit of Work pattern
β€’ Best for application development

Installation and Setup

Install SQLAlchemy and database drivers. For development, SQLite requires no additional drivers. For production databases, install the appropriate driver.

# Install SQLAlchemy pip install sqlalchemy # Database drivers pip install psycopg2-binary # PostgreSQL pip install pymysql # MySQL pip install cx_Oracle # Oracle # For async support pip install asyncpg # Async PostgreSQL pip install aiomysql # Async MySQL

Database Engine and Connection

The Engine is the starting point for any SQLAlchemy application. It manages database connections and serves as the home base for the connection pool.

from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker # Database URLs follow the pattern: # dialect+driver://username:password@host:port/database # SQLite (file-based) engine = create_engine('sqlite:///blog.db', echo=True) # PostgreSQL engine = create_engine('postgresql://user:pass@localhost/blog') # MySQL engine = create_engine('mysql+pymysql://user:pass@localhost/blog') # Connection pooling configuration engine = create_engine( 'postgresql://user:pass@localhost/blog', pool_size=10, # Number of connections to maintain max_overflow=20, # Additional connections when needed pool_timeout=30, # Seconds to wait for connection pool_recycle=3600, # Recycle connections after 1 hour echo=True # Log all SQL statements ) # Session factory Session = sessionmaker(bind=engine) # Create a session instance session = Session()

Connection String Security

Never hardcode credentials. Use environment variables: os.getenv('DATABASE_URL') or configuration management systems in production.

Declarative Base and Model Definition

SQLAlchemy ORM uses the declarative system to define models as Python classes. Each class represents a database table, and class attributes represent columns.

from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean from sqlalchemy.ext.declarative import declarative_base from datetime import datetime Base = declarative_base() class User(Base): __tablename__ = 'users' # Primary key id = Column(Integer, primary_key=True) # Required fields username = Column(String(50), unique=True, nullable=False) email = Column(String(120), unique=True, nullable=False, index=True) # Optional fields with defaults password_hash = Column(String(255), nullable=False) is_active = Column(Boolean, default=True) is_admin = Column(Boolean, default=False) # Text fields bio = Column(Text, nullable=True) # Timestamps created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) def __repr__(self): return f"<User(username='{self.username}', email='{self.email}')>" def __str__(self): return self.username

Column Types and Constraints

SQLAlchemy provides database-agnostic column types that map to the appropriate native types for each database backend.

SQLAlchemy Type Python Type SQL Equivalent Use Case
Integer int INTEGER IDs, counts, quantities
String(n) str VARCHAR(n) Limited text (usernames, emails)
Text str TEXT Unlimited text (articles, descriptions)
Boolean bool BOOLEAN Flags, status indicators
DateTime datetime DATETIME Timestamps, dates
Float float FLOAT Decimal numbers
Numeric(p,s) Decimal NUMERIC Precise decimals (money)
JSON dict/list JSON Structured data
from sqlalchemy import Numeric, JSON, Enum from decimal import Decimal import enum class OrderStatus(enum.Enum): PENDING = "pending" PAID = "paid" SHIPPED = "shipped" DELIVERED = "delivered" CANCELLED = "cancelled" class Product(Base): __tablename__ = 'products' id = Column(Integer, primary_key=True) name = Column(String(200), nullable=False) description = Column(Text) # Precise decimal for money price = Column(Numeric(10, 2), nullable=False) # Enumeration status = Column(Enum(OrderStatus), default=OrderStatus.PENDING) # JSON for flexible data metadata = Column(JSON) specifications = Column(JSON) # Constraints sku = Column(String(50), unique=True, nullable=False) stock = Column(Integer, default=0) # Check constraint __table_args__ = ( CheckConstraint('price >= 0', name='check_price_positive'), CheckConstraint('stock >= 0', name='check_stock_positive'), ) # Example usage product = Product( name="Gaming Laptop", price=Decimal('1299.99'), metadata={"brand": "TechCorp", "warranty": "2 years"}, specifications={ "cpu": "Intel i7", "ram": "16GB", "storage": "512GB SSD" } )

Relationships: One-to-Many

Relationships define how tables connect. One-to-many is the most commonβ€”one user has many posts, one category has many products.

from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True, nullable=False) email = Column(String(120), unique=True, nullable=False) # Relationship - one user has many posts posts = relationship('Post', back_populates='author', cascade='all, delete-orphan') comments = relationship('Comment', back_populates='user') class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) content = Column(Text, nullable=False) slug = Column(String(200), unique=True, nullable=False) published = Column(Boolean, default=False) created_at = Column(DateTime, default=datetime.utcnow) # Foreign key author_id = Column(Integer, ForeignKey('users.id'), nullable=False) # Relationship - many posts belong to one user author = relationship('User', back_populates='posts') # One post has many comments comments = relationship('Comment', back_populates='post', cascade='all, delete-orphan') class Comment(Base): __tablename__ = 'comments' id = Column(Integer, primary_key=True) content = Column(Text, nullable=False) created_at = Column(DateTime, default=datetime.utcnow) # Foreign keys user_id = Column(Integer, ForeignKey('users.id'), nullable=False) post_id = Column(Integer, ForeignKey('posts.id'), nullable=False) # Relationships user = relationship('User', back_populates='comments') post = relationship('Post', back_populates='comments') # Create all tables Base.metadata.create_all(engine)
The Relationship Pattern: Think of relationships like references in a library. A book (Post) knows its author (User) via the author card (foreign key). The author's profile lists all their books (relationship). When you look up an author, you can see all their books without manually searching the catalog.

Using Relationships

Once relationships are defined, you can navigate between objects naturally using Python attribute access.

from sqlalchemy.orm import Session # Create session session = Session(engine) # Create a user user = User(username='alice', email='alice@example.com') session.add(user) session.commit() # Create posts for that user post1 = Post( title='Getting Started with Python', content='Python is an amazing language...', slug='getting-started-python', author=user # Direct object assignment ) post2 = Post( title='Advanced Python Tips', content='Here are some pro tips...', slug='advanced-python-tips', author_id=user.id # Or use ID directly ) session.add_all([post1, post2]) session.commit() # Access relationships print(f"User: {user.username}") print(f"Number of posts: {len(user.posts)}") for post in user.posts: print(f" - {post.title}") # Reverse relationship post = session.query(Post).first() print(f"Post '{post.title}' by {post.author.username}") # Add a comment comment = Comment( content='Great article!', user=user, post=post1 ) session.add(comment) session.commit() # Cascade delete - deleting user deletes their posts session.delete(user) session.commit() # All user's posts and comments are deleted

Many-to-Many Relationships

Many-to-many requires an association table. A post can have many tags, and a tag can be on many posts.

from sqlalchemy import Table # Association table for many-to-many post_tags = Table('post_tags', Base.metadata, Column('post_id', Integer, ForeignKey('posts.id'), primary_key=True), Column('tag_id', Integer, ForeignKey('tags.id'), primary_key=True) ) class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) content = Column(Text, nullable=False) # Many-to-many relationship tags = relationship('Tag', secondary=post_tags, back_populates='posts') class Tag(Base): __tablename__ = 'tags' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True, nullable=False) slug = Column(String(50), unique=True, nullable=False) # Many-to-many relationship posts = relationship('Post', secondary=post_tags, back_populates='tags') # Usage python_tag = Tag(name='Python', slug='python') tutorial_tag = Tag(name='Tutorial', slug='tutorial') post = Post( title='Python Tutorial', content='Learn Python...', tags=[python_tag, tutorial_tag] ) session.add(post) session.commit() # Query posts by tag python_posts = session.query(Post).join(Post.tags).filter(Tag.slug == 'python').all() # Query tags by post post_tags = post.tags for tag in post_tags: print(tag.name)

Many-to-Many with Extra Data

When the association itself needs data (timestamps, order, status), use an association object instead of a simple table.

class Enrollment(Base): __tablename__ = 'enrollments' # Composite primary key student_id = Column(Integer, ForeignKey('students.id'), primary_key=True) course_id = Column(Integer, ForeignKey('courses.id'), primary_key=True) # Extra data on the association enrolled_date = Column(DateTime, default=datetime.utcnow) grade = Column(String(2)) completed = Column(Boolean, default=False) # Relationships student = relationship('Student', back_populates='enrollments') course = relationship('Course', back_populates='enrollments') class Student(Base): __tablename__ = 'students' id = Column(Integer, primary_key=True) name = Column(String(100), nullable=False) email = Column(String(120), unique=True, nullable=False) # Relationship to association object enrollments = relationship('Enrollment', back_populates='student') # Direct access to courses via association_proxy (requires import) # from sqlalchemy.ext.associationproxy import association_proxy # courses = association_proxy('enrollments', 'course') class Course(Base): __tablename__ = 'courses' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) code = Column(String(20), unique=True, nullable=False) enrollments = relationship('Enrollment', back_populates='course') # Usage student = Student(name='Bob', email='bob@example.com') course = Course(title='Database Systems', code='CS301') # Create enrollment with extra data enrollment = Enrollment( student=student, course=course, grade='A', completed=True ) session.add_all([student, course, enrollment]) session.commit() # Query with association data for enroll in student.enrollments: print(f"{enroll.course.title}: Grade {enroll.grade}")

Basic Querying

SQLAlchemy provides a powerful query API. All queries start from session.query().

# Get all users users = session.query(User).all() # Get first result user = session.query(User).first() # Get by primary key user = session.query(User).get(1) # SQLAlchemy 1.x user = session.get(User, 1) # SQLAlchemy 2.x preferred # Count user_count = session.query(User).count() # Filter - single condition active_users = session.query(User).filter(User.is_active == True).all() # Filter - multiple conditions (AND) admin_users = session.query(User).filter( User.is_active == True, User.is_admin == True ).all() # Filter with OR from sqlalchemy import or_ users = session.query(User).filter( or_( User.username == 'alice', User.username == 'bob' ) ).all() # LIKE queries users = session.query(User).filter(User.username.like('%john%')).all() # IN queries usernames = ['alice', 'bob', 'charlie'] users = session.query(User).filter(User.username.in_(usernames)).all() # NOT IN users = session.query(User).filter(~User.username.in_(usernames)).all() # IS NULL / IS NOT NULL users = session.query(User).filter(User.bio == None).all() users = session.query(User).filter(User.bio != None).all() # Order by users = session.query(User).order_by(User.created_at.desc()).all() # Limit and offset (pagination) users = session.query(User).limit(10).offset(0).all() # First or 404 pattern user = session.query(User).filter(User.id == 999).first() if not user: raise ValueError("User not found")

Advanced Filtering

Combine multiple conditions and operators for complex queries.

from sqlalchemy import and_, or_, not_ # Complex AND/OR combinations results = session.query(User).filter( and_( User.is_active == True, or_( User.is_admin == True, User.username.like('%moderator%') ) ) ).all() # Between from sqlalchemy import between from datetime import datetime, timedelta week_ago = datetime.utcnow() - timedelta(days=7) recent_posts = session.query(Post).filter( between(Post.created_at, week_ago, datetime.utcnow()) ).all() # Case-insensitive search users = session.query(User).filter(User.username.ilike('%alice%')).all() # Multiple tables posts_with_users = session.query(Post, User).filter( Post.author_id == User.id ).all() # Select specific columns usernames = session.query(User.username, User.email).all() for username, email in usernames: print(f"{username}: {email}") # Distinct unique_authors = session.query(Post.author_id).distinct().all()

Joins

Joins combine data from multiple tables. SQLAlchemy makes joins intuitive when relationships are defined.

# Implicit join using relationship posts_by_alice = session.query(Post).join(Post.author).filter( User.username == 'alice' ).all() # Explicit join posts_by_alice = session.query(Post).join(User, Post.author_id == User.id).filter( User.username == 'alice' ).all() # Left outer join posts = session.query(Post).outerjoin(Comment).all() # Multiple joins comments_with_user_and_post = session.query(Comment).join( Comment.user ).join( Comment.post ).filter( User.username == 'alice', Post.published == True ).all() # Select from multiple tables results = session.query(User.username, Post.title).join( Post, User.id == Post.author_id ).all() for username, title in results: print(f"{username} wrote '{title}'")

Eager Loading vs Lazy Loading

By default, SQLAlchemy uses lazy loadingβ€”relationships are loaded only when accessed. This causes the N+1 query problem. Eager loading solves this by loading everything upfront.

from sqlalchemy.orm import joinedload, subqueryload, selectinload # LAZY LOADING (default) - N+1 problem users = session.query(User).all() # 1 query for user in users: print(user.posts) # N additional queries (one per user) # JOINED LOAD - Single query with JOIN users = session.query(User).options( joinedload(User.posts) ).all() # 1 query with LEFT OUTER JOIN for user in users: print(user.posts) # No additional queries! # SUBQUERY LOAD - Two queries (one main, one for all related) users = session.query(User).options( subqueryload(User.posts) ).all() # 2 queries total # SELECT IN LOAD - Two queries, more efficient for large datasets users = session.query(User).options( selectinload(User.posts) ).all() # Multiple level eager loading posts = session.query(Post).options( joinedload(Post.author), joinedload(Post.comments).joinedload(Comment.user) ).all() # Now we can access everything without extra queries for post in posts: print(f"Post: {post.title}") print(f"Author: {post.author.username}") for comment in post.comments: print(f" Comment by {comment.user.username}: {comment.content}")

When to Use Each Strategy

joinedload: Best for one-to-one or small one-to-many. Single query but can return duplicate rows.
subqueryload: Good for larger collections. Two queries, no duplicates.
selectinload: Most efficient for large datasets. Uses IN clause, recommended for SQLAlchemy 1.4+.

Pagination

Efficient pagination is critical for performance. Never load all records at once.

def paginate(query, page=1, per_page=20): """Paginate a query""" # Calculate offset offset = (page - 1) * per_page # Get total count total = query.count() # Get items for current page items = query.limit(per_page).offset(offset).all() # Calculate page info total_pages = (total + per_page - 1) // per_page has_next = page < total_pages has_prev = page > 1 return { 'items': items, 'page': page, 'per_page': per_page, 'total': total, 'total_pages': total_pages, 'has_next': has_next, 'has_prev': has_prev } # Usage query = session.query(Post).filter(Post.published == True).order_by(Post.created_at.desc()) page_data = paginate(query, page=1, per_page=10) print(f"Showing page {page_data['page']} of {page_data['total_pages']}") for post in page_data['items']: print(f" - {post.title}") # Flask-SQLAlchemy pagination # results = query.paginate(page=1, per_page=10) # results.items, results.has_next, results.has_prev

Session Management

The Session manages the lifecycle of objects. It tracks changes and knows when to INSERT, UPDATE, or DELETE.

# Create session session = Session() try: # Add new object user = User(username='charlie', email='charlie@example.com') session.add(user) # Add multiple objects users = [ User(username='dave', email='dave@example.com'), User(username='eve', email='eve@example.com') ] session.add_all(users) # Commit changes session.commit() # After commit, objects are in "persistent" state print(f"User ID after commit: {user.id}") except Exception as e: # Rollback on error session.rollback() print(f"Error: {e}") finally: # Always close session session.close() # Context manager pattern (recommended) with Session() as session: user = User(username='frank', email='frank@example.com') session.add(user) session.commit() # Session automatically closed

Object States

Objects in SQLAlchemy have four states: Transient, Pending, Persistent, and Detached.

from sqlalchemy import inspect # TRANSIENT - not in session, no database identity user = User(username='test', email='test@example.com') print(inspect(user).transient) # True # PENDING - in session, will be inserted on next flush session.add(user) print(inspect(user).pending) # True # PERSISTENT - in session, has database identity session.commit() print(inspect(user).persistent) # True print(user.id) # Has an ID now # DETACHED - was persistent, but session closed session.close() print(inspect(user).detached) # True # Merging detached objects session = Session() user = session.merge(user) # Back to persistent state

Transactions and Commits

Every session operation happens within a transaction. Understanding when to commit is crucial.

# Explicit transaction session = Session() try: # Multiple operations in one transaction user = User(username='alice', email='alice@example.com') session.add(user) # Flush sends SQL but doesn't commit session.flush() # User gets an ID, but not committed print(f"User ID after flush: {user.id}") # Can use the ID before commit post = Post(title='Test', content='...', author_id=user.id) session.add(post) # Now commit everything session.commit() except Exception as e: session.rollback() raise # Savepoints for nested transactions session.begin_nested() # Creates a savepoint try: user = User(username='bob', email='bob@example.com') session.add(user) session.commit() # Commits the savepoint except: session.rollback() # Rolls back to savepoint # Commit outer transaction session.commit()

Update and Delete Operations

SQLAlchemy tracks changes to persistent objects automatically. You can also do bulk operations.

# Update single object (tracked by session) user = session.query(User).filter(User.username == 'alice').first() user.email = 'alice.new@example.com' user.updated_at = datetime.utcnow() session.commit() # UPDATE statement generated automatically # Bulk update (more efficient, bypasses ORM) session.query(User).filter(User.is_active == False).update({ 'is_active': True }) session.commit() # Increment a counter session.query(Post).filter(Post.id == 1).update({ Post.view_count: Post.view_count + 1 }) session.commit() # Delete single object user = session.query(User).filter(User.id == 5).first() session.delete(user) session.commit() # Bulk delete session.query(User).filter(User.is_active == False).delete() session.commit() # Delete with cascade (if relationship has cascade='all, delete-orphan') user = session.query(User).filter(User.id == 1).first() session.delete(user) # Also deletes all user's posts and comments session.commit()

Database Migrations with Alembic

Alembic is SQLAlchemy's migration tool. It tracks schema changes and allows version control for your database.

# Install Alembic pip install alembic # Initialize Alembic in your project alembic init alembic # This creates: # alembic/ # β”œβ”€β”€ versions/ # Migration scripts # β”œβ”€β”€ env.py # Environment configuration # β”œβ”€β”€ script.py.mako # Migration template # alembic.ini # Alembic configuration

Configuring Alembic

Edit alembic.ini and alembic/env.py to connect to your database.

# alembic.ini - Set your database URL sqlalchemy.url = postgresql://user:password@localhost/blog # Or use environment variable # sqlalchemy.url = # alembic/env.py - Import your models from myapp.models import Base target_metadata = Base.metadata # For autogenerate to work, import ALL models from myapp.models import User, Post, Comment, Tag # Import all models

Creating Migrations

Alembic can auto-generate migrations by comparing your models to the database schema.

# Create initial migration alembic revision --autogenerate -m "Initial migration" # This creates a file like: alembic/versions/abc123_initial_migration.py # The migration file: """Initial migration Revision ID: abc123 Revises: Create Date: 2024-01-15 10:30:00 """ from alembic import op import sqlalchemy as sa # revision identifiers revision = 'abc123' down_revision = None branch_labels = None depends_on = None def upgrade(): # Commands to upgrade schema op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=50), nullable=False), sa.Column('email', sa.String(length=120), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('username'), sa.UniqueConstraint('email') ) def upgrade(): # Commands to downgrade schema op.drop_table('users')

Running Migrations

Apply migrations to update your database schema.

# Apply all pending migrations alembic upgrade head # Upgrade to specific revision alembic upgrade abc123 # Downgrade one revision alembic downgrade -1 # Downgrade to specific revision alembic downgrade abc123 # Show current revision alembic current # Show migration history alembic history # Show SQL without executing alembic upgrade head --sql

Manual Migrations

Sometimes you need to write migrations manually for complex changes.

# Create empty migration alembic revision -m "Add full text search" # Edit the migration file def upgrade(): # Add a new column op.add_column('posts', sa.Column('view_count', sa.Integer(), default=0)) # Create an index op.create_index('idx_posts_published', 'posts', ['published', 'created_at']) # Run raw SQL op.execute(""" CREATE INDEX idx_posts_search ON posts USING GIN(to_tsvector('english', title || ' ' || content)) """) def downgrade(): op.drop_index('idx_posts_search', 'posts') op.drop_index('idx_posts_published', 'posts') op.drop_column('posts', 'view_count')

Advanced ORM Patterns

Hybrid properties allow you to define properties that work both at the Python level and in SQL queries.

from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import func class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name = Column(String(50)) last_name = Column(String(50)) _password = Column('password', String(255)) @hybrid_property def full_name(self): """Python-level property""" return f"{self.first_name} {self.last_name}" @full_name.expression def full_name(cls): """SQL-level expression""" return func.concat(cls.first_name, ' ', cls.last_name) @hybrid_property def password(self): """Prevent reading password""" raise AttributeError("Password is not readable") @password.setter def password(self, plaintext): """Hash password on set""" import hashlib self._password = hashlib.sha256(plaintext.encode()).hexdigest() def verify_password(self, plaintext): import hashlib return self._password == hashlib.sha256(plaintext.encode()).hexdigest() # Usage user = User(first_name='John', last_name='Doe') print(user.full_name) # "John Doe" (Python property) # Query using hybrid property users = session.query(User).filter(User.full_name == 'John Doe').all() # Generates: WHERE first_name || ' ' || last_name = 'John Doe'

Model Events

SQLAlchemy provides event hooks to run code before/after database operations.

from sqlalchemy import event from datetime import datetime class Post(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String(200)) slug = Column(String(200), unique=True) content = Column(Text) created_at = Column(DateTime, default=datetime.utcnow) updated_at = Column(DateTime, onupdate=datetime.utcnow) # Event: before insert, generate slug @event.listens_for(Post, 'before_insert') def generate_slug(mapper, connection, target): if not target.slug: import re slug = re.sub(r'[^\w\s-]', '', target.title.lower()) slug = re.sub(r'[-\s]+', '-', slug) target.slug = slug # Event: before update, set updated_at @event.listens_for(Post, 'before_update') def update_timestamp(mapper, connection, target): target.updated_at = datetime.utcnow() # Event: after insert, log action @event.listens_for(Post, 'after_insert') def log_insert(mapper, connection, target): print(f"New post created: {target.title}") # Usage - slug auto-generated post = Post(title='My Awesome Post', content='...') session.add(post) session.commit() print(post.slug) # 'my-awesome-post'

Model Mixins

Mixins allow you to reuse common columns and methods across multiple models.

from datetime import datetime class TimestampMixin: """Add created_at and updated_at to any model""" created_at = Column(DateTime, default=datetime.utcnow, nullable=False) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) class SoftDeleteMixin: """Add soft delete functionality""" deleted_at = Column(DateTime, nullable=True) def soft_delete(self): self.deleted_at = datetime.utcnow() @classmethod def get_active(cls, session): return session.query(cls).filter(cls.deleted_at == None) class User(TimestampMixin, SoftDeleteMixin, Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True, nullable=False) email = Column(String(120), unique=True, nullable=False) class Post(TimestampMixin, SoftDeleteMixin, Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) content = Column(Text, nullable=False) # Usage user = User(username='alice', email='alice@example.com') # user.created_at and user.updated_at automatically set # Soft delete user.soft_delete() session.commit() # Query only active users active_users = User.get_active(session).all()

Complete Blog Application Example

Bringing it all togetherβ€”a complete blog application with users, posts, comments, tags, and categories.

from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime, Boolean, ForeignKey, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.hybrid import hybrid_property from datetime import datetime import hashlib Base = declarative_base() # Association table for many-to-many post_tags = Table('post_tags', Base.metadata, Column('post_id', Integer, ForeignKey('posts.id'), primary_key=True), Column('tag_id', Integer, ForeignKey('tags.id'), primary_key=True) ) class TimestampMixin: created_at = Column(DateTime, default=datetime.utcnow, nullable=False) updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) class User(TimestampMixin, Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) username = Column(String(50), unique=True, nullable=False, index=True) email = Column(String(120), unique=True, nullable=False, index=True) _password = Column('password_hash', String(255), nullable=False) bio = Column(Text) is_active = Column(Boolean, default=True) is_admin = Column(Boolean, default=False) # Relationships posts = relationship('Post', back_populates='author', cascade='all, delete-orphan') comments = relationship('Comment', back_populates='author', cascade='all, delete-orphan') @hybrid_property def password(self): raise AttributeError("Password is not readable") @password.setter def password(self, plaintext): self._password = hashlib.sha256(plaintext.encode()).hexdigest() def verify_password(self, plaintext): return self._password == hashlib.sha256(plaintext.encode()).hexdigest() def __repr__(self): return f"<User(username='{self.username}')>" class Category(Base): __tablename__ = 'categories' id = Column(Integer, primary_key=True) name = Column(String(100), unique=True, nullable=False) slug = Column(String(100), unique=True, nullable=False) description = Column(Text) posts = relationship('Post', back_populates='category') def __repr__(self): return f"<Category(name='{self.name}')>" class Tag(Base): __tablename__ = 'tags' id = Column(Integer, primary_key=True) name = Column(String(50), unique=True, nullable=False) slug = Column(String(50), unique=True, nullable=False) posts = relationship('Post', secondary=post_tags, back_populates='tags') def __repr__(self): return f"<Tag(name='{self.name}')>" class Post(TimestampMixin, Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) title = Column(String(200), nullable=False) slug = Column(String(200), unique=True, nullable=False, index=True) content = Column(Text, nullable=False) excerpt = Column(String(500)) published = Column(Boolean, default=False) view_count = Column(Integer, default=0) # Foreign keys author_id = Column(Integer, ForeignKey('users.id'), nullable=False) category_id = Column(Integer, ForeignKey('categories.id')) # Relationships author = relationship('User', back_populates='posts') category = relationship('Category', back_populates='posts') comments = relationship('Comment', back_populates='post', cascade='all, delete-orphan') tags = relationship('Tag', secondary=post_tags, back_populates='posts') def __repr__(self): return f"<Post(title='{self.title}')>" class Comment(TimestampMixin, Base): __tablename__ = 'comments' id = Column(Integer, primary_key=True) content = Column(Text, nullable=False) # Foreign keys author_id = Column(Integer, ForeignKey('users.id'), nullable=False) post_id = Column(Integer, ForeignKey('posts.id'), nullable=False) # Relationships author = relationship('User', back_populates='comments') post = relationship('Post', back_populates='comments') def __repr__(self): return f"<Comment(author='{self.author.username}', post='{self.post.title}')>" # Database setup engine = create_engine('sqlite:///blog.db', echo=True) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) # Application code def create_sample_data(): session = Session() try: # Create users alice = User(username='alice', email='alice@example.com') alice.password = 'secret123' bob = User(username='bob', email='bob@example.com') bob.password = 'password456' # Create categories python_cat = Category(name='Python', slug='python', description='Python programming') web_cat = Category(name='Web Development', slug='web-dev', description='Web dev tutorials') # Create tags tutorial_tag = Tag(name='Tutorial', slug='tutorial') beginner_tag = Tag(name='Beginner', slug='beginner') advanced_tag = Tag(name='Advanced', slug='advanced') # Create posts post1 = Post( title='Getting Started with Python', slug='getting-started-python', content='Python is an amazing language for beginners...', excerpt='Learn Python basics', published=True, author=alice, category=python_cat, tags=[tutorial_tag, beginner_tag] ) post2 = Post( title='Advanced SQLAlchemy Patterns', slug='advanced-sqlalchemy', content='Deep dive into SQLAlchemy ORM patterns...', excerpt='Master SQLAlchemy', published=True, author=alice, category=python_cat, tags=[tutorial_tag, advanced_tag] ) post3 = Post( title='Building REST APIs with Flask', slug='flask-rest-api', content='Create RESTful APIs using Flask...', excerpt='Flask API tutorial', published=True, author=bob, category=web_cat, tags=[tutorial_tag, beginner_tag] ) # Create comments comment1 = Comment( content='Great article! Very helpful.', author=bob, post=post1 ) comment2 = Comment( content='Thanks for sharing this.', author=alice, post=post3 ) # Add all to session session.add_all([alice, bob, python_cat, web_cat, tutorial_tag, beginner_tag, advanced_tag, post1, post2, post3, comment1, comment2]) session.commit() print("Sample data created successfully!") except Exception as e: session.rollback() print(f"Error: {e}") finally: session.close() def query_examples(): session = Session() # Get all published posts with author and category posts = session.query(Post).options( joinedload(Post.author), joinedload(Post.category), joinedload(Post.tags) ).filter(Post.published == True).order_by(Post.created_at.desc()).all() for post in posts: print(f"\n{post.title}") print(f"By {post.author.username} in {post.category.name if post.category else 'Uncategorized'}") print(f"Tags: {', '.join(tag.name for tag in post.tags)}") print(f"Comments: {len(post.comments)}") # Get posts by tag python_tag = session.query(Tag).filter(Tag.slug == 'tutorial').first() tutorial_posts = python_tag.posts print(f"\n{len(tutorial_posts)} posts tagged with 'tutorial'") # Get user with all posts and comments user = session.query(User).options( joinedload(User.posts), joinedload(User.comments) ).filter(User.username == 'alice').first() print(f"\nUser: {user.username}") print(f"Posts written: {len(user.posts)}") print(f"Comments made: {len(user.comments)}") session.close() if __name__ == '__main__': create_sample_data() query_examples()

Query Optimization Tips

Writing efficient queries is essential for application performance.

Performance Best Practices

1. Always use eager loading for relationships you'll access
2. Add indexes to foreign keys and frequently queried columns
3. Use bulk operations for mass updates/deletes
4. Select only needed columns when fetching lots of data
5. Paginate large result sets instead of loading everything
6. Use exists() instead of count() for existence checks
7. Profile queries with echo=True to see generated SQL
8. Use database-specific features when appropriate (e.g., JSONB in PostgreSQL)

# Efficient existence check has_posts = session.query( session.query(Post).filter(Post.author_id == user_id).exists() ).scalar() # Select specific columns for reports stats = session.query( func.count(Post.id).label('total'), func.count(Post.id).filter(Post.published == True).label('published') ).first() # Bulk insert (bypasses ORM) session.bulk_insert_mappings(User, [ {'username': 'user1', 'email': 'user1@example.com'}, {'username': 'user2', 'email': 'user2@example.com'}, {'username': 'user3', 'email': 'user3@example.com'}, ]) # Window functions for ranking from sqlalchemy import func, over ranked_posts = session.query( Post, over(func.row_number(), order_by=Post.view_count.desc()).label('rank') ).all()
The Complete Picture: SQLAlchemy is like a sophisticated translator between your Python code and the database. You speak Python (objects, classes, relationships), and it translates to SQL (tables, joins, queries). The better you understand both languages, the more powerful your translations become. Master the basics, learn the idioms, and you'll write database code that's both elegant and lightning fast.

Database Design

Good database design is the foundation of scalable applications. Master normalization, indexing strategies, relationship modeling, and schema design patterns that prevent technical debt and enable future growth.

Schema Design Principles

Database schema design is both an art and a science. The right design decisions made early can save you from months of painful refactoring. The wrong ones can haunt your application forever.

Start With Requirements

Don't design in a vacuum. Understand what data you need to store, how it will be queried, and what performance requirements exist. Interview stakeholders, analyze existing systems, and document use cases before writing a single CREATE TABLE statement.

Design for Change

Requirements evolve. Your schema should be flexible enough to adapt without requiring complete rewrites. Use proper abstractions, avoid hard-coded values in your schema, and plan for extensibility from day one.

Think in Sets, Not Rows

SQL is a set-based language. Design your schema to leverage set operations rather than forcing row-by-row processing. This mindset shift is crucial for both performance and maintainability.

Balance Normalization & Performance

Pure normalization theory doesn't always match real-world needs. Sometimes denormalization is the right choice. Know the rules well enough to know when to break them.

The Golden Rules of Schema Design

1. Use meaningful names: Table and column names should be self-documenting. user_email_addresses is better than ue_addrs.

2. Every table needs a primary key: No exceptions. Even junction tables.

3. Enforce constraints at the database level: Don't rely solely on application code. Use NOT NULL, UNIQUE, CHECK, and FOREIGN KEY constraints.

4. Choose appropriate data types: VARCHAR(255) for everything is lazy. Use BOOLEAN for flags, INT for IDs, DECIMAL for money, TIMESTAMP for dates.

5. Document your schema: Use database comments. Future you (or your team) will thank you.

-- Example: Well-designed user table with proper constraints CREATE TABLE users ( user_id BIGSERIAL PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, password_hash CHAR(60) NOT NULL, -- bcrypt produces 60 chars email_verified BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), last_login_at TIMESTAMP, account_status VARCHAR(20) NOT NULL DEFAULT 'active', CONSTRAINT check_username_format CHECK (username ~ '^[a-zA-Z0-9_-]+$'), CONSTRAINT check_email_format CHECK (email ~ '^[^@]+@[^@]+\.[^@]+$'), CONSTRAINT check_account_status CHECK (account_status IN ('active', 'suspended', 'deleted')) ); -- Add indexes for common queries CREATE INDEX idx_users_email ON users(email); CREATE INDEX idx_users_username ON users(username); CREATE INDEX idx_users_created_at ON users(created_at); CREATE INDEX idx_users_status ON users(account_status) WHERE account_status != 'deleted'; -- Add comment for documentation COMMENT ON TABLE users IS 'Core user accounts table. All user authentication and profile data.'; COMMENT ON COLUMN users.password_hash IS 'bcrypt hash of user password. Never store plain text passwords.';

Normalization: From 1NF to 5NF

Normalization is the process of organizing data to reduce redundancy and improve integrity. Each normal form builds on the previous one, solving specific types of data anomalies.

First Normal Form (1NF)

Each column contains atomic (indivisible) values, and each column contains values of a single type. No repeating groups.

-- ❌ VIOLATES 1NF: Multiple values in one column CREATE TABLE orders_bad ( order_id INT PRIMARY KEY, customer_name VARCHAR(100), products VARCHAR(500), -- "Apple,Orange,Banana" prices VARCHAR(100) -- "1.50,2.00,0.75" ); -- βœ… FOLLOWS 1NF: Atomic values only CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_name VARCHAR(100), order_date TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE TABLE order_items ( order_item_id INT PRIMARY KEY, order_id INT NOT NULL REFERENCES orders(order_id), product_name VARCHAR(100) NOT NULL, price DECIMAL(10,2) NOT NULL, quantity INT NOT NULL DEFAULT 1 );

Second Normal Form (2NF)

Must be in 1NF, and all non-key columns must depend on the entire primary key (not just part of it). Eliminates partial dependencies.

-- ❌ VIOLATES 2NF: product_name depends only on product_id, not the full key CREATE TABLE order_items_bad ( order_id INT, product_id INT, product_name VARCHAR(100), -- Depends only on product_id product_category VARCHAR(50), -- Depends only on product_id quantity INT, price DECIMAL(10,2), PRIMARY KEY (order_id, product_id) ); -- βœ… FOLLOWS 2NF: Separate products into their own table CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(100) NOT NULL, product_category VARCHAR(50) NOT NULL, base_price DECIMAL(10,2) NOT NULL ); CREATE TABLE order_items ( order_id INT, product_id INT, quantity INT NOT NULL, unit_price DECIMAL(10,2) NOT NULL, -- Price at time of order PRIMARY KEY (order_id, product_id), FOREIGN KEY (order_id) REFERENCES orders(order_id), FOREIGN KEY (product_id) REFERENCES products(product_id) );

Third Normal Form (3NF)

Must be in 2NF, and all columns must depend directly on the primary key. No transitive dependencies (A β†’ B β†’ C).

-- ❌ VIOLATES 3NF: zip_code β†’ city (transitive dependency) CREATE TABLE customers_bad ( customer_id INT PRIMARY KEY, customer_name VARCHAR(100), street_address VARCHAR(200), zip_code VARCHAR(10), city VARCHAR(100), -- Depends on zip_code, not customer_id state VARCHAR(2) -- Depends on zip_code, not customer_id ); -- βœ… FOLLOWS 3NF: Separate location data CREATE TABLE zip_codes ( zip_code VARCHAR(10) PRIMARY KEY, city VARCHAR(100) NOT NULL, state VARCHAR(2) NOT NULL, latitude DECIMAL(10,8), longitude DECIMAL(11,8) ); CREATE TABLE customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(100) NOT NULL, street_address VARCHAR(200), zip_code VARCHAR(10) REFERENCES zip_codes(zip_code) );

Boyce-Codd Normal Form (BCNF)

Stronger version of 3NF. For every functional dependency X β†’ Y, X must be a superkey. Rare in practice but important for certain schemas.

-- ❌ VIOLATES BCNF: professor determines department, but not part of key CREATE TABLE teaching_bad ( student_id INT, course_id INT, professor_id INT, department VARCHAR(50), -- Depends on professor_id PRIMARY KEY (student_id, course_id) ); -- βœ… FOLLOWS BCNF: Separate professor-department relationship CREATE TABLE professors ( professor_id INT PRIMARY KEY, professor_name VARCHAR(100) NOT NULL, department VARCHAR(50) NOT NULL ); CREATE TABLE courses ( course_id INT PRIMARY KEY, course_name VARCHAR(100) NOT NULL, professor_id INT REFERENCES professors(professor_id) ); CREATE TABLE enrollments ( student_id INT, course_id INT, enrollment_date DATE NOT NULL, grade VARCHAR(2), PRIMARY KEY (student_id, course_id), FOREIGN KEY (course_id) REFERENCES courses(course_id) );

Fourth Normal Form (4NF)

Eliminates multi-valued dependencies. If a table has independent multi-valued facts, separate them.

-- ❌ VIOLATES 4NF: skills and certifications are independent CREATE TABLE employee_qualifications_bad ( employee_id INT, skill VARCHAR(50), certification VARCHAR(50), PRIMARY KEY (employee_id, skill, certification) ); -- This forces all skill-certification combinations even if unrelated -- βœ… FOLLOWS 4NF: Separate independent multi-valued facts CREATE TABLE employee_skills ( employee_id INT, skill VARCHAR(50), proficiency_level VARCHAR(20), PRIMARY KEY (employee_id, skill) ); CREATE TABLE employee_certifications ( employee_id INT, certification VARCHAR(50), issued_date DATE NOT NULL, expiry_date DATE, PRIMARY KEY (employee_id, certification) );

Fifth Normal Form (5NF)

Deals with join dependencies. Rarely needed in practice, but understanding it shows mastery of relational theory.

-- ❌ VIOLATES 5NF: Redundant data when supplier-part-project has constraints CREATE TABLE supplies_bad ( supplier_id INT, part_id INT, project_id INT, PRIMARY KEY (supplier_id, part_id, project_id) ); -- If "Supplier S supplies Part P" and "Part P used in Project Pr" -- then "Supplier S supplies Part P to Project Pr" is implied -- βœ… FOLLOWS 5NF: Decompose into separate relationships CREATE TABLE supplier_parts ( supplier_id INT, part_id INT, unit_price DECIMAL(10,2), PRIMARY KEY (supplier_id, part_id) ); CREATE TABLE project_parts ( project_id INT, part_id INT, quantity_needed INT, PRIMARY KEY (project_id, part_id) ); CREATE TABLE project_suppliers ( project_id INT, supplier_id INT, preferred BOOLEAN DEFAULT FALSE, PRIMARY KEY (project_id, supplier_id) );
Normalization as Organizing a Library: Imagine a library where books are scattered everywhere with duplicate information. 1NF is like saying "one book per slot, no book can contain another book inside it." 2NF is ensuring each shelf only contains books about one topic. 3NF is making sure you don't write the author's biography in every bookβ€”keep it in one place and reference it. Higher normal forms are like fine-tuning the Dewey Decimal System to eliminate every possible redundancy.

Relationship Patterns

Real-world data relationships come in three fundamental flavors. Understanding how to model each correctly is essential.

One-to-One (1:1) Relationships

Rare but useful for separating sensitive data or splitting large tables.

-- One-to-One: User and UserProfile CREATE TABLE users ( user_id BIGSERIAL PRIMARY KEY, username VARCHAR(50) NOT NULL UNIQUE, email VARCHAR(255) NOT NULL UNIQUE, password_hash CHAR(60) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); -- Separate table for optional/sensitive profile data CREATE TABLE user_profiles ( user_id BIGINT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE, full_name VARCHAR(200), bio TEXT, avatar_url VARCHAR(500), date_of_birth DATE, phone_number VARCHAR(20), address TEXT, updated_at TIMESTAMP NOT NULL DEFAULT NOW() ); -- One-to-One: Employee and EmployeeSecurityClearance CREATE TABLE employees ( employee_id INT PRIMARY KEY, employee_name VARCHAR(100) NOT NULL, department VARCHAR(50), hire_date DATE NOT NULL ); CREATE TABLE security_clearances ( employee_id INT PRIMARY KEY REFERENCES employees(employee_id), clearance_level VARCHAR(20) NOT NULL, issued_date DATE NOT NULL, expiry_date DATE NOT NULL, issuing_authority VARCHAR(100), CHECK (clearance_level IN ('Public', 'Confidential', 'Secret', 'Top Secret')) );

One-to-Many (1:N) Relationships

The most common relationship type. One parent, many children.

-- One-to-Many: Author to Books CREATE TABLE authors ( author_id SERIAL PRIMARY KEY, author_name VARCHAR(200) NOT NULL, bio TEXT, birth_year INT ); CREATE TABLE books ( book_id SERIAL PRIMARY KEY, title VARCHAR(300) NOT NULL, author_id INT NOT NULL REFERENCES authors(author_id), published_year INT, isbn VARCHAR(17) UNIQUE, pages INT, genre VARCHAR(50) ); CREATE INDEX idx_books_author ON books(author_id); -- One-to-Many: Customer to Orders CREATE TABLE customers ( customer_id SERIAL PRIMARY KEY, customer_name VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, customer_id INT NOT NULL REFERENCES customers(customer_id), order_date TIMESTAMP NOT NULL DEFAULT NOW(), total_amount DECIMAL(10,2) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'pending', CHECK (status IN ('pending', 'processing', 'shipped', 'delivered', 'cancelled')) ); CREATE INDEX idx_orders_customer ON orders(customer_id); CREATE INDEX idx_orders_date ON orders(order_date);

Many-to-Many (M:N) Relationships

Requires a junction (join) table to connect two tables.

-- Many-to-Many: Students and Courses CREATE TABLE students ( student_id SERIAL PRIMARY KEY, student_name VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, enrollment_date DATE NOT NULL ); CREATE TABLE courses ( course_id SERIAL PRIMARY KEY, course_code VARCHAR(10) NOT NULL UNIQUE, course_name VARCHAR(200) NOT NULL, credits INT NOT NULL, department VARCHAR(50) ); -- Junction table with additional attributes CREATE TABLE enrollments ( enrollment_id SERIAL PRIMARY KEY, student_id INT NOT NULL REFERENCES students(student_id) ON DELETE CASCADE, course_id INT NOT NULL REFERENCES courses(course_id) ON DELETE CASCADE, enrollment_date DATE NOT NULL DEFAULT CURRENT_DATE, grade VARCHAR(2), semester VARCHAR(20) NOT NULL, UNIQUE (student_id, course_id, semester) ); CREATE INDEX idx_enrollments_student ON enrollments(student_id); CREATE INDEX idx_enrollments_course ON enrollments(course_id); -- Many-to-Many: Products and Categories CREATE TABLE products ( product_id SERIAL PRIMARY KEY, product_name VARCHAR(200) NOT NULL, description TEXT, price DECIMAL(10,2) NOT NULL ); CREATE TABLE categories ( category_id SERIAL PRIMARY KEY, category_name VARCHAR(100) NOT NULL UNIQUE, parent_category_id INT REFERENCES categories(category_id) ); CREATE TABLE product_categories ( product_id INT REFERENCES products(product_id) ON DELETE CASCADE, category_id INT REFERENCES categories(category_id) ON DELETE CASCADE, is_primary BOOLEAN DEFAULT FALSE, PRIMARY KEY (product_id, category_id) ); CREATE INDEX idx_product_categories_product ON product_categories(product_id); CREATE INDEX idx_product_categories_category ON product_categories(category_id);

Self-Referencing Relationships

Tables that reference themselves, useful for hierarchical data.

-- Self-referencing: Employee hierarchy CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, employee_name VARCHAR(100) NOT NULL, job_title VARCHAR(100), manager_id INT REFERENCES employees(employee_id), salary DECIMAL(10,2), hire_date DATE NOT NULL ); -- Query to find all reports under a manager (requires recursive CTE) WITH RECURSIVE employee_hierarchy AS ( -- Base case: start with a specific manager SELECT employee_id, employee_name, manager_id, 1 as level FROM employees WHERE employee_id = 5 UNION ALL -- Recursive case: find direct reports SELECT e.employee_id, e.employee_name, e.manager_id, eh.level + 1 FROM employees e INNER JOIN employee_hierarchy eh ON e.manager_id = eh.employee_id ) SELECT * FROM employee_hierarchy; -- Self-referencing: Categories with parent-child CREATE TABLE categories ( category_id SERIAL PRIMARY KEY, category_name VARCHAR(100) NOT NULL, parent_category_id INT REFERENCES categories(category_id), depth_level INT NOT NULL DEFAULT 0, sort_order INT DEFAULT 0 ); -- Self-referencing: Comments with replies CREATE TABLE comments ( comment_id BIGSERIAL PRIMARY KEY, post_id INT NOT NULL, user_id INT NOT NULL, parent_comment_id BIGINT REFERENCES comments(comment_id) ON DELETE CASCADE, comment_text TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW(), upvotes INT DEFAULT 0 ); CREATE INDEX idx_comments_parent ON comments(parent_comment_id); CREATE INDEX idx_comments_post ON comments(post_id);

Common Design Patterns

Battle-tested patterns that solve recurring database design problems.

Soft Deletes

Never physically delete data. Mark it as deleted instead, preserving history and enabling recovery.

-- Soft delete pattern CREATE TABLE users ( user_id BIGSERIAL PRIMARY KEY, username VARCHAR(50) NOT NULL, email VARCHAR(255) NOT NULL, deleted_at TIMESTAMP NULL, -- NULL means active, timestamp means deleted deleted_by INT REFERENCES users(user_id), created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW() ); -- Index only active users for performance CREATE INDEX idx_users_active ON users(user_id) WHERE deleted_at IS NULL; -- View for active users only CREATE VIEW active_users AS SELECT user_id, username, email, created_at, updated_at FROM users WHERE deleted_at IS NULL; -- Soft delete function CREATE OR REPLACE FUNCTION soft_delete_user(p_user_id INT, p_deleted_by INT) RETURNS VOID AS $$ BEGIN UPDATE users SET deleted_at = NOW(), deleted_by = p_deleted_by WHERE user_id = p_user_id AND deleted_at IS NULL; END; $$ LANGUAGE plpgsql;

Audit Trails

Track who changed what and when. Essential for compliance, debugging, and accountability.

-- Audit trail pattern with shadow table CREATE TABLE products ( product_id SERIAL PRIMARY KEY, product_name VARCHAR(200) NOT NULL, price DECIMAL(10,2) NOT NULL, stock_quantity INT NOT NULL DEFAULT 0, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_by INT REFERENCES users(user_id) ); -- Audit log table CREATE TABLE product_audit_log ( audit_id BIGSERIAL PRIMARY KEY, product_id INT NOT NULL, action VARCHAR(10) NOT NULL, -- 'INSERT', 'UPDATE', 'DELETE' old_values JSONB, new_values JSONB, changed_by INT REFERENCES users(user_id), changed_at TIMESTAMP NOT NULL DEFAULT NOW(), change_reason TEXT ); -- Trigger to automatically log changes CREATE OR REPLACE FUNCTION audit_product_changes() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'DELETE' THEN INSERT INTO product_audit_log (product_id, action, old_values, changed_at) VALUES (OLD.product_id, 'DELETE', row_to_json(OLD), NOW()); RETURN OLD; ELSIF TG_OP = 'UPDATE' THEN INSERT INTO product_audit_log (product_id, action, old_values, new_values, changed_by, changed_at) VALUES (NEW.product_id, 'UPDATE', row_to_json(OLD), row_to_json(NEW), NEW.updated_by, NOW()); RETURN NEW; ELSIF TG_OP = 'INSERT' THEN INSERT INTO product_audit_log (product_id, action, new_values, changed_by, changed_at) VALUES (NEW.product_id, 'INSERT', row_to_json(NEW), NEW.updated_by, NOW()); RETURN NEW; END IF; END; $$ LANGUAGE plpgsql; CREATE TRIGGER product_audit_trigger AFTER INSERT OR UPDATE OR DELETE ON products FOR EACH ROW EXECUTE FUNCTION audit_product_changes();

Temporal Data (Slowly Changing Dimensions)

Track how data changes over time. Critical for analytics and historical reporting.

-- Type 2 SCD: Keep full history with date ranges CREATE TABLE customer_addresses ( address_id BIGSERIAL PRIMARY KEY, customer_id INT NOT NULL REFERENCES customers(customer_id), street VARCHAR(200) NOT NULL, city VARCHAR(100) NOT NULL, state VARCHAR(2) NOT NULL, zip_code VARCHAR(10) NOT NULL, valid_from TIMESTAMP NOT NULL DEFAULT NOW(), valid_to TIMESTAMP DEFAULT '9999-12-31', -- NULL or far future for current record is_current BOOLEAN DEFAULT TRUE, CHECK (valid_from < valid_to) ); CREATE INDEX idx_customer_addresses_current ON customer_addresses(customer_id) WHERE is_current = TRUE; -- Function to update address (creates new record, closes old one) CREATE OR REPLACE FUNCTION update_customer_address( p_customer_id INT, p_street VARCHAR, p_city VARCHAR, p_state VARCHAR, p_zip VARCHAR ) RETURNS VOID AS $$ BEGIN -- Close current address UPDATE customer_addresses SET valid_to = NOW(), is_current = FALSE WHERE customer_id = p_customer_id AND is_current = TRUE; -- Insert new address INSERT INTO customer_addresses (customer_id, street, city, state, zip_code, valid_from, is_current) VALUES (p_customer_id, p_street, p_city, p_state, p_zip, NOW(), TRUE); END; $$ LANGUAGE plpgsql; -- Query current address SELECT * FROM customer_addresses WHERE customer_id = 123 AND is_current = TRUE; -- Query address at specific point in time SELECT * FROM customer_addresses WHERE customer_id = 123 AND valid_from <= '2023-06-15' AND valid_to > '2023-06-15';

Polymorphic Associations

When multiple tables need to reference different types of entities.

-- Polymorphic pattern: Comments on multiple entity types CREATE TABLE posts ( post_id SERIAL PRIMARY KEY, title VARCHAR(300) NOT NULL, content TEXT NOT NULL ); CREATE TABLE images ( image_id SERIAL PRIMARY KEY, image_url VARCHAR(500) NOT NULL, caption TEXT ); -- Generic comments table with polymorphic reference CREATE TABLE comments ( comment_id BIGSERIAL PRIMARY KEY, commentable_type VARCHAR(50) NOT NULL, -- 'post', 'image', 'video' commentable_id INT NOT NULL, user_id INT NOT NULL REFERENCES users(user_id), comment_text TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW(), CHECK (commentable_type IN ('post', 'image', 'video')) ); -- Indexes for polymorphic queries CREATE INDEX idx_comments_polymorphic ON comments(commentable_type, commentable_id); -- Better approach: Explicit junction tables (more type-safe) CREATE TABLE post_comments ( comment_id BIGSERIAL PRIMARY KEY, post_id INT NOT NULL REFERENCES posts(post_id) ON DELETE CASCADE, user_id INT NOT NULL REFERENCES users(user_id), comment_text TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE TABLE image_comments ( comment_id BIGSERIAL PRIMARY KEY, image_id INT NOT NULL REFERENCES images(image_id) ON DELETE CASCADE, user_id INT NOT NULL REFERENCES users(user_id), comment_text TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() );

Tags and Tagging

Flexible categorization system that's more dynamic than rigid hierarchies.

-- Tagging system CREATE TABLE tags ( tag_id SERIAL PRIMARY KEY, tag_name VARCHAR(50) NOT NULL UNIQUE, slug VARCHAR(50) NOT NULL UNIQUE, -- URL-friendly version description TEXT, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE TABLE posts ( post_id SERIAL PRIMARY KEY, title VARCHAR(300) NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); -- Many-to-many junction table CREATE TABLE post_tags ( post_id INT REFERENCES posts(post_id) ON DELETE CASCADE, tag_id INT REFERENCES tags(tag_id) ON DELETE CASCADE, tagged_at TIMESTAMP NOT NULL DEFAULT NOW(), PRIMARY KEY (post_id, tag_id) ); CREATE INDEX idx_post_tags_post ON post_tags(post_id); CREATE INDEX idx_post_tags_tag ON post_tags(tag_id); -- Find posts with specific tag SELECT p.* FROM posts p INNER JOIN post_tags pt ON p.post_id = pt.post_id INNER JOIN tags t ON pt.tag_id = t.tag_id WHERE t.slug = 'javascript'; -- Find posts with multiple tags (AND logic) SELECT p.* FROM posts p WHERE p.post_id IN ( SELECT post_id FROM post_tags WHERE tag_id = 1 INTERSECT SELECT post_id FROM post_tags WHERE tag_id = 2 ); -- Tag cloud query (most popular tags) SELECT t.tag_name, COUNT(pt.post_id) as post_count FROM tags t LEFT JOIN post_tags pt ON t.tag_id = pt.tag_id GROUP BY t.tag_id, t.tag_name ORDER BY post_count DESC LIMIT 20;

Anti-Patterns to Avoid

Learn from others' mistakes. These design choices seem reasonable at first but lead to maintenance nightmares.

❌ Entity-Attribute-Value (EAV)

Storing data as key-value pairs instead of columns. Looks flexible, but kills query performance and type safety. Use JSONB for truly dynamic data instead.

❌ God Tables

One massive table with 100+ columns trying to store everything. Break it down. Use proper normalization and relationship modeling.

❌ Fear of Joins

Denormalizing everything into one table to avoid joins. Joins are fast when properly indexed. Premature optimization is the root of all evil.

❌ Ambiguous Column Names

Columns named "id", "name", "date" without context. Use descriptive names: user_id, product_name, order_date. Your future self will thank you.

❌ Missing Foreign Keys

Relying on application code to maintain referential integrity. Always use database constraints. They're faster and more reliable than your code.

❌ Using VARCHAR for Everything

VARCHAR(255) for numbers, dates, booleans. Use proper data types. They provide validation, save space, and enable better indexing.

-- ❌ ANTI-PATTERN: EAV (Don't do this) CREATE TABLE eav_attributes ( entity_id INT, attribute_name VARCHAR(100), attribute_value TEXT, -- Everything is text! PRIMARY KEY (entity_id, attribute_name) ); -- Querying is a nightmare: SELECT MAX(CASE WHEN attribute_name = 'name' THEN attribute_value END) as name, MAX(CASE WHEN attribute_name = 'age' THEN attribute_value END) as age, MAX(CASE WHEN attribute_name = 'email' THEN attribute_value END) as email FROM eav_attributes WHERE entity_id = 123 GROUP BY entity_id; -- βœ… BETTER: Proper columns with types CREATE TABLE users ( user_id INT PRIMARY KEY, name VARCHAR(100) NOT NULL, age INT CHECK (age >= 0 AND age <= 150), email VARCHAR(255) NOT NULL UNIQUE ); -- βœ… OR: Use JSONB for truly dynamic data CREATE TABLE user_metadata ( user_id INT PRIMARY KEY REFERENCES users(user_id), metadata JSONB NOT NULL DEFAULT '{}' ); -- Query JSONB efficiently with indexes CREATE INDEX idx_user_metadata_preferences ON user_metadata USING gin ((metadata -> 'preferences'));

E-Commerce Schema Example

A complete, production-ready e-commerce schema demonstrating all the patterns we've discussed.

-- USERS AND AUTHENTICATION CREATE TABLE users ( user_id BIGSERIAL PRIMARY KEY, email VARCHAR(255) NOT NULL UNIQUE, username VARCHAR(50) NOT NULL UNIQUE, password_hash CHAR(60) NOT NULL, email_verified BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), last_login_at TIMESTAMP, account_status VARCHAR(20) NOT NULL DEFAULT 'active', CHECK (account_status IN ('active', 'suspended', 'deleted')) ); CREATE TABLE user_profiles ( user_id BIGINT PRIMARY KEY REFERENCES users(user_id) ON DELETE CASCADE, first_name VARCHAR(100), last_name VARCHAR(100), phone VARCHAR(20), date_of_birth DATE, avatar_url VARCHAR(500) ); -- ADDRESSES (supports multiple addresses per user) CREATE TABLE addresses ( address_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE, address_type VARCHAR(20) NOT NULL, -- 'shipping', 'billing' street_line1 VARCHAR(200) NOT NULL, street_line2 VARCHAR(200), city VARCHAR(100) NOT NULL, state VARCHAR(50) NOT NULL, postal_code VARCHAR(20) NOT NULL, country VARCHAR(2) NOT NULL DEFAULT 'US', is_default BOOLEAN DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE INDEX idx_addresses_user ON addresses(user_id); -- PRODUCTS CREATE TABLE categories ( category_id SERIAL PRIMARY KEY, category_name VARCHAR(100) NOT NULL UNIQUE, slug VARCHAR(100) NOT NULL UNIQUE, parent_category_id INT REFERENCES categories(category_id), description TEXT, image_url VARCHAR(500) ); CREATE TABLE products ( product_id BIGSERIAL PRIMARY KEY, product_name VARCHAR(300) NOT NULL, slug VARCHAR(300) NOT NULL UNIQUE, description TEXT, base_price DECIMAL(10,2) NOT NULL, cost_price DECIMAL(10,2), -- For profit calculations sku VARCHAR(100) UNIQUE, weight_grams INT, is_active BOOLEAN DEFAULT TRUE, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), CHECK (base_price >= 0), CHECK (cost_price >= 0 OR cost_price IS NULL) ); CREATE TABLE product_categories ( product_id BIGINT REFERENCES products(product_id) ON DELETE CASCADE, category_id INT REFERENCES categories(category_id) ON DELETE CASCADE, is_primary BOOLEAN DEFAULT FALSE, PRIMARY KEY (product_id, category_id) ); -- PRODUCT VARIANTS (size, color, etc.) CREATE TABLE product_variants ( variant_id BIGSERIAL PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES products(product_id) ON DELETE CASCADE, variant_name VARCHAR(100) NOT NULL, -- "Red / Large" sku VARCHAR(100) UNIQUE, price_adjustment DECIMAL(10,2) DEFAULT 0, -- Add/subtract from base price stock_quantity INT NOT NULL DEFAULT 0, is_available BOOLEAN DEFAULT TRUE, CHECK (stock_quantity >= 0) ); CREATE INDEX idx_variants_product ON product_variants(product_id); -- PRODUCT IMAGES CREATE TABLE product_images ( image_id BIGSERIAL PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES products(product_id) ON DELETE CASCADE, image_url VARCHAR(500) NOT NULL, alt_text VARCHAR(200), display_order INT DEFAULT 0, is_primary BOOLEAN DEFAULT FALSE ); CREATE INDEX idx_images_product ON product_images(product_id); -- SHOPPING CART CREATE TABLE carts ( cart_id BIGSERIAL PRIMARY KEY, user_id BIGINT REFERENCES users(user_id) ON DELETE CASCADE, -- NULL for guest carts session_id VARCHAR(100), -- For guest users created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), expires_at TIMESTAMP -- Auto-cleanup old carts ); CREATE TABLE cart_items ( cart_item_id BIGSERIAL PRIMARY KEY, cart_id BIGINT NOT NULL REFERENCES carts(cart_id) ON DELETE CASCADE, product_id BIGINT NOT NULL REFERENCES products(product_id), variant_id BIGINT REFERENCES product_variants(variant_id), quantity INT NOT NULL DEFAULT 1, unit_price DECIMAL(10,2) NOT NULL, -- Snapshot price at add-to-cart time added_at TIMESTAMP NOT NULL DEFAULT NOW(), CHECK (quantity > 0), UNIQUE (cart_id, product_id, variant_id) ); -- ORDERS CREATE TABLE orders ( order_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(user_id), order_number VARCHAR(50) NOT NULL UNIQUE, -- Display to customers order_status VARCHAR(20) NOT NULL DEFAULT 'pending', subtotal DECIMAL(10,2) NOT NULL, tax_amount DECIMAL(10,2) NOT NULL DEFAULT 0, shipping_amount DECIMAL(10,2) NOT NULL DEFAULT 0, discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0, total_amount DECIMAL(10,2) NOT NULL, shipping_address_id BIGINT REFERENCES addresses(address_id), billing_address_id BIGINT REFERENCES addresses(address_id), payment_method VARCHAR(50), payment_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), shipped_at TIMESTAMP, delivered_at TIMESTAMP, CHECK (order_status IN ('pending', 'processing', 'shipped', 'delivered', 'cancelled', 'refunded')), CHECK (payment_status IN ('pending', 'paid', 'failed', 'refunded')), CHECK (total_amount = subtotal + tax_amount + shipping_amount - discount_amount) ); CREATE INDEX idx_orders_user ON orders(user_id); CREATE INDEX idx_orders_status ON orders(order_status); CREATE INDEX idx_orders_created ON orders(created_at); CREATE TABLE order_items ( order_item_id BIGSERIAL PRIMARY KEY, order_id BIGINT NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE, product_id BIGINT NOT NULL REFERENCES products(product_id), variant_id BIGINT REFERENCES product_variants(variant_id), product_name VARCHAR(300) NOT NULL, -- Snapshot for history variant_name VARCHAR(100), quantity INT NOT NULL, unit_price DECIMAL(10,2) NOT NULL, -- Price at order time subtotal DECIMAL(10,2) NOT NULL, CHECK (quantity > 0), CHECK (subtotal = quantity * unit_price) ); CREATE INDEX idx_order_items_order ON order_items(order_id); -- REVIEWS CREATE TABLE product_reviews ( review_id BIGSERIAL PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES products(product_id) ON DELETE CASCADE, user_id BIGINT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE, rating INT NOT NULL, review_title VARCHAR(200), review_text TEXT, is_verified_purchase BOOLEAN DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW(), CHECK (rating >= 1 AND rating <= 5), UNIQUE (product_id, user_id) -- One review per user per product ); CREATE INDEX idx_reviews_product ON product_reviews(product_id); CREATE INDEX idx_reviews_user ON product_reviews(user_id); -- WISHLISTS CREATE TABLE wishlists ( wishlist_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL REFERENCES users(user_id) ON DELETE CASCADE, wishlist_name VARCHAR(100) NOT NULL DEFAULT 'My Wishlist', is_public BOOLEAN DEFAULT FALSE, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE TABLE wishlist_items ( wishlist_id BIGINT REFERENCES wishlists(wishlist_id) ON DELETE CASCADE, product_id BIGINT REFERENCES products(product_id) ON DELETE CASCADE, added_at TIMESTAMP NOT NULL DEFAULT NOW(), PRIMARY KEY (wishlist_id, product_id) ); -- COUPONS AND DISCOUNTS CREATE TABLE coupons ( coupon_id SERIAL PRIMARY KEY, coupon_code VARCHAR(50) NOT NULL UNIQUE, discount_type VARCHAR(20) NOT NULL, -- 'percentage' or 'fixed' discount_value DECIMAL(10,2) NOT NULL, min_order_amount DECIMAL(10,2), max_discount_amount DECIMAL(10,2), usage_limit INT, -- NULL for unlimited usage_count INT NOT NULL DEFAULT 0, valid_from TIMESTAMP NOT NULL, valid_until TIMESTAMP NOT NULL, is_active BOOLEAN DEFAULT TRUE, CHECK (discount_type IN ('percentage', 'fixed')), CHECK (discount_value > 0) ); CREATE TABLE order_coupons ( order_id BIGINT REFERENCES orders(order_id), coupon_id INT REFERENCES coupons(coupon_id), discount_applied DECIMAL(10,2) NOT NULL, PRIMARY KEY (order_id, coupon_id) ); -- INVENTORY TRACKING CREATE TABLE inventory_transactions ( transaction_id BIGSERIAL PRIMARY KEY, variant_id BIGINT NOT NULL REFERENCES product_variants(variant_id), transaction_type VARCHAR(20) NOT NULL, -- 'purchase', 'sale', 'return', 'adjustment' quantity_change INT NOT NULL, -- Positive or negative resulting_quantity INT NOT NULL, reference_type VARCHAR(50), -- 'order', 'return', 'manual' reference_id BIGINT, notes TEXT, created_at TIMESTAMP NOT NULL DEFAULT NOW(), created_by BIGINT REFERENCES users(user_id), CHECK (transaction_type IN ('purchase', 'sale', 'return', 'adjustment')) );

Schema Design Checklist

βœ… Every table has a primary key
βœ… Foreign key constraints are defined
βœ… Appropriate indexes on foreign keys and frequently queried columns
βœ… NOT NULL constraints where applicable
βœ… CHECK constraints for data validation
βœ… Default values for columns that should have them
βœ… Timestamp columns (created_at, updated_at) for audit trails
βœ… Soft delete support (deleted_at) where needed
βœ… Proper data types (not VARCHAR for everything)
βœ… Meaningful, consistent naming conventions
βœ… Comments on tables and complex columns
βœ… Junction tables for many-to-many relationships
βœ… Separation of concerns (users vs profiles vs addresses)

Database Design as Architecture: Think of database design like designing a building. You can't easily move walls after construction begins. Foundation (schema) must be solid. Rooms (tables) should have clear purposes. Hallways (relationships) need to connect logically. Wiring (indexes) must be planned from the start. You can renovate (refactor), but it's expensive. Build it right the first time by understanding your requirements, following proven patterns, and learning from others' mistakes. A well-designed schema is invisibleβ€”it just works. A poorly designed one causes pain every single day.

Advanced Topics

Go beyond basics with transactions, ACID properties, replication, sharding, database migrations, and performance optimization. Learn the production-level skills that separate junior developers from senior engineers.

Database Replication

Replication creates copies of your database across multiple servers for redundancy, high availability, and load distribution. Master replication to build systems that never go down.

Metaphor: Replication is like having multiple photocopiers of your important documents in different buildings. If one building burns down, you still have all your documents safe elsewhere. Plus, people can read from the nearest copy instead of everyone crowding around one machine.

Master-Slave Replication (MySQL)

The most common pattern: one master handles writes, multiple slaves handle reads.

-- Master server configuration (my.cnf) [mysqld] server-id=1 log-bin=mysql-bin binlog-do-db=production_db binlog-format=ROW -- Slave server configuration (my.cnf) [mysqld] server-id=2 relay-log=mysql-relay-bin read_only=1 -- On master: Create replication user CREATE USER 'replicator'@'%' IDENTIFIED BY 'strong_password'; GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%'; FLUSH PRIVILEGES; SHOW MASTER STATUS; -- Note the File and Position -- On slave: Configure replication CHANGE MASTER TO MASTER_HOST='master.example.com', MASTER_USER='replicator', MASTER_PASSWORD='strong_password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=154; START SLAVE; SHOW SLAVE STATUS\G -- Verify replication is running

PostgreSQL Streaming Replication

PostgreSQL uses Write-Ahead Logging (WAL) streaming for real-time replication.

-- Primary server: postgresql.conf wal_level = replica max_wal_senders = 5 wal_keep_size = 1GB hot_standby = on -- Primary server: pg_hba.conf host replication replicator 192.168.1.0/24 md5 -- Create replication user on primary CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'secure_pass'; -- On standby server: Create base backup pg_basebackup -h primary.example.com -D /var/lib/postgresql/data \ -U replicator -P -v -R -X stream -C -S standby_slot -- standby.signal file is created automatically with -R flag -- Start standby server pg_ctl start -- Verify replication on primary SELECT client_addr, state, sync_state FROM pg_stat_replication;

MongoDB Replica Set

MongoDB uses replica sets with automatic failoverβ€”if the primary goes down, a secondary is automatically elected as the new primary.

// Initialize replica set on first node rs.initiate({ _id: "myReplicaSet", members: [ { _id: 0, host: "mongo1.example.com:27017" }, { _id: 1, host: "mongo2.example.com:27017" }, { _id: 2, host: "mongo3.example.com:27017" } ] }) // Check replica set status rs.status() // Check which is primary rs.isMaster() // Add a new member to existing replica set rs.add("mongo4.example.com:27017") // Remove a member rs.remove("mongo4.example.com:27017") // Set priority (higher = more likely to become primary) cfg = rs.conf() cfg.members[1].priority = 2 rs.reconfig(cfg) // Read from secondaries (in connection string) mongodb://mongo1.example.com,mongo2.example.com,mongo3.example.com/?replicaSet=myReplicaSet&readPreference=secondaryPreferred

Replication Lag

Slaves/secondaries aren't always perfectly in sync. There's a delay (lag) between when data is written to the master and when it appears on replicas. Monitor this lag and handle it in your application logicβ€”never assume a read from a replica will show the most recent write.

Database Sharding

Sharding splits your database horizontally across multiple servers. Instead of one giant database, you have many smaller databases, each holding a subset of your data.

Metaphor: Sharding is like dividing a massive library into multiple buildings. Building A holds books from A-G, Building B holds H-N, Building C holds O-Z. Each building is smaller and easier to manage, and you can search them in parallel.

Sharding Strategies

Range-Based Sharding

Split data by ranges of a shard key (e.g., user_id 1-1000000 on shard1, 1000001-2000000 on shard2). Simple but can lead to hotspots if data isn't evenly distributed.

Hash-Based Sharding

Hash the shard key and distribute based on hash value. Ensures even distribution but makes range queries difficult.

Geographic Sharding

Shard by location (EU users on EU servers, US users on US servers). Reduces latency and helps with data sovereignty laws.

Directory-Based Sharding

Maintain a lookup table that maps entities to shards. Most flexible but adds a lookup overhead and a potential single point of failure.

Implementing Hash-Based Sharding (Application Level)

When your database doesn't support automatic sharding, implement it in your application layer.

import hashlib import psycopg2 class ShardedDatabase: def __init__(self, shard_connections): """ shard_connections: List of database connection strings """ self.shards = [psycopg2.connect(conn) for conn in shard_connections] self.num_shards = len(self.shards) def get_shard(self, shard_key): """Determine which shard to use based on hash of key""" hash_value = int(hashlib.md5(str(shard_key).encode()).hexdigest(), 16) shard_index = hash_value % self.num_shards return self.shards[shard_index] def insert_user(self, user_id, username, email): """Insert user into appropriate shard""" shard = self.get_shard(user_id) cursor = shard.cursor() cursor.execute( "INSERT INTO users (user_id, username, email) VALUES (%s, %s, %s)", (user_id, username, email) ) shard.commit() cursor.close() def get_user(self, user_id): """Retrieve user from appropriate shard""" shard = self.get_shard(user_id) cursor = shard.cursor() cursor.execute("SELECT * FROM users WHERE user_id = %s", (user_id,)) result = cursor.fetchone() cursor.close() return result def get_all_users(self): """Query across all shards (expensive!)""" all_users = [] for shard in self.shards: cursor = shard.cursor() cursor.execute("SELECT * FROM users") all_users.extend(cursor.fetchall()) cursor.close() return all_users # Usage db = ShardedDatabase([ "postgresql://user:pass@shard1.example.com/db", "postgresql://user:pass@shard2.example.com/db", "postgresql://user:pass@shard3.example.com/db", "postgresql://user:pass@shard4.example.com/db" ]) db.insert_user(12345, "hacker", "hacker@null.com") user = db.get_user(12345) # Automatically queries correct shard

MongoDB Sharding (Built-in)

MongoDB has native sharding support through a cluster architecture with config servers, shard servers, and mongos routers.

// Enable sharding on database sh.enableSharding("mydb") // Shard a collection by hash of user_id sh.shardCollection("mydb.users", { user_id: "hashed" }) // Shard by range of created_at timestamp sh.shardCollection("mydb.posts", { created_at: 1 }) // Check sharding status sh.status() // See how data is distributed db.users.getShardDistribution() // Add a new shard to the cluster sh.addShard("rs1/mongo-shard3.example.com:27017") // Set shard tags for zone-based sharding (e.g., geographic) sh.addShardTag("shard0000", "US") sh.addShardTag("shard0001", "EU") sh.addTagRange("mydb.users", { country: "US" }, { country: "US" }, "US") sh.addTagRange("mydb.users", { country: "EU" }, { country: "EU" }, "EU")

Sharding Trade-offs

Benefits: Horizontal scalability, improved performance, geographic distribution. Costs: Increased complexity, difficult joins across shards, rebalancing challenges, distributed transactions become harder. Only shard when a single database can't handle your load.

Backup and Recovery

Data loss is catastrophic. Implement robust backup strategies and actually test your recovery proceduresβ€”an untested backup is just wishful thinking.

PostgreSQL Backup Strategies

# Logical backup with pg_dump (entire database) pg_dump -U postgres -d production_db -F c -f backup_$(date +%Y%m%d).dump # Restore from dump pg_restore -U postgres -d production_db -c backup_20260104.dump # Logical backup (single table) pg_dump -U postgres -d production_db -t users -F c -f users_backup.dump # Physical backup with pg_basebackup (entire cluster) pg_basebackup -D /backup/pg_backup -F tar -z -P # Continuous archiving (Point-in-Time Recovery) # In postgresql.conf: # archive_mode = on # archive_command = 'cp %p /archive/%f' # Create a base backup SELECT pg_start_backup('full_backup'); # Copy data directory # Then finish backup SELECT pg_stop_backup(); # Point-in-time recovery to specific timestamp restore_command = 'cp /archive/%f %p' recovery_target_time = '2026-01-04 15:30:00'

MySQL Backup Strategies

# Logical backup with mysqldump mysqldump -u root -p --all-databases --single-transaction \ --quick --lock-tables=false > full_backup_$(date +%Y%m%d).sql # Restore from dump mysql -u root -p < full_backup_20260104.sql # Backup single database mysqldump -u root -p production_db > production_backup.sql # Backup with compression mysqldump -u root -p --all-databases | gzip > backup.sql.gz # Physical backup with Percona XtraBackup (hot backup, no locks) xtrabackup --backup --target-dir=/backup/full # Incremental backup xtrabackup --backup --target-dir=/backup/inc1 \ --incremental-basedir=/backup/full # Restore XtraBackup xtrabackup --prepare --target-dir=/backup/full xtrabackup --prepare --target-dir=/backup/full \ --incremental-dir=/backup/inc1 xtrabackup --copy-back --target-dir=/backup/full

MongoDB Backup Strategies

# Mongodump (logical backup) mongodump --uri="mongodb://user:pass@localhost:27017/mydb" \ --out=/backup/mongo_$(date +%Y%m%d) # Restore with mongorestore mongorestore --uri="mongodb://user:pass@localhost:27017" \ /backup/mongo_20260104/mydb # Backup specific collection mongodump --db=mydb --collection=users --out=/backup # Cloud backup with MongoDB Atlas # Automatic point-in-time restore through Atlas UI # Filesystem snapshot (must use with --journal) db.fsyncLock() # Take filesystem snapshot db.fsyncUnlock() # Replica set backup (backup from secondary to avoid impact) # Connect to secondary, then mongodump mongodump --host=secondary.example.com:27017 --oplog

Automated Backup Script (PostgreSQL)

#!/bin/bash # backup_postgres.sh - Automated PostgreSQL backup with retention BACKUP_DIR="/backups/postgresql" DB_NAME="production_db" DB_USER="postgres" RETENTION_DAYS=30 DATE=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="$BACKUP_DIR/${DB_NAME}_${DATE}.dump" # Create backup directory if it doesn't exist mkdir -p "$BACKUP_DIR" # Perform backup echo "Starting backup of $DB_NAME..." pg_dump -U "$DB_USER" -d "$DB_NAME" -F c -f "$BACKUP_FILE" if [ $? -eq 0 ]; then echo "Backup successful: $BACKUP_FILE" # Compress backup gzip "$BACKUP_FILE" # Upload to S3 (optional) aws s3 cp "${BACKUP_FILE}.gz" s3://my-backups/postgres/ # Delete old backups find "$BACKUP_DIR" -name "*.dump.gz" -mtime +$RETENTION_DAYS -delete echo "Deleted backups older than $RETENTION_DAYS days" else echo "Backup failed!" exit 1 fi # Test restore (on test database) # pg_restore -U postgres -d test_db -c "$BACKUP_FILE"

3-2-1 Backup Rule

Keep 3 copies of your data (original + 2 backups), on 2 different types of media (e.g., disk + tape, or local + cloud), with 1 copy offsite. Also: test your restores regularly. A backup you can't restore is useless.

Database Security Best Practices

Databases hold your most valuable asset: data. One breach can destroy your company. Security isn't optional.

Authentication and Access Control

-- PostgreSQL: Create users with minimal privileges CREATE ROLE app_readonly WITH LOGIN PASSWORD 'strong_pass'; GRANT CONNECT ON DATABASE production_db TO app_readonly; GRANT USAGE ON SCHEMA public TO app_readonly; GRANT SELECT ON ALL TABLES IN SCHEMA public TO app_readonly; -- Automatically grant SELECT on future tables ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO app_readonly; -- Create application user with limited write access CREATE ROLE app_user WITH LOGIN PASSWORD 'secure_password'; GRANT CONNECT ON DATABASE production_db TO app_user; GRANT USAGE ON SCHEMA public TO app_user; GRANT SELECT, INSERT, UPDATE ON specific_table TO app_user; -- No DELETE permission = can't accidentally drop data -- Remove privileges REVOKE DELETE ON users FROM app_user; -- MySQL: Similar approach CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'strong_password'; GRANT SELECT, INSERT, UPDATE ON production_db.* TO 'app_user'@'localhost'; FLUSH PRIVILEGES; -- MongoDB: Role-based access control use admin db.createUser({ user: "app_user", pwd: "secure_password", roles: [ { role: "readWrite", db: "production_db" }, { role: "read", db: "analytics_db" } ] })

Encryption

-- PostgreSQL: Encrypt connections (postgresql.conf) ssl = on ssl_cert_file = '/path/to/server.crt' ssl_key_file = '/path/to/server.key' ssl_ca_file = '/path/to/ca.crt' -- Require SSL for specific users ALTER USER app_user SET ssl TO on; -- MySQL: Require SSL connections CREATE USER 'secure_user'@'%' IDENTIFIED BY 'password' REQUIRE SSL; -- MongoDB: Enable encryption at rest (Enterprise) security: enableEncryption: true encryptionKeyFile: /path/to/keyfile -- Application-level encryption (sensitive columns) -- Encrypt before storing from cryptography.fernet import Fernet key = Fernet.generate_key() # Store this securely, not in code! cipher = Fernet(key) # Encrypt sensitive data credit_card = "4532-1234-5678-9010" encrypted_cc = cipher.encrypt(credit_card.encode()) # Store encrypted_cc in database cursor.execute( "INSERT INTO payments (user_id, encrypted_cc) VALUES (%s, %s)", (user_id, encrypted_cc) ) # Decrypt when needed decrypted_cc = cipher.decrypt(encrypted_cc).decode()

SQL Injection Prevention

# NEVER DO THIS (Vulnerable to SQL injection) username = request.form['username'] query = f"SELECT * FROM users WHERE username = '{username}'" cursor.execute(query) # Attacker inputs: ' OR '1'='1' -- # Query becomes: SELECT * FROM users WHERE username = '' OR '1'='1' --' # Returns all users! # ALWAYS USE PARAMETERIZED QUERIES username = request.form['username'] cursor.execute("SELECT * FROM users WHERE username = %s", (username,)) # Python with SQLAlchemy (automatically parameterized) from sqlalchemy import text username = request.form['username'] result = session.execute( text("SELECT * FROM users WHERE username = :username"), {"username": username} ) # Node.js with parameterized queries const username = req.body.username; // Safe with placeholders connection.query( 'SELECT * FROM users WHERE username = ?', [username], (error, results) => { /* ... */ } ); # MongoDB: Use proper query objects (not string concatenation) # VULNERABLE: username = request.form['username'] db.users.find({ "$where": f"this.username == '{username}'" }) # SAFE: username = request.form['username'] db.users.find_one({ "username": username })

Network Security

# PostgreSQL: Restrict connections by IP (pg_hba.conf) # Allow only application servers to connect host all app_user 10.0.1.0/24 md5 host all all 127.0.0.1/32 md5 # Deny everything else (implicit) # MySQL: Bind to specific interface (my.cnf) bind-address = 10.0.1.5 # Only listen on internal network # Use firewall rules # Allow only application servers to reach database port sudo ufw allow from 10.0.1.0/24 to any port 5432 sudo ufw deny 5432 # Deny from everywhere else # MongoDB: Bind to internal IP # In mongod.conf: net: bindIp: 127.0.0.1,10.0.1.5 port: 27017 # Enable authentication security: authorization: enabled

Principle of Least Privilege

Every user, application, and process should have only the minimum permissions required to do its job. Your application doesn't need DROP DATABASE privileges. Your read-only analytics tool doesn't need INSERT access. Restrict everything by default.

Monitoring and Performance Tuning

You can't fix what you can't measure. Monitor your databases continuously to catch problems before they become disasters.

Key Metrics to Monitor

Query Performance

Slow query log, average query time, queries per second, long-running queries. Identify and optimize slow queries immediately.

Connection Pool

Active connections, max connections, connection wait time. Running out of connections causes service outages.

Disk I/O

Disk utilization, read/write throughput, IOPS. Disk is often the bottleneck in database performance.

Replication Lag

Delay between master and slaves. High lag means reads from replicas return stale data.

Cache Hit Ratio

Percentage of queries served from memory vs disk. Higher is betterβ€”aim for >99%.

Error Rates

Failed queries, deadlocks, connection errors. Sudden spikes indicate problems.

PostgreSQL Monitoring

-- Enable slow query logging (postgresql.conf) log_min_duration_statement = 1000 # Log queries taking >1 second log_line_prefix = '%t [%p]: [%l-1] user=%u,db=%d,app=%a,client=%h ' log_statement = 'all' # Or 'ddl' / 'mod' / 'none' -- View current activity SELECT pid, usename, application_name, client_addr, state, query FROM pg_stat_activity WHERE state = 'active'; -- Find slow queries SELECT query, mean_exec_time, calls FROM pg_stat_statements ORDER BY mean_exec_time DESC LIMIT 10; -- Check table bloat SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) FROM pg_tables ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC; -- Cache hit ratio (should be >99%) SELECT sum(heap_blks_read) as heap_read, sum(heap_blks_hit) as heap_hit, sum(heap_blks_hit) / (sum(heap_blks_hit) + sum(heap_blks_read)) as ratio FROM pg_statio_user_tables; -- Index usage statistics SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch FROM pg_stat_user_indexes ORDER BY idx_scan ASC; -- Low idx_scan = unused index -- Kill long-running query SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query_start < now() - interval '1 hour';

MySQL Monitoring

-- Enable slow query log (my.cnf) slow_query_log = 1 slow_query_log_file = /var/log/mysql/slow.log long_query_time = 1 -- View current queries SHOW FULL PROCESSLIST; -- Kill long-running query KILL ; -- Query cache hit rate SHOW STATUS LIKE 'Qcache%'; -- Calculate: Qcache_hits / (Qcache_hits + Qcache_inserts) -- InnoDB buffer pool hit rate SHOW STATUS LIKE 'Innodb_buffer_pool%'; -- Calculate: (Innodb_buffer_pool_read_requests - Innodb_buffer_pool_reads) -- / Innodb_buffer_pool_read_requests -- Table sizes SELECT table_schema, table_name, ROUND(data_length / 1024 / 1024, 2) AS data_mb, ROUND(index_length / 1024 / 1024, 2) AS index_mb FROM information_schema.tables ORDER BY (data_length + index_length) DESC LIMIT 10; -- Unused indexes SELECT * FROM sys.schema_unused_indexes;

MongoDB Monitoring

// Enable profiling for slow queries db.setProfilingLevel(1, { slowms: 100 }) // Log queries >100ms // View current operations db.currentOp() // Kill long-running operation db.killOp() // Database statistics db.stats() // Collection statistics db.users.stats() // Find slow queries in system.profile db.system.profile.find({ millis: { $gt: 1000 } }).sort({ ts: -1 }).limit(10) // Replication lag rs.printSlaveReplicationInfo() // Connection statistics db.serverStatus().connections // Check index usage db.users.aggregate([ { $indexStats: {} } ])

Monitoring with Prometheus + Grafana

Industry-standard monitoring stack. Exporters collect database metrics, Prometheus stores them, Grafana visualizes.

# PostgreSQL exporter for Prometheus docker run -d \ -p 9187:9187 \ -e DATA_SOURCE_NAME="postgresql://user:pass@postgres:5432/db?sslmode=disable" \ prometheuscommunity/postgres-exporter # MySQL exporter docker run -d \ -p 9104:9104 \ -e DATA_SOURCE_NAME="user:pass@(mysql:3306)/" \ prom/mysqld-exporter # MongoDB exporter docker run -d \ -p 9216:9216 \ -e MONGODB_URI="mongodb://user:pass@mongo:27017" \ percona/mongodb_exporter # Prometheus scrape config (prometheus.yml) scrape_configs: - job_name: 'postgresql' static_configs: - targets: ['postgres-exporter:9187'] - job_name: 'mysql' static_configs: - targets: ['mysql-exporter:9104'] - job_name: 'mongodb' static_configs: - targets: ['mongo-exporter:9216'] # Alert rules (alerts.yml) groups: - name: database_alerts rules: - alert: HighDatabaseConnections expr: pg_stat_database_numbackends > 80 for: 5m annotations: summary: "High number of database connections" - alert: SlowQuery expr: pg_stat_statements_mean_exec_time > 5000 annotations: summary: "Slow query detected (>5s avg)" - alert: ReplicationLag expr: pg_replication_lag_seconds > 60 for: 5m annotations: summary: "Replication lag >60 seconds"

Application-Level Monitoring (Python)

import time import logging from functools import wraps logger = logging.getLogger(__name__) def monitor_query(func): """Decorator to monitor query execution time""" @wraps(func) def wrapper(*args, **kwargs): start_time = time.time() try: result = func(*args, **kwargs) execution_time = time.time() - start_time if execution_time > 1.0: # Log slow queries logger.warning( f"Slow query in {func.__name__}: {execution_time:.2f}s" ) # Send to monitoring system (e.g., Prometheus, DataDog) # metrics.histogram('db.query.duration', execution_time, # tags=[f'function:{func.__name__}']) return result except Exception as e: logger.error(f"Query failed in {func.__name__}: {e}") # metrics.increment('db.query.errors', # tags=[f'function:{func.__name__}']) raise return wrapper @monitor_query def get_user_orders(user_id): cursor.execute( "SELECT * FROM orders WHERE user_id = %s ORDER BY created_at DESC", (user_id,) ) return cursor.fetchall() # Usage automatically logs slow queries orders = get_user_orders(12345)
Metaphor: Database monitoring is like having a car's dashboard. You need to constantly watch your speed (queries per second), fuel level (disk space), engine temperature (CPU usage), and warning lights (error logs). Ignoring the dashboard means you'll break down on the highway at the worst possible time.

Performance Tuning Checklist

  • Indexes: Add indexes on frequently queried columns, but don't over-index (slows writes)
  • Query optimization: Use EXPLAIN to analyze query plans, avoid SELECT *, use JOINs wisely
  • Connection pooling: Reuse connections instead of creating new ones for each request
  • Caching: Cache frequent queries in Redis/Memcached to reduce database load
  • Batch operations: Insert/update multiple rows at once instead of one-by-one
  • Archive old data: Move historical data to separate tables/databases
  • Vertical scaling: Add more RAM (increases cache hit ratio), faster disks (SSDs)
  • Horizontal scaling: Read replicas for read-heavy workloads, sharding for write-heavy

Real-World Patterns

Blue-Green Deployment for Database Migrations

Deploy schema changes with zero downtime by maintaining two identical environments.

# Strategy for zero-downtime migrations: # 1. Make changes backward-compatible first # BAD: Can't roll back if something breaks ALTER TABLE users DROP COLUMN legacy_field; # GOOD: Multi-step approach # Step 1: Stop writing to legacy_field (deploy app v1.1) # Step 2: Deploy for a week, verify no issues # Step 3: Drop the column (deploy app v1.2) ALTER TABLE users DROP COLUMN legacy_field; # Adding a NOT NULL column safely: # Step 1: Add column as nullable with default ALTER TABLE users ADD COLUMN new_field VARCHAR(255) DEFAULT 'default_value'; # Step 2: Backfill existing rows UPDATE users SET new_field = 'calculated_value' WHERE new_field IS NULL; # Step 3: Deploy app to use new_field # Step 4: Make it NOT NULL after everything is working ALTER TABLE users ALTER COLUMN new_field SET NOT NULL;

Circuit Breaker Pattern for Database Resilience

class DatabaseCircuitBreaker: def __init__(self, failure_threshold=5, timeout=60): self.failure_count = 0 self.failure_threshold = failure_threshold self.timeout = timeout self.last_failure_time = None self.state = "CLOSED" # CLOSED, OPEN, HALF_OPEN def call(self, func, *args, **kwargs): if self.state == "OPEN": if time.time() - self.last_failure_time > self.timeout: self.state = "HALF_OPEN" else: raise Exception("Circuit breaker is OPEN") try: result = func(*args, **kwargs) if self.state == "HALF_OPEN": self.state = "CLOSED" self.failure_count = 0 return result except Exception as e: self.failure_count += 1 self.last_failure_time = time.time() if self.failure_count >= self.failure_threshold: self.state = "OPEN" raise e # Usage circuit_breaker = DatabaseCircuitBreaker() def query_database(): return circuit_breaker.call( cursor.execute, "SELECT * FROM users WHERE id = %s", (user_id,) )

You now have the advanced database skills used in production systems at scale. Replication, sharding, backups, security, and monitoring aren't optionalβ€”they're the difference between a toy project and a real system that handles millions of users without falling over.

Real Projects

Theory means nothing without practice. Build complete database-driven applications that demonstrate your masteryβ€”from data modeling to query optimization to production deployment.

Project 1: Social Media Platform Database

Design and implement a complete social media database schema supporting users, posts, comments, likes, follows, messages, notifications, stories, hashtags, and media.

Schema Design (10 Tables)

-- Users table: Core user data CREATE TABLE users ( user_id BIGSERIAL PRIMARY KEY, username VARCHAR(50) UNIQUE NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, full_name VARCHAR(100), bio TEXT, profile_image_url VARCHAR(500), is_verified BOOLEAN DEFAULT false, is_private BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, last_login TIMESTAMP, INDEX idx_username (username), INDEX idx_email (email) ); -- Posts table: User-generated content CREATE TABLE posts ( post_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, caption TEXT, media_type ENUM('image', 'video', 'carousel') NOT NULL, media_urls TEXT[], -- Array of media URLs location VARCHAR(255), is_archived BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, INDEX idx_user_created (user_id, created_at DESC), INDEX idx_created (created_at DESC) ); -- Comments table: Post comments CREATE TABLE comments ( comment_id BIGSERIAL PRIMARY KEY, post_id BIGINT NOT NULL, user_id BIGINT NOT NULL, parent_comment_id BIGINT, -- For threaded comments comment_text TEXT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (post_id) REFERENCES posts(post_id) ON DELETE CASCADE, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, FOREIGN KEY (parent_comment_id) REFERENCES comments(comment_id) ON DELETE CASCADE, INDEX idx_post_created (post_id, created_at DESC), INDEX idx_user (user_id) ); -- Likes table: Post and comment likes CREATE TABLE likes ( like_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, likeable_type ENUM('post', 'comment') NOT NULL, likeable_id BIGINT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, UNIQUE KEY unique_like (user_id, likeable_type, likeable_id), INDEX idx_likeable (likeable_type, likeable_id, created_at DESC) ); -- Follows table: User relationships CREATE TABLE follows ( follow_id BIGSERIAL PRIMARY KEY, follower_id BIGINT NOT NULL, following_id BIGINT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (follower_id) REFERENCES users(user_id) ON DELETE CASCADE, FOREIGN KEY (following_id) REFERENCES users(user_id) ON DELETE CASCADE, UNIQUE KEY unique_follow (follower_id, following_id), INDEX idx_follower (follower_id), INDEX idx_following (following_id) ); -- Messages table: Direct messages CREATE TABLE messages ( message_id BIGSERIAL PRIMARY KEY, sender_id BIGINT NOT NULL, recipient_id BIGINT NOT NULL, message_text TEXT NOT NULL, media_url VARCHAR(500), is_read BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (sender_id) REFERENCES users(user_id) ON DELETE CASCADE, FOREIGN KEY (recipient_id) REFERENCES users(user_id) ON DELETE CASCADE, INDEX idx_conversation (sender_id, recipient_id, created_at DESC), INDEX idx_unread (recipient_id, is_read, created_at) ); -- Notifications table: User notifications CREATE TABLE notifications ( notification_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, actor_id BIGINT NOT NULL, -- Who triggered the notification notification_type ENUM('like', 'comment', 'follow', 'mention', 'message') NOT NULL, related_id BIGINT, -- Post/comment/message ID is_read BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, FOREIGN KEY (actor_id) REFERENCES users(user_id) ON DELETE CASCADE, INDEX idx_user_unread (user_id, is_read, created_at DESC) ); -- Stories table: Temporary 24-hour content CREATE TABLE stories ( story_id BIGSERIAL PRIMARY KEY, user_id BIGINT NOT NULL, media_url VARCHAR(500) NOT NULL, media_type ENUM('image', 'video') NOT NULL, expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE, INDEX idx_user_active (user_id, expires_at DESC), INDEX idx_expires (expires_at) ); -- Hashtags table: Post hashtags CREATE TABLE hashtags ( hashtag_id BIGSERIAL PRIMARY KEY, tag VARCHAR(100) UNIQUE NOT NULL, post_count BIGINT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_tag (tag), INDEX idx_popular (post_count DESC) ); -- Post_hashtags junction table CREATE TABLE post_hashtags ( post_id BIGINT NOT NULL, hashtag_id BIGINT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (post_id, hashtag_id), FOREIGN KEY (post_id) REFERENCES posts(post_id) ON DELETE CASCADE, FOREIGN KEY (hashtag_id) REFERENCES hashtags(hashtag_id) ON DELETE CASCADE, INDEX idx_hashtag_created (hashtag_id, created_at DESC) );

Python Implementation

import psycopg2 from psycopg2.extras import RealDictCursor from datetime import datetime, timedelta from typing import List, Dict, Optional class SocialMediaDB: def __init__(self, connection_string: str): self.conn = psycopg2.connect(connection_string) def create_user(self, username: str, email: str, password_hash: str, full_name: str = None, bio: str = None) -> int: """Create a new user account""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO users (username, email, password_hash, full_name, bio) VALUES (%s, %s, %s, %s, %s) RETURNING user_id """, (username, email, password_hash, full_name, bio)) user_id = cur.fetchone()[0] self.conn.commit() return user_id def create_post(self, user_id: int, media_type: str, media_urls: List[str], caption: str = None, location: str = None) -> int: """Create a new post""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO posts (user_id, media_type, media_urls, caption, location) VALUES (%s, %s, %s, %s, %s) RETURNING post_id """, (user_id, media_type, media_urls, caption, location)) post_id = cur.fetchone()[0] self.conn.commit() return post_id def get_feed(self, user_id: int, limit: int = 50, offset: int = 0) -> List[Dict]: """Get user's personalized feed (posts from followed users)""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT p.post_id, p.caption, p.media_urls, p.created_at, u.user_id, u.username, u.profile_image_url, COUNT(DISTINCT l.like_id) as like_count, COUNT(DISTINCT c.comment_id) as comment_count, EXISTS( SELECT 1 FROM likes WHERE user_id = %s AND likeable_type = 'post' AND likeable_id = p.post_id ) as user_has_liked FROM posts p JOIN users u ON p.user_id = u.user_id JOIN follows f ON p.user_id = f.following_id LEFT JOIN likes l ON p.post_id = l.likeable_id AND l.likeable_type = 'post' LEFT JOIN comments c ON p.post_id = c.post_id WHERE f.follower_id = %s AND p.is_archived = false GROUP BY p.post_id, u.user_id ORDER BY p.created_at DESC LIMIT %s OFFSET %s """, (user_id, user_id, limit, offset)) return cur.fetchall() def follow_user(self, follower_id: int, following_id: int) -> bool: """Follow another user""" try: with self.conn.cursor() as cur: cur.execute(""" INSERT INTO follows (follower_id, following_id) VALUES (%s, %s) ON CONFLICT (follower_id, following_id) DO NOTHING """, (follower_id, following_id)) # Create notification cur.execute(""" INSERT INTO notifications (user_id, actor_id, notification_type) VALUES (%s, %s, 'follow') """, (following_id, follower_id)) self.conn.commit() return True except Exception as e: self.conn.rollback() print(f"Error following user: {e}") return False def like_post(self, user_id: int, post_id: int) -> bool: """Like a post""" try: with self.conn.cursor() as cur: # Add like cur.execute(""" INSERT INTO likes (user_id, likeable_type, likeable_id) VALUES (%s, 'post', %s) ON CONFLICT (user_id, likeable_type, likeable_id) DO NOTHING """, (user_id, post_id)) # Get post owner for notification cur.execute("SELECT user_id FROM posts WHERE post_id = %s", (post_id,)) post_owner = cur.fetchone()[0] if post_owner != user_id: # Don't notify self cur.execute(""" INSERT INTO notifications (user_id, actor_id, notification_type, related_id) VALUES (%s, %s, 'like', %s) """, (post_owner, user_id, post_id)) self.conn.commit() return True except Exception as e: self.conn.rollback() print(f"Error liking post: {e}") return False def add_comment(self, user_id: int, post_id: int, comment_text: str, parent_comment_id: Optional[int] = None) -> Optional[int]: """Add comment to post (supports threaded comments)""" try: with self.conn.cursor() as cur: cur.execute(""" INSERT INTO comments (user_id, post_id, comment_text, parent_comment_id) VALUES (%s, %s, %s, %s) RETURNING comment_id """, (user_id, post_id, comment_text, parent_comment_id)) comment_id = cur.fetchone()[0] # Notify post owner cur.execute("SELECT user_id FROM posts WHERE post_id = %s", (post_id,)) post_owner = cur.fetchone()[0] if post_owner != user_id: cur.execute(""" INSERT INTO notifications (user_id, actor_id, notification_type, related_id) VALUES (%s, %s, 'comment', %s) """, (post_owner, user_id, post_id)) self.conn.commit() return comment_id except Exception as e: self.conn.rollback() print(f"Error adding comment: {e}") return None def get_trending_hashtags(self, limit: int = 10) -> List[Dict]: """Get trending hashtags""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT tag, post_count FROM hashtags ORDER BY post_count DESC LIMIT %s """, (limit,)) return cur.fetchall() def search_users(self, query: str, limit: int = 20) -> List[Dict]: """Search users by username or full name""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT user_id, username, full_name, profile_image_url, is_verified FROM users WHERE username ILIKE %s OR full_name ILIKE %s LIMIT %s """, (f"%{query}%", f"%{query}%", limit)) return cur.fetchall() def get_user_stats(self, user_id: int) -> Dict: """Get user statistics (posts, followers, following)""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT (SELECT COUNT(*) FROM posts WHERE user_id = %s AND is_archived = false) as post_count, (SELECT COUNT(*) FROM follows WHERE following_id = %s) as follower_count, (SELECT COUNT(*) FROM follows WHERE follower_id = %s) as following_count """, (user_id, user_id, user_id)) return cur.fetchone() # Usage example db = SocialMediaDB("postgresql://user:pass@localhost/social_db") # Create users alice_id = db.create_user("alice", "alice@example.com", "hash123", "Alice Smith") bob_id = db.create_user("bob", "bob@example.com", "hash456", "Bob Jones") # Alice follows Bob db.follow_user(alice_id, bob_id) # Bob creates post post_id = db.create_post(bob_id, "image", ["https://cdn.example.com/img1.jpg"], caption="Beautiful sunset! #nature #photography") # Alice likes and comments on Bob's post db.like_post(alice_id, post_id) db.add_comment(alice_id, post_id, "Amazing shot! πŸ“Έ") # Get Alice's personalized feed feed = db.get_feed(alice_id) for post in feed: print(f"{post['username']}: {post['caption']} ({post['like_count']} likes)") # Get trending hashtags trending = db.get_trending_hashtags() print("Trending:", [tag['tag'] for tag in trending])

Project 2: Analytics & Metrics Platform

Build an analytics platform that tracks website/app events, user sessions, conversions, and generates real-time reports. Handles millions of events per day.

Schema Design (8 Tables)

-- Events table: Core event tracking CREATE TABLE events ( event_id BIGSERIAL PRIMARY KEY, session_id VARCHAR(100) NOT NULL, user_id BIGINT, event_type VARCHAR(100) NOT NULL, event_properties JSONB, page_url TEXT, referrer_url TEXT, user_agent TEXT, ip_address INET, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_session_created (session_id, created_at), INDEX idx_user_created (user_id, created_at), INDEX idx_type_created (event_type, created_at), INDEX idx_created (created_at DESC) ) PARTITION BY RANGE (created_at); -- Partitions for time-series data CREATE TABLE events_2026_01 PARTITION OF events FOR VALUES FROM ('2026-01-01') TO ('2026-02-01'); -- Sessions table: User sessions CREATE TABLE sessions ( session_id VARCHAR(100) PRIMARY KEY, user_id BIGINT, device_type ENUM('desktop', 'mobile', 'tablet') NOT NULL, browser VARCHAR(50), os VARCHAR(50), country VARCHAR(2), city VARCHAR(100), started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, ended_at TIMESTAMP, page_views INT DEFAULT 0, duration_seconds INT, INDEX idx_user_started (user_id, started_at DESC), INDEX idx_started (started_at DESC) ); -- Page_views table: Page analytics CREATE TABLE page_views ( view_id BIGSERIAL PRIMARY KEY, session_id VARCHAR(100) NOT NULL, page_url TEXT NOT NULL, page_title VARCHAR(500), time_on_page INT, -- seconds scroll_depth INT, -- percentage created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_session (session_id), INDEX idx_page_created (page_url, created_at), INDEX idx_created (created_at DESC) ) PARTITION BY RANGE (created_at); -- Conversions table: Goal completions CREATE TABLE conversions ( conversion_id BIGSERIAL PRIMARY KEY, session_id VARCHAR(100) NOT NULL, user_id BIGINT, goal_type VARCHAR(100) NOT NULL, goal_value DECIMAL(10, 2), properties JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_session (session_id), INDEX idx_user (user_id), INDEX idx_goal_created (goal_type, created_at) ); -- Funnels table: Conversion funnel definitions CREATE TABLE funnels ( funnel_id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, steps JSONB NOT NULL, -- Array of step definitions created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Funnel_steps table: Track user progress through funnels CREATE TABLE funnel_steps ( step_id BIGSERIAL PRIMARY KEY, funnel_id INT NOT NULL, session_id VARCHAR(100) NOT NULL, step_number INT NOT NULL, completed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (funnel_id) REFERENCES funnels(funnel_id) ON DELETE CASCADE, INDEX idx_funnel_session (funnel_id, session_id, step_number) ); -- Daily_metrics table: Pre-aggregated daily stats CREATE TABLE daily_metrics ( metric_date DATE NOT NULL, metric_type VARCHAR(100) NOT NULL, metric_key VARCHAR(255), -- e.g., page URL, event type metric_value BIGINT NOT NULL, PRIMARY KEY (metric_date, metric_type, metric_key), INDEX idx_date_type (metric_date DESC, metric_type) ); -- Real_time_metrics table: Live dashboard data (TTL 1 hour) CREATE TABLE real_time_metrics ( metric_id BIGSERIAL PRIMARY KEY, metric_type VARCHAR(100) NOT NULL, metric_value BIGINT NOT NULL, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_type_updated (metric_type, updated_at DESC) );

Python Implementation

import psycopg2 from psycopg2.extras import RealDictCursor, Json from datetime import datetime, timedelta from typing import Dict, List, Optional import json class AnalyticsDB: def __init__(self, connection_string: str): self.conn = psycopg2.connect(connection_string) def track_event(self, session_id: str, event_type: str, user_id: Optional[int] = None, properties: Dict = None, page_url: str = None, referrer_url: str = None, user_agent: str = None, ip_address: str = None): """Track an analytics event""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO events (session_id, user_id, event_type, event_properties, page_url, referrer_url, user_agent, ip_address) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) """, (session_id, user_id, event_type, Json(properties or {}), page_url, referrer_url, user_agent, ip_address)) self.conn.commit() def create_session(self, session_id: str, device_type: str, browser: str, os: str, country: str = None, city: str = None, user_id: Optional[int] = None) -> str: """Create a new user session""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO sessions (session_id, user_id, device_type, browser, os, country, city) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (session_id) DO NOTHING """, (session_id, user_id, device_type, browser, os, country, city)) self.conn.commit() return session_id def track_page_view(self, session_id: str, page_url: str, page_title: str = None, time_on_page: int = None, scroll_depth: int = None): """Track a page view""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO page_views (session_id, page_url, page_title, time_on_page, scroll_depth) VALUES (%s, %s, %s, %s, %s) """, (session_id, page_url, page_title, time_on_page, scroll_depth)) # Update session page view count cur.execute(""" UPDATE sessions SET page_views = page_views + 1 WHERE session_id = %s """, (session_id,)) self.conn.commit() def track_conversion(self, session_id: str, goal_type: str, goal_value: float = None, properties: Dict = None, user_id: Optional[int] = None): """Track a conversion/goal completion""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO conversions (session_id, user_id, goal_type, goal_value, properties) VALUES (%s, %s, %s, %s, %s) """, (session_id, user_id, goal_type, goal_value, Json(properties or {}))) self.conn.commit() def get_daily_stats(self, start_date: str, end_date: str) -> Dict: """Get daily statistics for date range""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT DATE(created_at) as date, COUNT(DISTINCT session_id) as sessions, COUNT(*) as events, COUNT(DISTINCT user_id) as unique_users FROM events WHERE created_at >= %s AND created_at < %s GROUP BY DATE(created_at) ORDER BY date """, (start_date, end_date)) return cur.fetchall() def get_top_pages(self, limit: int = 10, days: int = 7) -> List[Dict]: """Get most viewed pages""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT page_url, COUNT(*) as view_count, AVG(time_on_page) as avg_time, AVG(scroll_depth) as avg_scroll_depth FROM page_views WHERE created_at >= NOW() - INTERVAL '%s days' GROUP BY page_url ORDER BY view_count DESC LIMIT %s """, (days, limit)) return cur.fetchall() def get_traffic_sources(self, days: int = 7) -> List[Dict]: """Analyze traffic sources (referrers)""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT CASE WHEN referrer_url IS NULL THEN 'Direct' WHEN referrer_url LIKE '%%google.com%%' THEN 'Google' WHEN referrer_url LIKE '%%facebook.com%%' THEN 'Facebook' WHEN referrer_url LIKE '%%twitter.com%%' THEN 'Twitter' ELSE 'Other' END as source, COUNT(DISTINCT session_id) as sessions, COUNT(*) as events FROM events WHERE created_at >= NOW() - INTERVAL '%s days' GROUP BY source ORDER BY sessions DESC """, (days,)) return cur.fetchall() def get_device_breakdown(self, days: int = 7) -> List[Dict]: """Get device type distribution""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT device_type, COUNT(*) as session_count, AVG(page_views) as avg_page_views, AVG(duration_seconds) as avg_duration FROM sessions WHERE started_at >= NOW() - INTERVAL '%s days' GROUP BY device_type ORDER BY session_count DESC """, (days,)) return cur.fetchall() def get_conversion_rate(self, goal_type: str, days: int = 7) -> Dict: """Calculate conversion rate for specific goal""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" WITH session_counts AS ( SELECT COUNT(DISTINCT session_id) as total_sessions FROM sessions WHERE started_at >= NOW() - INTERVAL '%s days' ), conversion_counts AS ( SELECT COUNT(DISTINCT session_id) as converted_sessions FROM conversions WHERE goal_type = %s AND created_at >= NOW() - INTERVAL '%s days' ) SELECT total_sessions, converted_sessions, ROUND((converted_sessions::DECIMAL / total_sessions * 100), 2) as conversion_rate FROM session_counts, conversion_counts """, (days, goal_type, days)) return cur.fetchone() def create_funnel(self, name: str, steps: List[Dict]) -> int: """Create conversion funnel""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO funnels (name, steps) VALUES (%s, %s) RETURNING funnel_id """, (name, Json(steps))) funnel_id = cur.fetchone()[0] self.conn.commit() return funnel_id def analyze_funnel(self, funnel_id: int, days: int = 7) -> List[Dict]: """Analyze funnel drop-off rates""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT step_number, COUNT(DISTINCT session_id) as users, COUNT(DISTINCT session_id) * 100.0 / FIRST_VALUE(COUNT(DISTINCT session_id)) OVER (ORDER BY step_number) as retention_rate FROM funnel_steps WHERE funnel_id = %s AND completed_at >= NOW() - INTERVAL '%s days' GROUP BY step_number ORDER BY step_number """, (funnel_id, days)) return cur.fetchall() def get_real_time_active_users(self, minutes: int = 5) -> int: """Get active users in last N minutes""" with self.conn.cursor() as cur: cur.execute(""" SELECT COUNT(DISTINCT session_id) FROM events WHERE created_at >= NOW() - INTERVAL '%s minutes' """, (minutes,)) return cur.fetchone()[0] def aggregate_daily_metrics(self, date: str): """Pre-aggregate metrics for faster reporting (run daily via cron)""" with self.conn.cursor() as cur: # Aggregate page views by page cur.execute(""" INSERT INTO daily_metrics (metric_date, metric_type, metric_key, metric_value) SELECT %s::DATE, 'page_views', page_url, COUNT(*) FROM page_views WHERE DATE(created_at) = %s::DATE GROUP BY page_url ON CONFLICT (metric_date, metric_type, metric_key) DO UPDATE SET metric_value = EXCLUDED.metric_value """, (date, date)) # Aggregate events by type cur.execute(""" INSERT INTO daily_metrics (metric_date, metric_type, metric_key, metric_value) SELECT %s::DATE, 'events', event_type, COUNT(*) FROM events WHERE DATE(created_at) = %s::DATE GROUP BY event_type ON CONFLICT (metric_date, metric_type, metric_key) DO UPDATE SET metric_value = EXCLUDED.metric_value """, (date, date)) self.conn.commit() # Usage example analytics = AnalyticsDB("postgresql://user:pass@localhost/analytics_db") # Track user session and events session_id = analytics.create_session("sess_12345", "desktop", "Chrome", "Windows", "US", "New York") analytics.track_page_view(session_id, "/home", "Homepage", time_on_page=45, scroll_depth=80) analytics.track_event(session_id, "button_click", properties={"button_id": "signup"}) analytics.track_conversion(session_id, "signup", goal_value=0) # Get analytics reports daily_stats = analytics.get_daily_stats("2026-01-01", "2026-01-07") print("Daily stats:", daily_stats) top_pages = analytics.get_top_pages(limit=5) print("Top pages:", [(p['page_url'], p['view_count']) for p in top_pages]) conversion_rate = analytics.get_conversion_rate("signup", days=7) print(f"Signup conversion rate: {conversion_rate['conversion_rate']}%") # Real-time metrics active_users = analytics.get_real_time_active_users(minutes=5) print(f"Active users (last 5 min): {active_users}")

Project 3: Content Management System (CMS)

Design a flexible CMS supporting multiple content types, versioning, media library, categories, tags, roles/permissions, and multi-language content.

Schema Design (12 Tables)

-- Users table: System users CREATE TABLE users ( user_id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, password_hash VARCHAR(255) NOT NULL, first_name VARCHAR(100), last_name VARCHAR(100), role_id INT NOT NULL, is_active BOOLEAN DEFAULT true, last_login TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_email (email), INDEX idx_role (role_id) ); -- Roles table: User roles (admin, editor, author, etc.) CREATE TABLE roles ( role_id SERIAL PRIMARY KEY, role_name VARCHAR(50) UNIQUE NOT NULL, permissions JSONB NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Content_types table: Define custom content types CREATE TABLE content_types ( type_id SERIAL PRIMARY KEY, type_name VARCHAR(100) UNIQUE NOT NULL, fields JSONB NOT NULL, -- Field definitions created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Content table: Main content storage CREATE TABLE content ( content_id BIGSERIAL PRIMARY KEY, type_id INT NOT NULL, slug VARCHAR(255) UNIQUE NOT NULL, status ENUM('draft', 'published', 'archived') DEFAULT 'draft', author_id INT NOT NULL, published_at TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (type_id) REFERENCES content_types(type_id), FOREIGN KEY (author_id) REFERENCES users(user_id), INDEX idx_type_status (type_id, status), INDEX idx_author (author_id), INDEX idx_slug (slug), INDEX idx_published (published_at DESC) ); -- Content_versions table: Version control for content CREATE TABLE content_versions ( version_id BIGSERIAL PRIMARY KEY, content_id BIGINT NOT NULL, version_number INT NOT NULL, data JSONB NOT NULL, -- All content fields as JSON author_id INT NOT NULL, change_summary TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (content_id) REFERENCES content(content_id) ON DELETE CASCADE, FOREIGN KEY (author_id) REFERENCES users(user_id), UNIQUE (content_id, version_number), INDEX idx_content_version (content_id, version_number DESC) ); -- Translations table: Multi-language support CREATE TABLE translations ( translation_id BIGSERIAL PRIMARY KEY, content_id BIGINT NOT NULL, language_code VARCHAR(5) NOT NULL, -- en, es, fr, etc. data JSONB NOT NULL, is_published BOOLEAN DEFAULT false, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (content_id) REFERENCES content(content_id) ON DELETE CASCADE, UNIQUE (content_id, language_code), INDEX idx_content_lang (content_id, language_code) ); -- Categories table: Hierarchical categories CREATE TABLE categories ( category_id SERIAL PRIMARY KEY, parent_id INT, name VARCHAR(255) NOT NULL, slug VARCHAR(255) UNIQUE NOT NULL, description TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (parent_id) REFERENCES categories(category_id) ON DELETE CASCADE, INDEX idx_parent (parent_id), INDEX idx_slug (slug) ); -- Content_categories junction table CREATE TABLE content_categories ( content_id BIGINT NOT NULL, category_id INT NOT NULL, PRIMARY KEY (content_id, category_id), FOREIGN KEY (content_id) REFERENCES content(content_id) ON DELETE CASCADE, FOREIGN KEY (category_id) REFERENCES categories(category_id) ON DELETE CASCADE, INDEX idx_category (category_id) ); -- Tags table: Flat tagging system CREATE TABLE tags ( tag_id SERIAL PRIMARY KEY, name VARCHAR(100) UNIQUE NOT NULL, slug VARCHAR(100) UNIQUE NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_name (name), INDEX idx_slug (slug) ); -- Content_tags junction table CREATE TABLE content_tags ( content_id BIGINT NOT NULL, tag_id INT NOT NULL, PRIMARY KEY (content_id, tag_id), FOREIGN KEY (content_id) REFERENCES content(content_id) ON DELETE CASCADE, FOREIGN KEY (tag_id) REFERENCES tags(tag_id) ON DELETE CASCADE, INDEX idx_tag (tag_id) ); -- Media table: Media library (images, videos, files) CREATE TABLE media ( media_id BIGSERIAL PRIMARY KEY, filename VARCHAR(255) NOT NULL, original_filename VARCHAR(255) NOT NULL, mime_type VARCHAR(100) NOT NULL, file_size BIGINT NOT NULL, file_path VARCHAR(500) NOT NULL, thumbnail_path VARCHAR(500), width INT, height INT, uploaded_by INT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (uploaded_by) REFERENCES users(user_id), INDEX idx_mime_type (mime_type), INDEX idx_uploaded_by (uploaded_by), INDEX idx_created (created_at DESC) ); -- Content_media junction table CREATE TABLE content_media ( content_id BIGINT NOT NULL, media_id BIGINT NOT NULL, display_order INT DEFAULT 0, PRIMARY KEY (content_id, media_id), FOREIGN KEY (content_id) REFERENCES content(content_id) ON DELETE CASCADE, FOREIGN KEY (media_id) REFERENCES media(media_id) ON DELETE CASCADE, INDEX idx_media (media_id) );

Python Implementation

import psycopg2 from psycopg2.extras import RealDictCursor, Json from datetime import datetime from typing import Dict, List, Optional import json class CMSDB: def __init__(self, connection_string: str): self.conn = psycopg2.connect(connection_string) def create_content_type(self, type_name: str, fields: Dict) -> int: """Create a custom content type""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO content_types (type_name, fields) VALUES (%s, %s) RETURNING type_id """, (type_name, Json(fields))) type_id = cur.fetchone()[0] self.conn.commit() return type_id def create_content(self, type_id: int, slug: str, author_id: int, data: Dict, status: str = 'draft', categories: List[int] = None, tags: List[int] = None) -> int: """Create new content""" try: with self.conn.cursor() as cur: # Create content record cur.execute(""" INSERT INTO content (type_id, slug, author_id, status) VALUES (%s, %s, %s, %s) RETURNING content_id """, (type_id, slug, author_id, status)) content_id = cur.fetchone()[0] # Create initial version cur.execute(""" INSERT INTO content_versions (content_id, version_number, data, author_id) VALUES (%s, 1, %s, %s) """, (content_id, Json(data), author_id)) # Add categories if categories: for cat_id in categories: cur.execute(""" INSERT INTO content_categories (content_id, category_id) VALUES (%s, %s) """, (content_id, cat_id)) # Add tags if tags: for tag_id in tags: cur.execute(""" INSERT INTO content_tags (content_id, tag_id) VALUES (%s, %s) """, (content_id, tag_id)) self.conn.commit() return content_id except Exception as e: self.conn.rollback() raise e def update_content(self, content_id: int, data: Dict, author_id: int, change_summary: str = None) -> int: """Update content and create new version""" with self.conn.cursor() as cur: # Get current version number cur.execute(""" SELECT COALESCE(MAX(version_number), 0) + 1 FROM content_versions WHERE content_id = %s """, (content_id,)) next_version = cur.fetchone()[0] # Create new version cur.execute(""" INSERT INTO content_versions (content_id, version_number, data, author_id, change_summary) VALUES (%s, %s, %s, %s, %s) RETURNING version_id """, (content_id, next_version, Json(data), author_id, change_summary)) version_id = cur.fetchone()[0] # Update content timestamp cur.execute(""" UPDATE content SET updated_at = CURRENT_TIMESTAMP WHERE content_id = %s """, (content_id,)) self.conn.commit() return version_id def publish_content(self, content_id: int): """Publish content""" with self.conn.cursor() as cur: cur.execute(""" UPDATE content SET status = 'published', published_at = CURRENT_TIMESTAMP WHERE content_id = %s """, (content_id,)) self.conn.commit() def get_content(self, content_id: int, version: Optional[int] = None, language: str = 'en') -> Dict: """Get content with specific version and language""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: if version is None: # Get latest version cur.execute(""" SELECT cv.data, c.slug, c.status, c.published_at, u.first_name, u.last_name, cv.version_number FROM content c JOIN content_versions cv ON c.content_id = cv.content_id JOIN users u ON c.author_id = u.user_id WHERE c.content_id = %s ORDER BY cv.version_number DESC LIMIT 1 """, (content_id,)) else: cur.execute(""" SELECT cv.data, c.slug, c.status, c.published_at, u.first_name, u.last_name, cv.version_number FROM content c JOIN content_versions cv ON c.content_id = cv.content_id JOIN users u ON c.author_id = u.user_id WHERE c.content_id = %s AND cv.version_number = %s """, (content_id, version)) result = cur.fetchone() if result and language != 'en': # Check for translation cur.execute(""" SELECT data FROM translations WHERE content_id = %s AND language_code = %s AND is_published = true """, (content_id, language)) translation = cur.fetchone() if translation: result['data'] = translation['data'] return result def add_translation(self, content_id: int, language_code: str, data: Dict): """Add translation for content""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO translations (content_id, language_code, data) VALUES (%s, %s, %s) ON CONFLICT (content_id, language_code) DO UPDATE SET data = EXCLUDED.data """, (content_id, language_code, Json(data))) self.conn.commit() def get_content_by_category(self, category_id: int, limit: int = 20, offset: int = 0) -> List[Dict]: """Get published content by category""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" SELECT c.content_id, c.slug, c.published_at, cv.data, u.first_name, u.last_name FROM content c JOIN content_categories cc ON c.content_id = cc.content_id JOIN content_versions cv ON c.content_id = cv.content_id JOIN users u ON c.author_id = u.user_id WHERE cc.category_id = %s AND c.status = 'published' AND cv.version_number = ( SELECT MAX(version_number) FROM content_versions WHERE content_id = c.content_id ) ORDER BY c.published_at DESC LIMIT %s OFFSET %s """, (category_id, limit, offset)) return cur.fetchall() def search_content(self, query: str, content_type: Optional[int] = None, limit: int = 20) -> List[Dict]: """Full-text search across content""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: if content_type: cur.execute(""" SELECT c.content_id, c.slug, c.published_at, cv.data, u.first_name, u.last_name FROM content c JOIN content_versions cv ON c.content_id = cv.content_id JOIN users u ON c.author_id = u.user_id WHERE c.status = 'published' AND c.type_id = %s AND cv.data::text ILIKE %s AND cv.version_number = ( SELECT MAX(version_number) FROM content_versions WHERE content_id = c.content_id ) ORDER BY c.published_at DESC LIMIT %s """, (content_type, f"%{query}%", limit)) else: cur.execute(""" SELECT c.content_id, c.slug, c.published_at, cv.data, u.first_name, u.last_name FROM content c JOIN content_versions cv ON c.content_id = cv.content_id JOIN users u ON c.author_id = u.user_id WHERE c.status = 'published' AND cv.data::text ILIKE %s AND cv.version_number = ( SELECT MAX(version_number) FROM content_versions WHERE content_id = c.content_id ) ORDER BY c.published_at DESC LIMIT %s """, (f"%{query}%", limit)) return cur.fetchall() def create_category(self, name: str, slug: str, parent_id: Optional[int] = None, description: str = None) -> int: """Create content category""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO categories (name, slug, parent_id, description) VALUES (%s, %s, %s, %s) RETURNING category_id """, (name, slug, parent_id, description)) category_id = cur.fetchone()[0] self.conn.commit() return category_id def get_category_tree(self) -> List[Dict]: """Get hierarchical category tree""" with self.conn.cursor(cursor_factory=RealDictCursor) as cur: cur.execute(""" WITH RECURSIVE category_tree AS ( SELECT category_id, parent_id, name, slug, 0 as level FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.category_id, c.parent_id, c.name, c.slug, ct.level + 1 FROM categories c JOIN category_tree ct ON c.parent_id = ct.category_id ) SELECT * FROM category_tree ORDER BY level, name """) return cur.fetchall() def upload_media(self, filename: str, original_filename: str, mime_type: str, file_size: int, file_path: str, uploaded_by: int, thumbnail_path: str = None, width: int = None, height: int = None) -> int: """Add media to library""" with self.conn.cursor() as cur: cur.execute(""" INSERT INTO media (filename, original_filename, mime_type, file_size, file_path, thumbnail_path, width, height, uploaded_by) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING media_id """, (filename, original_filename, mime_type, file_size, file_path, thumbnail_path, width, height, uploaded_by)) media_id = cur.fetchone()[0] self.conn.commit() return media_id def attach_media_to_content(self, content_id: int, media_ids: List[int]): """Attach media files to content""" with self.conn.cursor() as cur: for order, media_id in enumerate(media_ids): cur.execute(""" INSERT INTO content_media (content_id, media_id, display_order) VALUES (%s, %s, %s) ON CONFLICT (content_id, media_id) DO UPDATE SET display_order = EXCLUDED.display_order """, (content_id, media_id, order)) self.conn.commit() # Usage example cms = CMSDB("postgresql://user:pass@localhost/cms_db") # Create blog post content type blog_type_id = cms.create_content_type("blog_post", { "title": {"type": "string", "required": True}, "body": {"type": "richtext", "required": True}, "excerpt": {"type": "string"}, "featured_image": {"type": "media"} }) # Create category tech_cat_id = cms.create_category("Technology", "technology") # Create blog post post_id = cms.create_content( blog_type_id, "my-first-post", author_id=1, data={ "title": "My First Blog Post", "body": "

This is the content...

", "excerpt": "An introduction to blogging" }, categories=[tech_cat_id] ) # Publish post cms.publish_content(post_id) # Add Spanish translation cms.add_translation(post_id, "es", { "title": "Mi Primera PublicaciΓ³n", "body": "

Este es el contenido...

", "excerpt": "Una introducciΓ³n al blogging" }) # Search content results = cms.search_content("blog", limit=10) print(f"Found {len(results)} posts") # Get category tree tree = cms.get_category_tree() for cat in tree: indent = " " * cat['level'] print(f"{indent}{cat['name']}")

Production Deployment Tips

Social Media: Implement Redis caching for feeds, use CDN for media, partition by date, set up read replicas.

Analytics: Use time-series partitioning, aggregate data hourly/daily, implement data retention policies, consider ClickHouse for massive scale.

CMS: Cache published content aggressively, use Elasticsearch for search, implement CDN for media library, enable content preview environments.

These aren't toy examplesβ€”they're production-ready schemas used by real companies handling millions of users. Master these patterns and you can build any database-driven application that exists.

← Chapter 06: Frontend & Backend Next: Chapter 08 β†’