Blogs and Insights

Thoughts, tutorials, and practical lessons on AI engineering, machine learning, and building useful software.

← Back to all blogs

Deep Learning · ML Engineering

Neural Networks, Explained from First Principles: Perceptrons, Backpropagation, PyTorch, and Tuning

How does a neural network actually learn? Start with one neuron, follow three numerical training updates, build a multilayer network in PyTorch, and learn how to tune and optimize it.

Scope: This article focuses on perceptrons and fully connected feedforward neural networks (multilayer perceptrons, or MLPs). It deliberately does not cover CNNs, RNNs, or Transformers. Numerical tables labeled illustrative are teaching examples, not reported experiment results.

The big idea: learning is a repeated correction

A neural network is not a collection of mysterious rules. It is a mathematical function with adjustable parameters—primarily weights and biases. During training, it makes a prediction, measures how far that prediction is from the correct answer, and adjusts its parameters to improve future predictions.

The essential cycle is:

Text
Input features
      ↓
Linear layers (weights + biases)
      ↓
Activation functions
      ↓
Prediction (forward pass)
      ↓
Loss function: how wrong was it?
      ↓
Backpropagation: compute gradients
      ↓
Optimizer: update weights and biases
      ↺ Repeat with more training data

There are three distinct jobs worth remembering:

  • The loss function measures prediction error.
  • Backpropagation calculates how changing each trainable parameter would affect that error.
  • The optimizer uses those gradients to update the parameters.

Keeping those jobs separate makes almost every later training concept easier to understand.

1. From one perceptron to one prediction

Start with a single artificial neuron. It takes input values, multiplies them by weights, adds a bias, and applies an activation function.

For two features:

Here, and are inputs, and determine how strongly those inputs contribute, is a learned offset, and is the activation function.

Let's calculate a simple example:

Value Number
First input, 1
Second input, 0
First weight, 0.6
Second weight, −0.2
Bias, −0.3

With the classic perceptron's step activation—output 1 when , otherwise 0—the result is 1.

Python
x1, x2 = 1, 0
w1, w2 = 0.6, -0.2
bias = -0.3

z = x1 * w1 + x2 * w2 + bias
output = 1 if z >= 0 else 0

print(z, output)  # 0.3 1

This simple model introduces the ingredients of larger networks. One important distinction: the classic perceptron uses a step function, whereas modern networks generally use activations suitable for gradient-based training.

2. What changes when we add layers?

A feedforward neural network connects many neurons in successive layers. Information moves from the input toward the output:

  • Input features describe an example, such as house size, bedrooms, and property age.
  • Hidden layers learn intermediate transformations.
  • The output layer produces the value or score required by the task.

Consider this small PyTorch model:

Python
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(3, 8),  # Three inputs → eight hidden neurons
    nn.ReLU(),        # Nonlinear activation
    nn.Linear(8, 4),  # Eight neurons → four
    nn.ReLU(),
    nn.Linear(4, 1),  # Four neurons → one output
)

Its architecture is 3 → 8 → 4 → 1. It has two hidden layers, with 8 and 4 neurons. The ReLU() operations are activations, not extra groups of neurons.

Each nn.Linear layer has weights and biases. For a layer with inputs and outputs, the trainable-parameter count is .

Layer Calculation Parameters
Linear(3, 8) 32
Linear(8, 4) 36
Linear(4, 1) 5
Total 73

The network is not specifically a house-price model. Its purpose depends on the training data, target, output design, and loss function. Three numerical inputs and one output could describe house-price regression, a student's predicted score, delivery time, or a binary-classification logit.

Why not just stack linear layers?

If there are no nonlinear activations between them, a stack of linear layers is still equivalent to one linear transformation. Activations allow the network to represent more complex relationships.

Common choices are:

Activation What it does Typical role
ReLU Hidden layers
Sigmoid Maps values into (0, 1) Convert binary logits to probabilities
Tanh Maps values into (−1, 1) Some hidden-layer designs
Softmax Converts a vector of logits to class probabilities Multiclass predictions

An important PyTorch detail: BCEWithLogitsLoss expects a raw logit, so do not put a sigmoid immediately before that loss. Likewise, CrossEntropyLoss normally receives raw multiclass logits, not probabilities already passed through softmax. For ordinary regression, the final linear layer often has no activation.

3. Forward pass, loss, and backpropagation

A forward pass is simply the computation that produces a prediction. With one linear neuron:

The prediction is compared with the actual target through a loss function.

For regression, a common choice is mean squared error (MSE):

If an actual value is 10 and the prediction is 8, the squared error for that one example is .

Problem Common loss PyTorch example
Predict a continuous number Mean squared error nn.MSELoss()
Predict one of two classes Binary cross-entropy from logits nn.BCEWithLogitsLoss()
Predict one of several classes Multiclass cross-entropy nn.CrossEntropyLoss()

The loss tells us how wrong the prediction is, but it does not update the model. To change parameters, we need gradients.

Backpropagation applies the chain rule of calculus to calculate how the loss depends on each weight and bias. For one neuron with squared-error loss,

we get:

These derivatives are gradients. A basic stochastic gradient descent (SGD) optimizer updates the parameters using a learning rate :

In PyTorch, loss.backward() computes the gradients and optimizer.step() applies the update. The learning rate determines the scale of that update: excessively small updates can make training slow, while excessively large ones can overshoot or destabilize it.

4. Watch a neuron learn: three real numerical iterations

The formulas become clearer when we follow the same neuron through three updates. Use a single training example and deliberately simple starting values:

Setting Value
Input 1
Actual target 2
Initial weight 0
Initial bias 0
Learning rate 0.1
Loss
Optimizer SGD

Iteration 1. Starting with and :

Both gradients are . Applying SGD:

Iteration 2. With , the next prediction is 0.8. Loss falls to 1.44, both gradients are , and the updated weight and bias become 0.64.

Iteration 3. With , the next prediction is 1.28. Loss falls to 0.5184, both gradients are , and the parameters become 0.784.

Iteration Prediction before update Loss before update Weight after update Bias after update
1 0.00 4.0000 0.400 0.400
2 0.80 1.4400 0.640 0.640
3 1.28 0.5184 0.784 0.784

After the third update, the next prediction—before another update—would be , with squared error .

That progression is the heart of training: predict → calculate loss → compute gradients → update parameters → predict again. The weight and bias happen to change equally here because ; for other inputs their gradients can differ.

You can reproduce every number without installing any machine-learning library:

Python
x = 1.0
y = 2.0
weight = 0.0
bias = 0.0
learning_rate = 0.1

for iteration in range(1, 4):
    prediction = weight * x + bias
    loss = (y - prediction) ** 2

    grad_weight = 2 * (prediction - y) * x
    grad_bias = 2 * (prediction - y)

    weight -= learning_rate * grad_weight
    bias -= learning_rate * grad_bias

    print(
        f"Iteration {iteration}: prediction={prediction:.2f}, "
        f"loss={loss:.4f}, weight={weight:.3f}, bias={bias:.3f}"
    )

This is a deliberately controlled teaching example with one data point. Real training uses many examples and must be evaluated on data not used to fit the model.

5. Translating the learning cycle into PyTorch

The PyTorch equivalent of that learning loop is short:

Python
# Assumes model, train_loader, loss_fn, and optimizer are defined.
for epoch in range(num_epochs):
    model.train()

    for X_batch, y_batch in train_loader:
        optimizer.zero_grad()                 # Clear previous gradients
        predictions = model(X_batch)         # Forward pass
        loss = loss_fn(predictions, y_batch) # Measure error
        loss.backward()                      # Compute gradients
        optimizer.step()                     # Update weights and biases

Four terms are easy to confuse:

Term Meaning
Parameter A learned value, such as a weight or bias
Hyperparameter A chosen setting, such as learning rate or layer width
Batch The examples processed for one optimizer update
Epoch One full pass through the training dataset

An iteration usually means one optimizer update. With 1,000 training examples and batch size 100, one epoch typically contains 10 iterations.

A small, complete example: learning XOR

XOR has the targets 0, 1, 1, 0 for the binary input pairs (0,0), (0,1), (1,0), and (1,1). One classic linear perceptron cannot learn that pattern, but a multilayer network with a nonlinear activation can.

Python
import torch
from torch import nn

torch.manual_seed(0)

X = torch.tensor([
    [0., 0.],
    [0., 1.],
    [1., 0.],
    [1., 1.],
])
y = torch.tensor([[0.], [1.], [1.], [0.]])

model = nn.Sequential(
    nn.Linear(2, 8),
    nn.Tanh(),
    nn.Linear(8, 1),
)

loss_fn = nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.05)

for epoch in range(1000):
    optimizer.zero_grad()
    logits = model(X)
    loss = loss_fn(logits, y)
    loss.backward()
    optimizer.step()

model.eval()
with torch.no_grad():
    probabilities = torch.sigmoid(model(X))
    print(probabilities)

Notice that the model returns logits and sigmoid is applied after training, for interpretation. This four-example exercise demonstrates training mechanics, not real-world generalization: it evaluates the same examples used for learning.

6. How many hidden layers and neurons should a network have?

In PyTorch you can define deeper models simply by adding layers:

Python
model = nn.Sequential(
    nn.Linear(3, 64),
    nn.ReLU(),
    nn.Linear(64, 32),
    nn.ReLU(),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 8),
    nn.ReLU(),
    nn.Linear(8, 1),
)

That architecture is 3 → 64 → 32 → 16 → 8 → 1 and contains four hidden layers. You choose the depth and width, but more layers are not automatically better. Larger models can express more complex patterns while also consuming more computation and potentially fitting noise in the training data.

There is no universal formula for the ideal layer count. Start with a reasonable small model, compare validation results, and increase capacity only when the evidence supports it.

A useful practical distinction:

  • Underfitting: Both training and validation performance remain poor; investigate the data, feature quality, optimization setup, and model capacity.
  • Overfitting: Training loss improves while validation performance worsens; investigate regularization, data quality, model size, and when to stop training.

The training set teaches the model. A validation set helps select model settings. A separate test set, held back from tuning, is used for the final performance assessment.

7. The hyperparameters that actually matter

Hyperparameter tuning means selecting settings that govern the model's structure and training process. The network learns its weights and biases; you choose or search over settings such as layer widths and learning rate.

Area Hyperparameter What it controls Illustrative starting choices
Architecture Hidden layers Network depth 1–4 in small experiments
Architecture Hidden units Neurons per layer 8, 16, 32, 64, 128
Architecture Activation Nonlinearity ReLU, Tanh, GELU
Training Learning rate Parameter-update scale 0.01, 0.001, 0.0001
Training Optimizer Update algorithm SGD, Adam, AdamW
Training Batch size Examples per update 16, 32, 64, 128
Training Epochs Maximum complete data passes 50, 100, 200
Training Loss function Which error to minimize MSE, BCE-with-logits, cross-entropy
Regularization Dropout Fraction of activations dropped during training 0.1, 0.2, 0.3
Regularization Weight decay Penalty/discouragement for large weights 0.0001 as an experiment
Stability Gradient clipping Limit gradient magnitude max_norm=1.0 when needed
Training control Early-stopping patience Bad validation epochs tolerated before stopping 5–10
Training control Scheduler patience Bad epochs before an LR adjustment 2–3
Evaluation Validation split Data reserved for tuning/monitoring 0.2 as a simple starting point
Reproducibility Random seed Helps reproduce initialization and shuffling 42

These are examples to test, not universal defaults. Some settings (such as class weights, label smoothing, and probability thresholds) apply particularly to classification tasks rather than continuous regression. Normalization layers such as BatchNorm or LayerNorm are additional architecture choices when appropriate.

Dropout: reducing dependence on particular activations

Python
model = nn.Sequential(
    nn.Linear(3, 32),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Linear(16, 1),
)

nn.Dropout(0.2) randomly zeroes approximately 20% of the activations on each training pass. It may reduce overfitting by discouraging dependence on particular activations. Too much dropout can make a small model underfit.

Use model.train() during training. model.eval() turns dropout off for validation and inference. PyTorch handles the training-time scaling internally.

Weight decay and gradient clipping serve different purposes

Python
optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=0.001,
    weight_decay=0.0001,
)

# In a training step, after loss.backward():
# torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)

Weight decay is a regularization technique. Gradient clipping is primarily a training-stability measure; it is not an interchangeable cure for overfitting.

8. A learning-rate scheduler is not early stopping

As training progresses, the learning rate that worked initially might become too large for fine adjustments. A scheduler can reduce it when a monitored metric stops improving.

A common PyTorch choice is ReduceLROnPlateau:

Python
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    optimizer,
    mode="min",     # Lower validation loss is better
    factor=0.5,     # Halve the learning rate
    patience=3,
    min_lr=1e-6,
)

# After computing validation loss at the end of each epoch:
# scheduler.step(val_loss)

A sequence of reductions might be 0.001 → 0.0005 → 0.00025, but only when the plateau condition is met; these are not changes that automatically happen every three epochs.

One subtle detail: With PyTorch's ReduceLROnPlateau, patience=3 means it tolerates three bad epochs and normally reduces the learning rate when the bad-epoch count exceeds three—typically on the fourth bad epoch. If the goal is a reduction right after the third consecutive bad epoch, patience=2 is a closer match to that behavior.

Early stopping does something different: it ends training when validation results fail to improve sufficiently. A typical setup might have scheduler patience 3 and early-stopping patience 10, giving the scheduler time to make an adjustment before training stops.

Feature Learning-rate scheduler Early stopping
Watches validation performance Often Often
Changes the learning rate Yes No
Stops training No Yes
Useful when Progress plateaus but further improvement may be possible Continued training no longer seems useful

When implementing early stopping, track the best validation metric, count consecutive insufficient improvements, and save the best model weights for restoration. A min_delta threshold defines what counts as meaningful improvement. The scheduler may use its own different threshold rules.

9. Tuning architectures: grid search, random search, and Optuna

Neural-network tuning follows the same general logic as GridSearchCV and RandomizedSearchCV in scikit-learn: choose trial configurations, train on training data, compare on validation data, and select the best configuration.

Approach Strategy Tradeoff
Grid search Try every specified combination Simple, but gets expensive as choices multiply
Random search Sample combinations Covers larger spaces within a fixed trial budget
Optuna Adaptively suggest configurations Flexible for conditional choices and neural-network experiments

For example, Optuna can choose the number of hidden layers and neurons per layer:

Python
import optuna
import torch.nn as nn


def objective(trial):
    n_layers = trial.suggest_int("layers", 1, 4)
    n_units = trial.suggest_categorical("units", [8, 16, 32, 64])

    modules = []
    in_features = 3

    for _ in range(n_layers):
        modules += [nn.Linear(in_features, n_units), nn.ReLU()]
        in_features = n_units

    modules.append(nn.Linear(in_features, 1))
    candidate = nn.Sequential(*modules)

    # Your own training/validation function must be implemented.
    return train_and_evaluate(candidate)


study = optuna.create_study(direction="minimize")
study.optimize(objective, n_trials=30)
print(study.best_params)

This Optuna snippet is an integration pattern, not standalone runnable code: train_and_evaluate is intentionally undefined. It must train the candidate and return a validation loss. For scikit-learn-style wrappers around PyTorch, skorch is another possibility; SciKeras is for Keras rather than native PyTorch networks.

Avoid using the final test set to pick your hyperparameters. Otherwise it becomes another validation set, and the reported final result is less meaningful.

10. Quantization: optimizing the trained model

Training and deployment have different concerns. After you have a useful model, you may want to reduce its memory footprint or improve inference performance. Quantization represents some weights and/or activations using lower-precision formats, such as INT8 rather than FP32.

Representation Bits per value Approximate raw storage for 1 million values
FP32 32 4 MB
FP16 / BF16 16 2 MB
INT8 8 1 MB
INT4 4 0.5 MB

FP16 and BF16 are lower-precision floating-point formats, not integer quantization. These storage figures omit scales, metadata, packing, padding, and other implementation overhead.

Three useful quantization terms:

  • Post-training quantization (PTQ): Apply quantization after training.
  • Quantization-aware training (QAT): Simulate quantization effects during training so the model can adapt.
  • Dynamic quantization: Quantize some values dynamically during inference, depending on the backend and method.

A version-dependent illustration of weight-only INT8 with torchao looks like this:

Python
from torchao.quantization import quantize_, Int8WeightOnlyConfig

# 'model' must already be trained; backend/version compatibility varies.
model.eval()
quantize_(model, Int8WeightOnlyConfig())

That example is not guaranteed to work on every torchao version or hardware backend and does not imply all activations run in INT8. Benchmark inference accuracy, memory, and latency on the actual target device before accepting a quantized model.

Also, the earlier 3 → 8 → 4 → 1 network has only 73 trainable parameters: reducing their precision saves almost nothing in absolute terms. Quantization becomes more compelling when model size and deployment constraints justify it. The underlying principle also appears in LLM quantization, though methods such as GPTQ and AWQ are more specialized.

11. A complete training example: fit a small regression network

The following self-contained educational example ties together layers, nonlinearities, batch training, validation, dropout, AdamW, gradient clipping, a plateau scheduler, and early stopping. It creates synthetic data with three features and one continuous target; it does not download a real dataset or call an external API.

For clarity, this version separates training, validation, and test data, and restores the best validation checkpoint before evaluating the held-out test set.

Python
import copy
import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.manual_seed(42)

# Synthetic nonlinear regression: three features, one target.
X = torch.randn(1000, 3)
y = (
    2.0 * X[:, :1]
    - 1.5 * X[:, 1:2]
    + 0.8 * X[:, 2:3].square()
    + 0.1 * torch.randn(1000, 1)
)

# Keep the test set separate from the training/tuning decisions.
indices = torch.randperm(len(X))
train_idx = indices[:800]
val_idx = indices[800:900]
test_idx = indices[900:]

train_loader = DataLoader(
    TensorDataset(X[train_idx], y[train_idx]),
    batch_size=32,
    shuffle=True,
)
val_loader = DataLoader(
    TensorDataset(X[val_idx], y[val_idx]), batch_size=64
)
test_loader = DataLoader(
    TensorDataset(X[test_idx], y[test_idx]), batch_size=64
)

model = nn.Sequential(
    nn.Linear(3, 32),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(32, 16),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(16, 1),
)

loss_fn = nn.MSELoss()
optimizer = torch.optim.AdamW(
    model.parameters(), lr=0.001, weight_decay=0.0001
)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    optimizer, mode="min", factor=0.5, patience=3, min_lr=1e-6
)


def evaluate(data_loader):
    model.eval()  # Disables dropout
    total_loss, total_count = 0.0, 0
    with torch.no_grad():
        for xb, yb in data_loader:
            batch_loss = loss_fn(model(xb), yb)
            total_loss += batch_loss.item() * len(xb)
            total_count += len(xb)
    return total_loss / total_count


best_val_loss = float("inf")
best_state = copy.deepcopy(model.state_dict())
bad_epochs = 0
early_stopping_patience = 10
min_delta = 0.001

for epoch in range(100):
    model.train()
    for xb, yb in train_loader:
        optimizer.zero_grad()
        predictions = model(xb)
        loss = loss_fn(predictions, yb)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
        optimizer.step()

    val_loss = evaluate(val_loader)
    scheduler.step(val_loss)

    if val_loss < best_val_loss - min_delta:
        best_val_loss = val_loss
        best_state = copy.deepcopy(model.state_dict())
        bad_epochs = 0
    else:
        bad_epochs += 1

    current_lr = optimizer.param_groups[0]["lr"]
    print(f"Epoch {epoch + 1:3d} | Val MSE {val_loss:.5f} | LR {current_lr:.6f}")

    if bad_epochs >= early_stopping_patience:
        print("Early stopping triggered")
        break

model.load_state_dict(best_state)
test_mse = evaluate(test_loader)
print(f"Held-out test MSE: {test_mse:.5f}")

Run it with Python and PyTorch installed:

Shell
pip install torch
python neural_network_example.py

The test MSE printed by this script is a result of your own run; no specific score is promised here. Real applications also require representative data, leakage-safe preprocessing, task-appropriate metrics, and evaluation of the conditions in which predictions will be used.

12. A practical checklist for diagnosing training

When a model performs poorly, the most productive first question is not always "Should I add more layers?" Look at the pattern in the training and validation metrics.

What you observe What to investigate first
Training loss barely decreases Input scaling, target quality, learning rate, gradients, model capacity
Training loss oscillates or diverges Learning rate, data values, batch size, gradient stability
Training improves, validation worsens Overfitting, data quality, dropout, weight decay, smaller architecture
Both training and validation remain poor Underfitting, features, optimization settings, training duration
Validation loss stops improving LR scheduler, early-stopping patience, whether more capacity helps
Model is too large or slow for deployment Size/latency profiling, then quantization if supported

A reasonable workflow is to define the supervised task → split the data → prepare features without leakage → build a simple network → train and validate → tune deliberately → test on held-out data → optimize deployment if necessary.

Closing thought

A neural network makes more sense once its components stop looking like separate buzzwords. Layers and activations determine what it can represent. Loss and gradients explain what it needs to change. Optimizers and learning rates control how it changes. Validation, regularization, and training controls help determine whether it learned something useful rather than merely memorizing the examples.

Start with one neuron and three parameter updates. Once that is intuitive, the larger PyTorch architecture is the same fundamental learning process repeated across many parameters.


← Back to all blogs

AI Engineering · LLMOps

Retrieval-Augmented Generation, Explained: From Documents to Reranking and Grounded Answers

How does a RAG system turn university admission PDFs into reliable answers? Follow the full pipeline, learn the settings that matter in code, and understand how a reranker is trained as a machine-learning model.

Scope: This article covers RAG mechanics, coding settings, and reranking—including its ML training process. It deliberately excludes explanations of attention mechanisms and Transformer architectures. University admission requirements, similarity scores, and sample training labels below are illustrative, not verified University X policies or reported experiment results.

The problem: answering questions from documents, not memory

Imagine a student asks a university chatbot:

“What documents do I need to apply to University X?”

The university maintains admission guides, eligibility rules, international-student instructions, and application deadlines as PDFs and web pages. A general-purpose LLM might know something about university applications, but it should not guess University X’s current requirements.

Retrieval-Augmented Generation (RAG) addresses that problem by finding relevant information in an external collection and supplying it to the LLM when it answers. The LLM is not retrained on every PDF update: the searchable collection can be reindexed as the documents change.

RAG has two distinct phases:

Text
OFFLINE / WHEN DOCUMENTS CHANGE
PDFs, web pages, database records
    → Load and extract text
    → Split into chunks
    → Embed chunks as vectors
    → Store vectors + text + source metadata

ONLINE / WHEN A STUDENT ASKS
Student's question
    → Embed question
    → Retrieve candidate chunks (e.g., top 20)
    → Rerank candidates (e.g., keep best 5)
    → Build a prompt with question + evidence
    → LLM generates answer with source citations

The key separation is retrieval finds evidence; generation turns that evidence into an answer. Reranking sits between them and improves which evidence reaches the LLM.

1. Document ingestion: loading PDFs correctly

For a PDF-based knowledge base, PyPDFLoader from langchain-community is a convenient wrapper around PDF text extraction. The similarly named pypdf package is the underlying PDF-processing library; they are not the same API.

Python
from langchain_community.document_loaders import PyPDFLoader

loader = PyPDFLoader(
    "admission.pdf",
    mode="page",
    extraction_mode="plain",
    extract_images=False,
)

pages = loader.load()
print(pages[0].page_content[:200])
print(pages[0].metadata)

This is runnable with an actual admission.pdf and the required dependencies installed. Each page is returned as a document with text and metadata such as the source path and page index.

Setting What it determines Example / tradeoff
File path Which PDF is loaded "admission.pdf"
mode Whether one document represents a page or the whole file "page" preserves page-level references; "single" can avoid page-boundary breaks
extraction_mode How ordinary PDF text is extracted "plain" vs. "layout" where supported
extract_images Whether to process embedded PDF images False for text-centric PDFs; image extraction needs additional handling
Password How to access encrypted PDFs Set only if needed

A PDF can look readable while containing scanned images rather than selectable text. Ordinary PDF text extraction is not OCR; scanned admission forms may require OCR or other image-aware extraction. Validate a few pages before indexing the whole collection.

Keep metadata alongside every chunk—for example source, page, university, document title, and a version/date if known. Metadata makes filtering and citations possible. For the page index returned by the loader, note that page is commonly zero-based; use page_label where available for human-readable citations.

2. Chunking: why chunk_size and chunk_overlap matter

Suppose an admission guide is 80 pages long. Embedding the entire guide as a single vector would mix requirements, fees, housing, deadlines, and other topics into one representation. Instead, split it into smaller chunks that preserve useful meaning.

Two settings are especially important:

  • chunk_size: The maximum target length of a chunk, in characters or tokens depending on the splitter. It includes any overlap; it is not the new content plus overlap.
  • chunk_overlap: Content carried over between adjacent chunks to avoid losing information at boundaries. It is a target, not a promise that every pair will overlap by exactly that amount.

For a simplified fixed-length example, chunk_size=100 and chunk_overlap=20 means a 100-unit chunk followed by a new chunk beginning 80 units later. Real splitters usually prefer paragraph or sentence boundaries, so their chunk lengths can vary.

Characters and tokens are not interchangeable. With the standard RecursiveCharacterTextSplitter, chunk_size=500 usually means 500 characters because the default length_function is len. A tokenizer-aware splitter instead measures token counts.

Python
from langchain_text_splitters import RecursiveCharacterTextSplitter

# Default: counts characters, not model tokens.
character_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=75,
    add_start_index=True,
)

# Alternative: count tokens with the embedding model's tokenizer.
from sentence_transformers import SentenceTransformer

embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
token_splitter = RecursiveCharacterTextSplitter.from_huggingface_tokenizer(
    embedding_model.tokenizer,
    chunk_size=180,
    chunk_overlap=30,
    add_start_index=True,
)

chunks = token_splitter.split_documents(pages)

The second example is aligned to the chosen embedding model’s tokenizer. Its 180/30 values are starting choices to test, not universal defaults. all-MiniLM-L6-v2 truncates inputs beyond its model limit (commonly 256 word pieces), so choosing 500 tokens with that particular embedding model can silently discard part of each chunk. Tokenizer limits, special tokens, and the model’s effective maximum input length must be checked together.

The default recursive splitter tries boundaries such as "\n\n", "\n", " ", and finally individual characters. separators controls that order; add_start_index=True adds a chunk’s character start offset to metadata when it can be located.

Chunking decision Benefit Risk if taken too far
Smaller chunks More focused retrieval A requirement may be separated from its qualification
Larger chunks More surrounding context Irrelevant material, longer prompts, possible truncation
More overlap Better continuity across boundaries Duplicates, larger index, repeated evidence
Page-based loading Easier page citations A paragraph may cross a page boundary

Practical rule: Start with meaningful document sections, use a tokenizer compatible with your embedding model, and tune chunking based on questions your system must answer.

3. Embeddings and the vector database

An embedding model turns a text chunk into a numerical vector. A bi-encoder generates embeddings for the question and chunks independently. You can therefore calculate document embeddings once during indexing and reuse them across many student questions.

For example, all-MiniLM-L6-v2 produces 384-dimensional embeddings. In a real system, the vector database stores the vector together with its original text and metadata. Options for vector search include FAISS and Pinecone; FAISS is a similarity-search library, while Pinecone is a managed vector-database service.

Similarity is often measured with cosine similarity:

cosine(𝐪,𝐝)=𝐪⋅𝐝∥𝐪∥∥𝐝∥ \operatorname{cosine}(\mathbf{q},\mathbf{d}) =\frac{\mathbf{q}\cdot\mathbf{d}}{\|\mathbf{q}\|\,\|\mathbf{d}\|}

Here, 𝐪\mathbf{q} is the question embedding and 𝐝\mathbf{d} is a document-chunk embedding. The score measures vector alignment—not a guaranteed probability that a passage correctly answers the question.

Python
texts = [chunk.page_content for chunk in chunks]

vectors = embedding_model.encode(
    texts,
    batch_size=32,
    normalize_embeddings=True,
)

question = "What documents do I need to apply to University X?"
query_vector = embedding_model.encode(
    [question], normalize_embeddings=True
)[0]
Embedding setting Meaning Example
model_name Which text-to-vector model is used all-MiniLM-L6-v2
embedding_dimension How many numbers each vector contains 384 for this model
batch_size Number of texts encoded per batch 32
normalize_embeddings Whether vectors have unit length True
Model input limit How much text the encoder actually sees Model-specific; check truncation
Similarity metric How vectors are compared Cosine or dot product

Consistency matters: Index and query with the same compatible embedding model and preprocessing setup. If you switch to a model producing different embeddings, the collection normally needs to be re-embedded. The vector index must use the expected dimension.

4. Retrieval: top_k is not a threshold

At query time, the system embeds the student’s question and searches the stored chunk vectors.

If top_k=20, the retriever asks for the 20 highest-ranking candidates. This does not mean the candidates each exceeded a similarity of 0.87. A score threshold, if supported, is an additional filter; the numeric scale depends on the model, metric, and database implementation.

Retrieval setting What it controls Example
top_k / k Number of candidate chunks returned 20
similarity_metric Vector comparison Cosine
score_threshold Optional minimum accepted similarity Must be calibrated; no universal 0.87
metadata_filter Which documents are eligible university = X
search_type How candidates are found Similarity, MMR, or hybrid retrieval
fetch_k Initial candidate count for methods such as MMR 40

Metadata filtering is valuable here: a highly similar passage from University Y is still the wrong evidence for University X. In some systems, hybrid retrieval combines semantic vector search with keyword search. MMR (maximal marginal relevance) can balance relevance against near-duplicate results.

A successful retriever aims for recall: get enough genuinely useful passages into the candidate set. It does not need to arrange all 20 perfectly—that is where reranking can help.

5. Reranking: a second, more careful relevance judgment

The student asks:

“What documents do I need to apply to University X?”

Vector retrieval returns 20 candidate chunks. Some may discuss fees or admission deadlines because their wording overlaps with the question. Reranking scores each retrieved passage against the actual question and sorts the candidates again.

Text
Vector retrieval:     top_k = 20 candidate chunks
                              ↓
Cross-encoder:        question + chunk → relevance score
                      (repeated for each of 20 chunks)
                              ↓
Reranking:            sort by the new scores
                              ↓
Selection:            top_n = 5 chunks for the LLM

This is not just another cosine-similarity sort.

Retrieval with a bi-encoder Reranking with a cross-encoder
Encodes the question and documents separately Evaluates a question–document pair jointly
Compares stored vectors mathematically Uses a learned model to predict pair relevance
Efficient across a large collection More expensive for each candidate pair
Optimized for finding likely matches quickly Used to improve ordering within a candidate set

Both models perform numerical computation internally. “Cross-encoder reads the text” does not mean it operates without numerical representations; it means it uses the paired text as one model input instead of comparing two independently precomputed embeddings.

A concrete example

The following scores are invented to demonstrate ranking, not outputs from the actual model:

Candidate passage Illustrative reranker score
University X — passport, transcripts, and language certificate 0.96
University X — general eligibility criteria 0.79
University X — annual tuition 0.18

The reranker can elevate a passage that directly answers the documents question over one that merely concerns university admissions. It also has a limitation: it cannot recover a relevant passage that retrieval failed to include in the first 20 candidates.

Real inference code

Python
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")

candidate_texts = [
    "Applicants must submit their passport and transcript.",
    "University X charges an annual tuition fee.",
    "Applicants must provide English proficiency evidence.",
]

pairs = [(question, passage) for passage in candidate_texts]
scores = reranker.predict(pairs)

ranked = sorted(
    zip(candidate_texts, scores),
    key=lambda item: float(item[1]),
    reverse=True,
)

for passage, score in ranked:
    print(round(float(score), 3), passage)

The code is runnable after model dependencies are installed and the pretrained weights are available. It deliberately prints model scores, not fabricated outputs. The model shown commonly returns raw logits, not calibrated probabilities from 0 to 1. A score threshold such as >= 0.87 must therefore not be copied blindly from a hypothetical example. CrossEncoder.rank(question, passages, top_k=5) is another supported API for ranking and selecting candidates.

Top-K and threshold are separate ideas: top_n=5 keeps at most five highest-ranked candidates; an optional calibrated threshold can reject insufficiently relevant results. A system can apply either or both.

6. How a reranker is trained as an ML model

A reranker is not an invented function such as magic_relevance_score(question, chunk). A pretrained reranker is a supervised machine-learning model whose parameters were optimized on examples of query–passage relevance.

One well-known training resource is MS MARCO, built around real web-search queries and candidate passages. The pretrained model cross-encoder/ms-marco-MiniLM-L6-v2 is a concrete example of a reranker trained for passage ranking. The rows below are our university example, not literal MS MARCO records:

Query Passage Relevance label
Required admission documents? Submit passport and transcript 1
Required admission documents? Tuition costs $12,000 annually 0
Required admission documents? University X was founded in 1950 0

For a binary-relevance training setup, the loop looks like any other supervised ML training process:

Text
Labeled (question, passage) pairs
    → Model predicts relevance
    → Loss compares prediction with label
    → Backpropagation computes parameter gradients
    → Optimizer updates model parameters
    → Repeat and validate on held-out queries

With binary labels y∈{0,1}y\in\{0,1\} and predicted probability pp, one possible objective is binary cross-entropy:

L=−[ylog(p)+(1−y)log(1−p)] L=-\left[y\log(p)+(1-y)\log(1-p)\right]

  • y=1y=1: the passage is labeled relevant.
  • y=0y=0: the passage is labeled non-relevant.
  • pp: a probability derived from the model’s prediction for this training objective.

This is one possible training approach, not the universal loss for every reranker. Ranking-based objectives can instead learn which passages should score above others. A model may output raw logits at inference even when its training objective uses binary cross-entropy.

Why hard negatives matter

A random passage about football is an easy negative for a university-documents question. A better training challenge is a hard negative:

“University X admissions are open until December 1.”

It sounds relevant to admissions, but it does not answer which documents must be submitted. Hard negatives teach the reranker to distinguish a general topic match from evidence that actually answers the question.

A minimal fine-tuning illustration

Python
from datasets import Dataset
from sentence_transformers import CrossEncoder
from sentence_transformers.cross_encoder import (
    CrossEncoderTrainer,
    CrossEncoderTrainingArguments,
)
from sentence_transformers.cross_encoder.losses import BinaryCrossEntropyLoss

train_data = Dataset.from_dict({
    "sentence1": [
        "What documents are required?",
        "What documents are required?",
        "What is the tuition fee?",
    ],
    "sentence2": [
        "Submit a passport and transcript.",
        "The university was founded in 1950.",
        "Annual tuition is $12,000.",
    ],
    "label": [1.0, 0.0, 1.0],
})

model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
args = CrossEncoderTrainingArguments(
    output_dir="./university-reranker",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    learning_rate=2e-5,
    report_to="none",
)
trainer = CrossEncoderTrainer(
    model=model,
    args=args,
    train_dataset=train_data,
    loss=BinaryCrossEntropyLoss(model),
)
trainer.train()
model.save_pretrained("./university-reranker")

This is an API-level, runnable fine-tuning illustration with current Sentence Transformers training interfaces, subject to library-version and hardware compatibility. Its three examples are far too few to produce a useful new reranker; they show the components and workflow, not a trained system validated for university admissions. A real project needs a much larger dataset with positive and negative examples, a held-out validation set, and ranking metrics such as MRR or nDCG.

You usually do not have to train a reranker from scratch. Start with a pretrained model, evaluate it on your own admission questions, and fine-tune only if the domain evidence supports doing so.

7. Context augmentation and the LLM answer

Once reranking selects the strongest chunks, put the question and the retrieved passages into a prompt. Include source references so the answer can cite evidence.

Text
SYSTEM:
Answer using only the supplied University X documents.
If the documents do not establish an answer, say so.
Cite the source document and page for each requirement.

CONTEXT:
[admission.pdf, page 4]
Applicants must submit transcripts and a passport copy.

[international_students.pdf, page 2]
Proof of English proficiency is required for this program.

QUESTION:
What documents do I need to apply to University X?

A possible answer to this hypothetical context is:

For the program covered by these documents, you need transcripts and a passport copy (admission.pdf, p. 4), plus proof of English proficiency (international_students.pdf, p. 2).

The LLM should not invent a motivation-letter requirement if that is absent from the supplied passages. It also should not claim the retrieved passages are exhaustive when they might omit another applicable admission rule. University, program, degree level, intake year, and applicant type can all matter; filtering metadata or asking a targeted follow-up may be necessary.

RAG does not retrain the LLM at answer time. It augments the prompt with evidence retrieved from the external source collection. Retrieval can reduce unsupported answers, but it does not guarantee factual accuracy.

8. All the important RAG coding settings, in one place

These are starting configurations to evaluate, not universal best practices. Library names and supported parameters vary, especially across vector databases and LLM providers.

Stage Setting What it defines Illustrative value
PDF loading mode Per-page vs. whole-PDF document "page"
PDF loading extraction_mode Text extraction style "plain"
PDF loading extract_images Embedded-image handling False
Chunking chunk_size Maximum target chunk length; units depend on tokenizer/length function 180 model tokens in the MiniLM example
Chunking chunk_overlap Repeated context at chunk boundaries 30 model tokens
Chunking length_function / tokenizer Whether length means characters or tokens Embedding-model tokenizer
Chunking separators Preferred boundaries when splitting Paragraphs, lines, spaces
Embeddings embedding_model Which model produces vectors all-MiniLM-L6-v2
Embeddings embedding_dimension Stored vector length 384 for that model
Embeddings batch_size Texts processed per embedding batch 32
Embeddings normalize_embeddings Unit-length vectors for comparison True
Index / search similarity_metric Vector comparison method Cosine
Retrieval top_k Initial retrieved-candidate count 20
Retrieval metadata_filter Restricts the source collection University X
Retrieval score_threshold Optional minimum accepted similarity Calibrate on your data
Retrieval search_type / fetch_k Similarity vs. diversity/hybrid search and candidate pool MMR with fetch_k=40, if used
Reranking reranker_model Pairwise relevance-scoring model MS MARCO MiniLM cross-encoder
Reranking top_n How many reranked chunks reach the LLM 5
Reranking max_length Reranker pair-input limit Model-specific
Generation temperature Randomness of sampling, if supported 0–0.2
Generation max_output_tokens Upper bound on generated response length 500
Generation top_p Nucleus-sampling control 1.0
Generation Context budget How many retrieved tokens can fit, alongside prompt and response Model-specific
Reliability API timeout Upper bound for a request to complete e.g., 30 seconds

A small configuration object

Python
RAG_CONFIG = {
    "pdf_mode": "page",
    "chunk_size": 180,               # Embedding-model tokens
    "chunk_overlap": 30,
    "embedding_model": "all-MiniLM-L6-v2",
    "embedding_batch_size": 32,
    "normalize_embeddings": True,
    "similarity_metric": "cosine",
    "retrieval_top_k": 20,
    "reranker_model": "cross-encoder/ms-marco-MiniLM-L6-v2",
    "rerank_top_n": 5,
    "temperature": 0.1,
    "max_output_tokens": 500,
}

This is a configuration template, not a complete application: your code must read and apply these values to the chosen libraries. Keep separate budgets for embedding-model input length, reranker pair length, and LLM input/output tokens; they are different limits.

9. A compact, runnable retrieval-and-reranking demonstration

This script demonstrates the central online retrieval + reranking part without requiring a vector-database server or paid LLM API. It uses three illustrative passages as a tiny in-memory collection. It prints the best evidence and a draft prompt; it does not call an LLM or generate an answer.

Install the core library:

Shell
pip install sentence-transformers numpy
Python
import numpy as np
from sentence_transformers import CrossEncoder, SentenceTransformer

question = "What documents do I need to apply to University X?"
passages = [
    "University X applicants must provide a passport copy and transcripts.",
    "University X tuition fees are listed in the finance guide.",
    "International applicants to University X need proof of English proficiency.",
]
sources = ["admission.pdf, p. 4", "fees.pdf, p. 1", "international.pdf, p. 2"]

# Indexing: independently embed each passage.
encoder = SentenceTransformer("all-MiniLM-L6-v2")
doc_vectors = encoder.encode(passages, normalize_embeddings=True)

# Query: compare the question vector against stored vectors.
query_vector = encoder.encode([question], normalize_embeddings=True)[0]
similarities = doc_vectors @ query_vector  # cosine for normalized vectors
candidate_ids = np.argsort(similarities)[::-1][:20]

# Reranking: score each question–passage pair with a second model.
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
pairs = [(question, passages[int(i)]) for i in candidate_ids]
rerank_scores = reranker.predict(pairs)
order = np.argsort(rerank_scores)[::-1][:2]
selected_ids = [int(candidate_ids[int(j)]) for j in order]

# The next step would be to pass this prompt to your chosen LLM.
context = "\n\n".join(
    f"[{sources[i]}]\n{passages[i]}" for i in selected_ids
)
prompt = (
    "Answer only from this context and cite its sources. "
    "If evidence is missing, say so.\n\n"
    f"Context:\n{context}\n\nQuestion: {question}"
)
print(prompt)

Why [:20] returns only three candidates here: the demonstration contains only three passages. In a real indexed university corpus, top_k=20 means up to 20 candidates, and the selected count is also constrained by filters and the contents of the index.

For a real PDF-backed application, replace the passages list with your loaded and chunked documents, preserve their metadata, persist the embeddings in a vector index, and supply the constructed prompt to a configured LLM. Those integrations depend on the chosen database and LLM provider, so they are intentionally not presented here as working API calls.

10. How to evaluate and debug a RAG system

Changing top_k, chunk size, or the reranker is meaningful only if you can observe whether the system improves. Make a small test set of real university questions with known supporting passages and expected answers.

Observation Likely investigation
Relevant document never appears in top 20 Extraction quality, metadata filters, chunking, embeddings, retrieval recall
Right document appears at rank 15 but is missed in final 5 Reranker relevance quality, reranking top_n, hard negatives
Retrieved passage is cut in the middle of a requirement Chunk boundaries, overlap, tokenizer limit
Correct passages are provided but answer invents requirements Prompt constraints, generation behavior, citation checking
Response is too slow Retrieval size, reranker candidate count, embedding/API latency
Token usage is unexpectedly high Number and size of selected chunks, duplicate overlap, output budget

Useful measurements include Recall@K for retrieval, MRR or nDCG for ranking, answer correctness and citation accuracy for generation, plus p50/p95 latency and per-request cost. Evaluate on held-out questions, not only the examples used to tune settings or train a reranker.

One important failure boundary: reranking fixes the order of candidates; it does not fix missing source documents, bad OCR, incorrect metadata, or unsupported final claims. A reliable RAG system needs each stage to work.

Closing thought

RAG becomes much easier to reason about when the stages have distinct jobs:

Load accurate sources → split them into sensible chunks → embed and index them → retrieve broadly → rerank carefully → give the LLM a small, cited evidence set → check the final answer.

The first retrieval stage uses fast vector similarity to find potential evidence. The cross-encoder reranker is a separately trained ML model that scores the question–passage pair more carefully. Settings such as chunk_size, tokenizer, top_k, top_n, context budget, and model choice control how much useful information reaches the LLM—and at what latency and cost.

The goal is not merely to produce a fluent answer about University X. It is to produce an answer the student can trace back to the correct, applicable university documents.

← Back to all blogs

ML Engineering · AI Engineering

Practical Machine Learning, from Raw Data to Reliable Models: Preprocessing, Feature Engineering, Evaluation, Ensembles, NLP, Regression, and Clustering

How do you get from a messy dataset to a model you can trust? Follow the complete machine-learning workflow: prepare features without leakage, reduce complexity, validate and tune models, combine learners, work with text, predict numbers, and discover structure in unlabeled data.

Scope: This is a practical guide to classical machine learning, centered on NumPy, pandas, and scikit-learn. It covers both supervised and unsupervised methods, but not neural-network architectures. Small numerical examples are illustrative, not benchmark results. Code blocks marked self-contained can be run independently after installing their stated dependencies; shorter snippets identify the variables they assume. Library signatures use current scikit-learn conventions where relevant.

The real challenge is everything around fit()

A classifier can be trained in two lines:

Python
model.fit(X_train, y_train)
predictions = model.predict(X_test)

Those two lines don't tell us whether missing values were handled correctly, whether categorical columns were encoded sensibly, whether a model saw information from its test set, or whether its chosen accuracy metric hides failure on an important minority class. Nor do they tell us whether the model is too complex, too slow, or even solving the right kind of problem.

A trustworthy workflow looks more like this:

Text
Define the prediction or discovery task
        ↓
Inspect the data and identify feature types
        ↓
Create an appropriate train / test split (when supervised)
        ↓
Fit preprocessing and feature engineering on training data
        ↓
Choose simple baselines and candidate models
        ↓
Cross-validate, diagnose, and tune
        ↓
Evaluate once on untouched test data
        ↓
Inspect errors and decide whether added complexity is justified

For clustering or visualization, there may be no target labels or conventional predictive test score. The goal instead is to determine whether the discovered structure is meaningful and stable.

The principles in this article apply to ordinary numeric tables, mixed categorical data, text, regression targets, and unlabeled observations. Each requires different details, but the overarching concern stays the same: learn patterns from the right data, measure what matters, and avoid mistaking a good-looking score for reliable behavior.


1. Preparing data: missing values, categories, and numerical scales

A dataset is a matrix of observations and features, but the columns do not always arrive in a form that an algorithm can use. Consider a table of product orders:

Customer Order value Membership Delivery speed Returned?
A 48.50 Standard Normal No
B — Premium Express Yes
C 79.00 Premium Normal No
D 22.00 Standard — Yes

Order value has a missing numerical entry. Delivery speed has a missing category. Membership is categorical, while Returned? is our binary target. A model needs explicit decisions for all of them.

1.1 Missing data: delete or impute?

Start by measuring missingness rather than immediately deleting rows:

Python
import pandas as pd

missing_counts = df.isna().sum()
missing_percent = df.isna().mean().mul(100)

print(missing_counts)
print(missing_percent.round(1))

Deletion can be reasonable when only a tiny fraction of observations is affected. But df.dropna() may discard many useful rows if different columns have missing values in different places. Removing an entire column can be equally costly when it contains valuable signal.

Imputation replaces missing entries with an estimate:

  • Mean: useful for roughly symmetric numerical distributions; sensitive to extreme values.
  • Median: often preferable for skewed numerical data or outliers.
  • Most frequent: a simple option for categorical features.
  • K-nearest-neighbors imputation: uses similar observations to estimate missing numerical values, at greater computational cost and with a dependence on meaningful distances.
Python
from sklearn.impute import SimpleImputer, KNNImputer

median_imputer = SimpleImputer(strategy="median")
mode_imputer = SimpleImputer(strategy="most_frequent")
knn_imputer = KNNImputer(n_neighbors=5)

A subtle but important point: imputation is learned preprocessing. A column median calculated using all the data includes information from the test set. That makes an evaluation less independent than it appears. Fit the imputer on the training portion only.

Also distinguish between a value that is unknown and one that is not applicable. Missingness can itself contain information. Blindly replacing everything with the mean may erase that distinction.

1.2 Ordinal and nominal categories are not interchangeable

Categorical variables come in two forms:

Kind Example Meaningful order? Typical representation
Ordinal Small, Medium, Large Yes Explicitly ordered values
Nominal Red, Blue, Green No One-hot columns

For ordinal categories, an explicit mapping communicates the order:

Python
size_to_number = {"M": 1, "L": 2, "XL": 3}
df["size_encoded"] = df["size"].map(size_to_number)

Be careful: 1, 2, 3 also imply equal numerical spacing. If that spacing is not appropriate, ordered threshold indicators or another representation may be more suitable.

For nominal categories, assigning arbitrary integers creates a false ordering. Blue = 0, Green = 1, and Red = 2 could imply that Red is "twice" Green or farther from Blue than Green is. A linear or distance-based model might treat that arithmetic as meaningful.

One-hot encoding avoids that problem:

Color Blue Green Red
Blue 1 0 0
Green 0 1 0
Red 0 0 1

Use OneHotEncoder for categorical input features. Use LabelEncoder primarily for the target labels, not as a default encoder for nominal predictors.

Python
from sklearn.preprocessing import OneHotEncoder, LabelEncoder

feature_encoder = OneHotEncoder(handle_unknown="ignore")
target_encoder = LabelEncoder()

handle_unknown="ignore" is useful when a category appears at inference time that was absent during training; it prevents an error, although the unseen category will have an all-zero encoding for that feature's ordinary category columns.

High-cardinality variables, such as a unique ID for nearly every customer, deserve special treatment. One-hot encoding such columns may create huge sparse matrices and may offer little generalizable information. Dropping an ID, grouping rare categories, or using an appropriate alternative encoding can be more useful than mechanically expanding every category.

1.3 Scaling: why feature magnitudes change model behavior

Imagine a nearest-neighbor model that uses Age (18–70) and Annual income (20,000–200,000). With Euclidean distance, income can overwhelm age even if both variables matter.

Two common transformations are:

Min–max scaling to a range such as :

Standardization to zero mean and unit variance (for the fitted training data):

Here and are the training feature's mean and standard deviation. A third option, robust scaling, uses the median and interquartile range (IQR), often helping when features contain large outliers.

Python
from sklearn.preprocessing import (
    MinMaxScaler, StandardScaler, RobustScaler
)

standard_scaler = StandardScaler()
minmax_scaler = MinMaxScaler()
robust_scaler = RobustScaler()

Scaling matters for models that use distances, gradients, or regularization—including KNN, SVMs, logistic regression, and PCA. Ordinary decision trees and random forests generally do not need scaling, because splitting at a threshold is unchanged by a monotonic linear rescaling of a single feature.

Rule: learn all scaling statistics from training data, then reuse the same fitted scaler on validation, test, and later inputs.

1.4 Put transformations in a pipeline, not scattered notebook cells

Self-contained example — mixed numerical and categorical features. This example deliberately uses a tiny synthetic dataset to show the API. It does not establish predictive performance.

Python
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression

X = pd.DataFrame({
    "amount": [24.0, None, 95.0, 15.0, 72.0, 13.0, 88.0, 29.0],
    "visits": [2, 1, 8, 1, 6, 2, 7, 3],
    "member": ["basic", "basic", "premium", "basic",
               "premium", "basic", "premium", "premium"],
})
y = [0, 0, 1, 0, 1, 0, 1, 1]

numeric = Pipeline([
    ("impute", SimpleImputer(strategy="median")),
    ("scale", StandardScaler()),
])
categorical = Pipeline([
    ("impute", SimpleImputer(strategy="most_frequent")),
    ("encode", OneHotEncoder(handle_unknown="ignore")),
])

preprocess = ColumnTransformer([
    ("numeric", numeric, ["amount", "visits"]),
    ("categorical", categorical, ["member"]),
])

model = Pipeline([
    ("preprocess", preprocess),
    ("classifier", LogisticRegression(max_iter=1000)),
])

model.fit(X, y)
print(model.predict(X.iloc[[0]]))

The code is readable because each step has one responsibility: the numerical pipeline imputes and scales; the categorical pipeline imputes and encodes; the final estimator learns the prediction rule. ColumnTransformer puts the processed columns back together.

A pipeline does more than save typing. During cross-validation, it ensures that preprocessing is refitted inside each training fold, instead of leaking information across folds.


2. Choosing useful information: feature selection and dimensionality reduction

High-dimensional data creates several problems. Features may be noisy, irrelevant, highly correlated, or expensive to collect. A model may fit training data closely while failing to generalize.

There are two distinct approaches:

Strategy What survives? Example
Feature selection A subset of original columns Keep 5 out of 30 measurements
Feature extraction New coordinates made from original columns Project 30 measurements onto 2 components

A selected feature often retains its original interpretation. An extracted component usually represents a combination of several original features.

2.1 Regularization: prefer simpler explanations when they perform similarly

Regularization adds a penalty for excessively large model weights. Abstractly:

measures prediction error, penalizes model complexity, and determines how strongly complexity is discouraged.

Two standard penalties are:

L1 regularization can force some coefficients exactly to zero. It therefore doubles as a feature-selection mechanism. L2 regularization usually shrinks many coefficients without eliminating them completely.

In scikit-learn logistic regression, C is the inverse of regularization strength. Smaller C means stronger regularization. In Ridge and Lasso, conversely, a larger alpha means stronger regularization.

Python
from sklearn.linear_model import LogisticRegression

sparse_classifier = LogisticRegression(
    penalty="l1", solver="liblinear", C=0.1
)

Regularization is not a universal substitute for better data. Strong L1 penalties can discard genuinely useful correlated features, and excessive L2 penalties can cause underfitting.

2.2 Sequential feature selection and tree importance

Sequential backward selection (SBS) is a greedy algorithm:

  1. Start with all features.
  2. Remove each candidate feature in turn and evaluate the remaining subset.
  3. Keep the removal that produces the best validation score.
  4. Repeat until the desired number of features remains.

Greedy selection does not guarantee the globally best subset, but it is much more manageable than trying every possible subset. Feature selection must occur inside the training/validation process, not on the complete dataset before splitting.

Tree ensembles offer another view of feature importance. In a random forest, feature_importances_ gives impurity-based contributions to splits:

Python
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel

forest = RandomForestClassifier(n_estimators=500, random_state=1)
forest.fit(X_train, y_train)  # Assumes prepared numerical training data.

print(forest.feature_importances_)

selector = SelectFromModel(forest, threshold=0.1, prefit=True)
X_train_selected = selector.transform(X_train)

The code above is context-dependent: X_train and y_train must already contain numerical features and targets. The threshold is illustrative and should be chosen appropriately.

Do not mistake feature importance for causality. Correlated predictors can share or distort importance, and impurity-based importances can favor some feature types. Model usefulness and business significance are different questions.

2.3 PCA: compress data by retaining major directions of variation

Principal Component Analysis (PCA) is an unsupervised linear transformation. It finds perpendicular directions—principal components—that capture decreasing amounts of variance.

Suppose has observations and original features. A projection from features to components is:

The typical process is to standardize the data, form its covariance matrix, calculate eigenvectors and eigenvalues, rank them, and project onto the top directions.

An eigenvector of covariance matrix satisfies:

The eigenvector gives a direction; the eigenvalue measures the variance associated with that direction. The explained variance ratio of component is:

Self-contained example — PCA on Wine measurements:

Python
from sklearn.datasets import load_wine
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

X, y = load_wine(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X)

pca = PCA(n_components=2)
Z = pca.fit_transform(X_scaled)

print("Original:", X.shape)      # (178, 13)
print("Compressed:", Z.shape)     # (178, 2)
print("Variance ratios:", pca.explained_variance_ratio_)

This snippet uses the full dataset for visualization only. If PCA is used before a predictive model, fit both the scaler and PCA only on the training fold, preferably through a pipeline. Do not compute PCA on all observations before supervised cross-validation.

For interpretation, PCA loadings relate the original variables to components. In scikit-learn, a common standardized-data loading calculation is:

Python
import numpy as np
loadings = pca.components_.T * np.sqrt(pca.explained_variance_)

PCA's limitation: the direction of greatest variance is not necessarily the direction that best distinguishes the target classes. A high-variance feature can be irrelevant to the prediction.

2.4 LDA: project toward class separation rather than total variance

Linear Discriminant Analysis (LDA) for dimensionality reduction is supervised. It uses class labels to seek directions with large separation between classes and small dispersion within each class.

The intuition is to maximize a ratio of between-class scatter to within-class scatter. In a common formulation, discriminant directions are obtained from the generalized eigenvalue problem involving and , or from eigenvectors of when that inverse is well defined.

Python
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

lda = LinearDiscriminantAnalysis(n_components=2)
Z_lda = lda.fit_transform(X_scaled, y)

For classes, the number of discriminant dimensions is at most . A three-class problem therefore has no more than two LDA components.

LDA assumes, in its classical model, approximately normally distributed classes with shared covariance structure. It may still be useful when those assumptions are imperfect. Supervision does not make it universally superior to PCA, particularly with limited observations per class.

Be careful with the acronym: LDA here means Linear Discriminant Analysis. In text topic modeling, the same acronym stands for Latent Dirichlet Allocation, an unrelated algorithm.

2.5 t-SNE: local structure for visualization, not a general prediction pipeline

t-distributed Stochastic Neighbor Embedding (t-SNE) constructs a nonlinear low-dimensional embedding that attempts to preserve nearby relationships between observations.

It is particularly useful for visualizing high-dimensional data such as handwritten digit images. A 64-feature digit image can be represented as a point in a two-dimensional plot. This may reveal groups without specifying a classifier.

Python
from sklearn.datasets import load_digits
from sklearn.manifold import TSNE

digits = load_digits()
embedding = TSNE(
    n_components=2,
    init="pca",
    perplexity=30,
    random_state=123,
).fit_transform(digits.data)

print(embedding.shape)  # (1797, 2)

Class labels can color the resulting scatterplot, but t-SNE does not use those labels during the embedding.

Three interpretation warnings matter:

  • Distances between widely separated groups are not necessarily faithful measurements of original-space distances.
  • Hyperparameters and initialization influence the visualization; different runs may show different layouts.
  • scikit-learn's t-SNE does not expose the reusable out-of-sample transform() interface available in PCA and LDA.

Other manifold-learning approaches, including UMAP, can be useful when the data has nonlinear structure, but they bring their own tuning and interpretation challenges.

2.6 Which dimensionality-reduction technique should you use?

Method Uses labels? Linear? Primary purpose New observations?
L1-based selection Yes Model-dependent Remove some original predictors Yes, using fitted selection
PCA No Yes Compression, denoising, projection Yes
Linear discriminant analysis Yes Yes Separate known classes Yes
t-SNE No No Explore and visualize local patterns Not through scikit-learn's t-SNE API

The correct choice depends on whether you want interpretability, compression, predictive performance, or a visualization. Reducing a 30-feature dataset to two dimensions makes a plot easier to read, but may discard information that matters to your classifier.


3. Evaluating models without fooling ourselves

A model score answers a specific question: How did this model perform on these observations under this evaluation procedure? It does not automatically answer whether the model will work on different customers, patients, or future market conditions.

The quality of the evaluation procedure is therefore part of the quality of the model.

3.1 Training, validation, and test sets have different jobs

The training set fits model parameters. A validation set or cross-validation folds help choose preprocessing, algorithms, and hyperparameters. The test set estimates performance after those choices have been made.

Text
All labeled observations
        |
        +── Training portion ─── CV folds / model selection
        |
        +── Held-out test portion ─── final evaluation only

This is the reason to split data before learning imputation medians, scaling statistics, feature-selection masks, or PCA components. Letting a test observation influence those transformations can inflate performance estimates even when its label was not used directly.

For classification, stratify=y maintains approximately the same class proportions across a random split:

Python
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.30,
    random_state=0,
    stratify=y,
)

A 70/30 split is only one reasonable arrangement; it isn't a universal rule. With scarce data, cross-validation makes better use of the training observations. With very large datasets, smaller test proportions may still yield a precise estimate.

3.2 K-fold cross-validation: evaluate across multiple partitions

In -fold cross-validation, divide the training data into approximately equal folds. For each iteration, fit the complete pipeline on folds and validate on the remaining fold. Every fold serves as validation once.

where is the validation score on fold . The mean offers a more informative summary than one lucky split, while the spread across folds suggests sensitivity to the data partition.

In classification, stratified folds preserve class proportions where possible. StratifiedKFold gives explicit control; cross_val_score handles the evaluation loop for us.

Self-contained example — evaluate a complete pipeline:

Python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression

X, y = load_breast_cancer(return_X_y=True)

pipeline = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000),
)

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipeline, X, y, cv=cv, scoring="accuracy")

print("Fold scores:", scores.round(3))
print(f"Mean: {scores.mean():.3f}; std: {scores.std():.3f}")

Every fold gets its own freshly fitted scaler. That is exactly what we want. This code estimates the pipeline via CV on all available data for demonstration; a real model-selection workflow should set aside an untouched final test portion first.

Leave-one-out cross-validation is an extreme version with : validate on one observation at a time. It can be useful with very small samples but is computationally expensive and not automatically better.

3.3 Diagnose underfitting and overfitting before changing the algorithm

The first diagnostic is the relationship between training and validation performance:

Pattern Likely issue What to investigate
Both scores poor High bias / underfitting Feature quality, regularization, model capacity
Training high, validation much lower High variance / overfitting Complexity, regularization, more representative data
Both high and similar Better generalization signal Confirm on held-out data and relevant metrics

A learning curve plots train and validation scores as the number of training examples increases. A persistent gap may suggest high variance; two low curves may suggest high bias.

A validation curve holds the dataset size fixed and plots performance over a hyperparameter such as the logistic-regression parameter C.

Python
from sklearn.model_selection import learning_curve, validation_curve
import numpy as np

sizes, train_scores, val_scores = learning_curve(
    pipeline, X, y,
    cv=cv,
    train_sizes=np.linspace(0.2, 1.0, 5),
)

c_values = np.logspace(-3, 2, 6)
train_c, val_c = validation_curve(
    pipeline, X, y,
    param_name="logisticregression__C",
    param_range=c_values,
    cv=cv,
)

The two underscores in logisticregression__C mean "the C parameter of the logisticregression step". This naming convention is used throughout scikit-learn pipelines.

These arrays become useful when plotted as training and validation mean curves. Avoid reacting to one noisy point; look for a systematic pattern.

3.4 Hyperparameter tuning: grid, random, and successive halving

Grid search evaluates every combination from a predefined grid. It is simple and reproducible, but grows expensive when each parameter has many possible values.

Randomized search samples from parameter distributions or lists. Under a fixed computational budget, it can examine a larger, more varied search space.

Successive halving starts with many candidates using relatively few resources, discards weaker candidates, and allocates more resources to survivors. It can be efficient, but early measurements are noisy and the resources being allocated must make sense for the estimator.

Search strategy Advantage Limitation
GridSearchCV Exhaustive within the specified grid Combinations grow rapidly
RandomizedSearchCV Flexible budget and distributions May miss good regions
HalvingGridSearchCV Concentrates resources on survivors Experimental API in some versions; early rejection risk
HalvingRandomSearchCV Random exploration plus resource allocation Same early-rejection tradeoff

Self-contained example — SVM search with a training/test split:

Python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, stratify=y, random_state=0
)

svm_pipeline = make_pipeline(StandardScaler(), SVC())

param_grid = [
    {"svc__kernel": ["linear"], "svc__C": [0.1, 1, 10]},
    {
        "svc__kernel": ["rbf"],
        "svc__C": [0.1, 1, 10],
        "svc__gamma": [0.001, 0.01, 0.1],
    },
]

search = GridSearchCV(
    svm_pipeline,
    param_grid=param_grid,
    scoring="accuracy",
    cv=5,
    refit=True,
    n_jobs=-1,
)
search.fit(X_train, y_train)

print("Best settings:", search.best_params_)
print("CV score:", search.best_score_)
print("Held-out score:", search.score(X_test, y_test))

The grid includes a linear SVM, where only C is searched, and an RBF-kernel SVM, where both C and gamma are searched. The best candidate is automatically refitted on the complete training portion because refit=True.

The value from best_score_ is a cross-validation estimate used for selection, not a final test result. The held-out score plays a different role and should not become an excuse to launch repeated rounds of search on the same test set.

3.5 Nested cross-validation: evaluate the selection process itself

Suppose we're comparing SVMs, decision trees, and other model families, while tuning each one. If we tune and report performance on the same validation folds, we risk an optimistic estimate of the search process.

Nested cross-validation adds another layer:

  • Inner loop: selects hyperparameters, for example through GridSearchCV.
  • Outer loop: evaluates the entire hyperparameter-selection procedure on data it did not see during tuning.
Python
from sklearn.model_selection import cross_val_score

# 'search' is a GridSearchCV estimator configured above.
outer_scores = cross_val_score(
    search,
    X_train,
    y_train,
    cv=5,
    scoring="accuracy",
)
print(outer_scores.mean(), outer_scores.std())

This is a context-dependent continuation of the preceding SVM example. It may be much more computationally expensive because the inner search is repeated for every outer fold. That cost can be justified when comparing model-selection procedures or when available data is limited.


4. Classification metrics: measure the errors that matter

A single accuracy number can hide serious mistakes. Suppose only 1% of transactions are fraudulent. A model that labels every transaction as legitimate achieves 99% accuracy while detecting zero fraud cases.

To understand the behavior, we need the confusion matrix:

Predicted negative Predicted positive
Actually negative True negative (TN) False positive (FP)
Actually positive False negative (FN) True positive (TP)

From these four counts, we obtain several distinct measurements.

4.1 Precision, recall, F1, specificity, and MCC

Precision asks: of everything predicted positive, how much was truly positive? Recall, or sensitivity, asks: of the actual positive cases, how many did we find? F1 balances the two through their harmonic mean.

A numerical example clarifies their disagreement. Suppose there are 100 actual positive cases. A model catches 80 of them, while producing 20 false alarms.

That sounds balanced. But if missing a true positive is extremely costly, 80% recall may still be inadequate. The metric is not the business objective; it is a tool for understanding it.

Matthews correlation coefficient (MCC) incorporates all four confusion-matrix cells:

When its denominator is nonzero, MCC ranges from (inverse agreement) through 0 (no correlation) to (perfect classification). It can be informative on imbalanced datasets.

4.2 ROC curves, AUC, and thresholds

A binary classifier often produces scores or probabilities, not just hard labels. Changing the decision threshold changes the number of false positives and false negatives.

The receiver operating characteristic (ROC) curve plots:

across thresholds. Its area, ROC AUC, summarizes ranking quality. Around 0.5 corresponds to random ranking in the usual binary interpretation; 1.0 is perfect ranking.

ROC AUC does not tell you that the default threshold is right, nor does it guarantee useful precision when positives are extremely rare. In imbalanced settings, inspect the precision–recall tradeoff and class-specific errors as well.

Self-contained example — calculate several metrics:

Python
from sklearn.metrics import (
    confusion_matrix, classification_report,
    roc_auc_score, matthews_corrcoef,
)

# Actual labels and illustrative probabilistic predictions.
y_true = [0, 0, 0, 1, 1, 1, 1, 0]
p_positive = [0.1, 0.7, 0.2, 0.8, 0.4, 0.9, 0.6, 0.3]
y_pred = [int(p >= 0.5) for p in p_positive]

print(confusion_matrix(y_true, y_pred))
print(classification_report(y_true, y_pred, zero_division=0))
print("ROC AUC:", roc_auc_score(y_true, p_positive))
print("MCC:", matthews_corrcoef(y_true, y_pred))

classification_report summarizes precision, recall, F1, and support. For multiclass problems, distinguish micro averages (aggregate decisions), macro averages (equal weight per class), and weighted averages (weight classes by support). These give different answers when class frequencies differ.

4.3 Imbalanced data: weights, resampling, and evaluation design

Common options are:

  1. Class weighting: assign more cost to errors on underrepresented classes, for estimators that support it.
  2. Upsampling: repeat minority-class training examples.
  3. Downsampling: remove some majority-class training examples.
  4. Synthetic oversampling: create new minority-class observations, as in SMOTE.
Python
from sklearn.linear_model import LogisticRegression

weighted_model = LogisticRegression(
    class_weight="balanced",
    max_iter=1000,
)

Balancing does not manufacture trustworthy information: repeated observations do not add new facts, and synthetic examples can introduce artifacts. Class weighting can improve recall while worsening precision. Compare both types of error on untouched validation data.

Critical safeguard: perform oversampling or undersampling within each training fold. Duplicating minority-class rows before splitting risks putting near-identical observations in both train and validation sets. The same warning applies to SMOTE. Libraries such as imbalanced-learn provide pipeline components designed for this situation.


5. Ensembles: why combining models can outperform a single one

Ensembles exploit the fact that different models—or different versions of the same model—make different mistakes. If those mistakes are not perfectly correlated, combining predictions can reduce error.

Not all ensembles learn in the same way:

Text
Voting:     train separate models → combine their predictions
Bagging:    train on bootstrap datasets → average or vote
Boosting:   train sequentially → each learner improves the current ensemble
Stacking:   train base models → train another model to combine predictions

5.1 Voting: hard labels and soft probabilities

With hard voting, each model votes for a class. With soft voting, the models' predicted class probabilities are averaged (possibly with weights) before selecting the most probable class.

Python
from sklearn.ensemble import VotingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

voter = VotingClassifier(
    estimators=[
        ("lr", make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))),
        ("tree", DecisionTreeClassifier(max_depth=3, random_state=1)),
        ("knn", make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))),
    ],
    voting="soft",
)

This snippet defines a model; it needs training data and a voter.fit(X_train, y_train) call to produce predictions. Scaling is applied only to the models that benefit from it.

For three base models predicting classes [0, 0, 1], ordinary hard voting returns 0. But with voting weights [0.2, 0.2, 0.6], the third learner can determine the final decision. The point is not that one weight choice is correct, but that weighting expresses an assumption about model reliability and should itself be validated.

Voting gains depend on diversity. Three identical models that always make the same errors are effectively one model repeated three times.

5.2 Bagging: train independently on bootstrap samples

Bootstrap aggregating, or bagging, creates several training sets by sampling observations with replacement. Each base learner is trained independently, and their predictions are aggregated.

The replacement rule matters: the same training observation can appear multiple times in a bootstrap sample, and some observations may not appear at all.

Bagging usually reduces variance and is especially effective with unstable base learners such as deep, unpruned decision trees. It is less effective against high bias: averaging many severely underfitting models does not automatically fix their inability to represent the pattern.

Python
from sklearn.ensemble import BaggingClassifier
from sklearn.tree import DecisionTreeClassifier

bag = BaggingClassifier(
    estimator=DecisionTreeClassifier(random_state=1),
    n_estimators=200,
    max_samples=1.0,
    bootstrap=True,
    random_state=1,
)

A random forest takes this idea further by adding randomness to the features considered at tree splits. That can reduce correlation between trees, increasing the benefit of averaging.

5.3 AdaBoost: pay more attention to mistakes

Adaptive Boosting (AdaBoost) trains weak learners sequentially. After each learner, misclassified observations receive greater emphasis for the next round. The final prediction combines the learners through weights reflecting their performance.

A typical weak learner is a decision stump: a decision tree with max_depth=1.

For the traditional binary formulation, the weight of a weak learner with weighted error is:

A low-error weak learner receives a larger positive vote. The formulation assumes the relevant error range and handles edge cases separately.

Python
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier

ada = AdaBoostClassifier(
    estimator=DecisionTreeClassifier(max_depth=1, random_state=1),
    n_estimators=100,
    learning_rate=0.1,
    random_state=1,
)

AdaBoost can turn weak learners into a much stronger classifier, but its emphasis on difficult examples can also make it sensitive to noisy labels and outliers.

5.4 Gradient boosting: fit the direction of loss improvement

Gradient boosting is also sequential, but it does not simply raise weights on misclassified observations. Each new model aims to approximate the negative gradient of a differentiable loss function with respect to current predictions.

A general additive update is:

where is the current ensemble, is the next learner, and is the learning rate (or shrinkage factor).

For squared-error regression, the negative gradients correspond to ordinary residuals:

Suppose a model predicts 250 for a target of 300. The residual is 50. If the next learner predicts a correction of 50 and , the ensemble prediction becomes .

For classification, the mathematics changes: a common gradient-boosting formulation works with log-odds and logistic loss, not a direct addition of probability values.

Python
from sklearn.ensemble import GradientBoostingClassifier

gb = GradientBoostingClassifier(
    n_estimators=200,
    learning_rate=0.05,
    max_depth=3,
    random_state=1,
)

Two controls deserve attention: more estimators can improve fit but cost time, while a smaller learning rate often requires more rounds. Trees that are too deep can overfit.

5.5 XGBoost and modern boosting implementations

XGBoost is an optimized gradient-boosting implementation designed for efficient tree construction and strong predictive performance, especially on many tabular-data problems. Related implementations include LightGBM and CatBoost.

Python
# Requires: pip install xgboost
from xgboost import XGBClassifier

xgb_model = XGBClassifier(
    n_estimators=300,
    learning_rate=0.05,
    max_depth=4,
    random_state=1,
    eval_metric="logloss",
)

This code only defines an estimator. It still requires compatible labeled training data and fit(). XGBoost's label requirements and defaults vary by task and version; do not assume a binary-classification setup applies unchanged to every multiclass problem.

Finally, stacking trains a meta-learner to combine base-model predictions. To avoid leakage, the meta-learner should learn from appropriate out-of-fold predictions, not simply the base models' overfitted outputs on their own training data. scikit-learn provides StackingClassifier and StackingRegressor.

Method Fits learners Main strength Main caution
Voting Independently Combine diverse hypotheses Correlated errors limit gains
Bagging Independently on bootstrap samples Reduce variance Does not solve high bias
Random forest Bootstraps + random feature choices Decorrelate decision trees Interpretation becomes harder
AdaBoost Sequentially, weighted mistakes Strengthen simple learners Noise/outlier sensitivity
Gradient boosting Sequentially, loss gradients Strong nonlinear tabular models Tuning and overfitting risk
XGBoost Optimized gradient boosting Efficient, flexible training More settings and dependencies
Stacking Base learners + meta-learner Learn combination rules Needs leakage-safe meta-features

Engineering question: if an ensemble improves cross-validation accuracy by only a tiny amount, does that gain justify slower inference, larger artifacts, and more complicated maintenance? Predictive quality is only one part of system quality.


6. Classical NLP: turn raw language into useful numerical features

Natural language arrives as strings, while traditional classifiers expect numerical feature matrices. A useful classical NLP pipeline is:

Text
Raw reviews
   ↓
Cleaning and tokenization
   ↓
Bag-of-words or TF-IDF representation
   ↓
Logistic regression or another classifier
   ↓
Positive / negative prediction

Consider sentiment analysis on movie reviews: the target is whether a review is positive or negative, but the input is free-form text. The central engineering choice is how to represent text without discarding the information relevant to the label.

6.1 Bag-of-words: a document becomes a vector of counts

The bag-of-words representation constructs a vocabulary from the training documents and counts how often each word appears.

For example:

Review excellent awful movie
“excellent movie” 1 0 1
“awful movie” 0 1 1
“excellent excellent movie” 2 0 1

If the vocabulary has 20,000 terms, each document becomes a 20,000-dimensional row. Most entries are zero, so scikit-learn stores the matrix in a sparse format rather than allocating a dense array unnecessarily.

Self-contained example:

Python
from sklearn.feature_extraction.text import CountVectorizer

reviews = [
    "The movie was excellent",
    "The movie was awful",
    "Excellent direction and excellent acting",
]

vectorizer = CountVectorizer()
X_counts = vectorizer.fit_transform(reviews)

print(vectorizer.get_feature_names_out())
print(X_counts.toarray())  # Only for a tiny demonstration.

Bag-of-words is simple and often surprisingly effective. Its principal weakness is that it discards word order. “Not good” and “good not” have the same unigram counts, despite their different language use.

N-grams partly address this limitation by including consecutive sequences of words. ngram_range=(1, 2) includes both individual words and two-word sequences, such as not good.

6.2 TF-IDF: frequent words are not always informative words

A word such as “movie” may appear in nearly every movie review. It has high frequency but little power to distinguish sentiment. Term Frequency–Inverse Document Frequency (TF-IDF) discounts terms that appear across many documents while retaining terms that stand out within a particular document.

A conceptual version is:

Undefined control sequence \operatorname

One common IDF definition is:

Undefined control sequence \operatorname

Here is the number of documents, and is the number of documents containing term . In practice, scikit-learn uses a smoothed variant by default and L2-normalizes resulting document vectors; the exact numbers therefore depend on the library's settings.

Python
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer(
    ngram_range=(1, 2),
    max_df=0.95,
    min_df=1,
)
X_tfidf = vectorizer.fit_transform(reviews)

TfidfVectorizer combines token counting and TF-IDF weighting. An alternative is CountVectorizer followed by TfidfTransformer.

As with numerical preprocessing, fit the vocabulary and IDF weights only on training text. Fitting them on test reviews before evaluation leaks information about the supposedly unseen corpus.

6.3 Cleaning, tokenization, stemming, and stop words

Text cleaning may involve stripping HTML, standardizing case, and handling punctuation. But cleaning is not the same as removing every unusual character: emoticons such as :) or :( may carry sentiment.

Self-contained example — minimal preprocessing function:

Python
import re

def clean_review(text: str) -> str:
    text = re.sub(r"<[^>]*>", " ", text)
    emoticons = re.findall(r"(?::|;|=)-?(?:\)|\(|D|P)", text)
    words = re.sub(r"[^a-z0-9]+", " ", text.lower()).strip()
    return (words + " " + " ".join(emoticons)).strip()

print(clean_review("<p>Great movie!</p> :)"))

That function is appropriate only as a teaching example for mostly English text. It intentionally strips accented and non-Latin characters; real multilingual or international text requires a Unicode-aware approach.

Three terms are often confused:

  • Tokenization divides text into units, usually words or subword pieces.
  • Stemming reduces related words to a crude stem, e.g. connected and connecting may share a reduced form.
  • Lemmatization aims to map words to a dictionary base form, often using grammatical context.

Stop-word removal removes common words such as “the” or “and,” but it can remove relevant information if applied indiscriminately. Sentiment classification especially cares about negations such as not and never. It is better to compare preprocessing choices by validation performance than to treat aggressive cleaning as automatically beneficial.

6.4 Train a text classifier as one pipeline

Logistic regression works naturally with high-dimensional sparse text features. Put TF-IDF and the classifier together so the vocabulary is learned independently in each cross-validation fold.

Self-contained example — deliberately tiny teaching corpus:

Python
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

texts = [
    "Wonderful story and excellent acting",
    "I loved the film and the music",
    "Brilliant and moving performances",
    "A great movie with a lovely ending",
    "Terrible acting and a boring story",
    "I hated the film and the dialogue",
    "Awful direction and weak performances",
    "A disappointing and tedious movie",
]
labels = [1, 1, 1, 1, 0, 0, 0, 0]

sentiment_model = make_pipeline(
    TfidfVectorizer(ngram_range=(1, 2)),
    LogisticRegression(max_iter=1000),
)
sentiment_model.fit(texts, labels)

print(sentiment_model.predict(["Excellent film and acting"]))

This demonstrates an end-to-end prediction call, not a meaningful accuracy result. Eight training reviews are too few for a reliable sentiment model. A realistic experiment needs a large labeled corpus, proper splits, and cross-validation.

For tuning, parameters are accessed through pipeline step names such as tfidfvectorizer__ngram_range and logisticregression__C. You can compare unigrams against bigrams, alternative tokenizers, TF-IDF settings, and regularization values.

6.5 Out-of-core learning: when the document collection won't fit in memory

A growing vocabulary can be expensive. Two tools make incremental text classification possible:

  • HashingVectorizer maps tokens into a fixed number of feature positions without storing a growing vocabulary. The tradeoff is possible hash collisions and less direct interpretability.
  • SGDClassifier.partial_fit() updates a model from successive mini-batches rather than repeatedly fitting on the complete dataset.

Self-contained example — two incremental mini-batches:

Python
import numpy as np
from sklearn.feature_extraction.text import HashingVectorizer
from sklearn.linear_model import SGDClassifier

batches = [
    (["excellent movie", "awful movie"], [1, 0]),
    (["great acting", "boring acting"], [1, 0]),
]

vectorizer = HashingVectorizer(n_features=2**18)
classifier = SGDClassifier(loss="log_loss", random_state=1)

for texts_batch, labels_batch in batches:
    X_batch = vectorizer.transform(texts_batch)
    classifier.partial_fit(
        X_batch, labels_batch, classes=np.array([0, 1])
    )

X_new = vectorizer.transform(["great movie"])
print(classifier.predict(X_new))

This tiny script demonstrates the API, not useful model quality. In a real streaming pipeline, batches would come from a document iterator or stored data stream, and you would separately monitor performance and distribution changes.

A useful distinction: incremental learning is not necessarily online deployment. partial_fit() describes the update mechanism; a production system may still update periodically from saved batches.

6.6 Topic modeling with Latent Dirichlet Allocation

Sentiment analysis is supervised; topic modeling is generally unsupervised. Instead of being told that a review is about crime or comedy, a topic model tries to discover recurring combinations of words.

Latent Dirichlet Allocation (LDA) represents documents as mixtures of topics and topics as distributions over words. A review might be 70% associated with a horror topic and 30% with a family-drama topic. Those percentages are model estimates, not human-established genre labels.

Python
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation

corpus = [
    "The detective solved the murder and arrested the suspect",
    "Police investigated the crime and found evidence",
    "The actor gave a funny comedy performance",
    "The comedian delivered jokes and funny scenes",
    "The police pursued the suspect in the crime story",
    "The comedy actor delivered an amusing performance",
]

counts = CountVectorizer(stop_words="english").fit_transform(corpus)
lda_topics = LatentDirichletAllocation(
    n_components=2,
    random_state=123,
)
mixtures = lda_topics.fit_transform(counts)
print(mixtures.round(2))

The code is self-contained, but the toy corpus is too small to establish stable, interpretable topics. In practice, examine top words for each topic, compare plausible topic counts, and check example documents before assigning labels such as “crime” or “comedy.”

A frequently overlooked limitation: topics represent statistical patterns in word co-occurrence. They may reflect sentiment, writing style, or common expressions rather than the semantic categories you hoped to discover.


7. Regression: predicting continuous values and understanding residuals

Classification predicts classes; regression predicts continuous targets, such as a house sale price. A practical housing dataset might include living area, overall quality, basement size, condition, and a flag for central air conditioning.

Before building a model, inspect distributions, missing values, extreme prices, scatterplots, and correlations. A positive correlation between floor area and sale price suggests a relationship, but it is not a causal claim and need not be exactly linear.

7.1 Linear regression: start with a transparent baseline

Simple linear regression uses one feature:

Multiple linear regression uses several:

The coefficients describe how the prediction changes with a one-unit change in a feature holding the other included features fixed. Interpretation depends on scale and correlation among features.

Ordinary least squares (OLS) finds coefficients that minimize squared residuals:

Undefined control sequence \operatorname

In matrix notation, an analytical solution may be written as:

when is invertible and the intercept is represented appropriately. Practical libraries use numerically robust least-squares solvers rather than explicitly taking this inverse. The coefficients can also be optimized iteratively by gradient descent.

For a simple coefficient , a gradient step is:

where is the learning rate. The optimization rule is the same basic idea used in many other machine-learning models.

Self-contained regression example — synthetic linear relationship:

Python
import numpy as np
from sklearn.linear_model import LinearRegression

X = np.array([[500], [800], [1100], [1400], [1700]], dtype=float)
y = np.array([90, 120, 151, 181, 210], dtype=float)  # Price in $1,000s

reg = LinearRegression()
reg.fit(X, y)

print("Slope:", reg.coef_[0])
print("Intercept:", reg.intercept_)
print("Predicted $1,000s:", reg.predict([[1250]])[0])

The numbers are deliberately illustrative. A house's size is not enough for a realistic valuation; location and numerous other variables can matter.

7.2 RANSAC: reduce sensitivity to unusual observations

OLS squares residuals, so a few extreme points may strongly influence the fitted line. RANSAC (Random Sample Consensus) repeatedly fits models on randomly selected subsets and checks which observations fall within an acceptable error tolerance.

These accepted observations are called inliers; others are treated as outliers for the fit.

Python
from sklearn.linear_model import RANSACRegressor, LinearRegression

robust = RANSACRegressor(
    estimator=LinearRegression(),
    max_trials=100,
    min_samples=0.95,
    random_state=123,
)
robust.fit(X, y)  # Assumes a numerical feature matrix and regression targets.

print("Inliers:", robust.inlier_mask_)

The code is context-dependent and follows the preceding single-feature regression example. In a meaningful application, choose residual_threshold (or an appropriate automatic threshold) with the target's scale and error distribution in mind.

RANSAC is useful when the dominant data relationship is credible and some observations are corrupted. It is not a license to discard rare but legitimate cases, and it does not guarantee better out-of-sample performance.

7.3 Residuals and the four common regression metrics

A residual is the difference between the actual value and the predicted value:

Plot residuals against predictions. If they form an obvious curve, the linear model may be missing a nonlinear relationship. If residual spread increases with the predicted value, errors may be heteroscedastic. Unusually large residuals may indicate outliers, data errors, or an omitted feature.

Four metrics are especially useful:

Metric Formula Interpretation
MAE $\frac{1}{n}\sum e_i
MSE Strongly penalizes large errors; squared units
RMSE Larger errors matter more; original target units
Improvement over predicting the mean

Suppose three actual values are and predictions are . Then absolute errors are and squared errors are :

These are worked arithmetic examples, not benchmark scores.

A positive means the model beats the mean baseline on the evaluated data. An of 0.75 means a 75% reduction in summed squared error relative to that baseline; negative is possible when predictions are worse than the baseline.

Python
from sklearn.metrics import (
    mean_absolute_error, mean_squared_error, r2_score
)

actual = [10, 20, 30]
predicted = [12, 18, 29]

mae = mean_absolute_error(actual, predicted)
mse = mean_squared_error(actual, predicted)
rmse = mse ** 0.5
r2 = r2_score(actual, predicted)

print(f"MAE={mae:.3f}, MSE={mse:.3f}, RMSE={rmse:.3f}, R2={r2:.3f}")

Use the metric that fits the decision. A property app might prefer MAE because stakeholders understand dollar error; RMSE adds extra cost to rare, very large mistakes. Evaluate the errors across relevant subgroups, not just in aggregate.

7.4 Ridge, Lasso, and Elastic Net: regularize regression coefficients

Linear regression can overfit when many correlated features compete to explain relatively few observations. The regression versions of L1 and L2 regularization are:

Ridge — L2 penalty:

Lasso — L1 penalty:

Elastic Net combines the two. In scikit-learn, l1_ratio controls the relative contribution of L1 and L2.

Python
from sklearn.linear_model import Ridge, Lasso, ElasticNet

ridge = Ridge(alpha=1.0)
lasso = Lasso(alpha=1.0)
elastic = ElasticNet(alpha=1.0, l1_ratio=0.5)

These models are particularly sensitive to the relative scales of their input features. Put StandardScaler inside the training pipeline before fitting them. Select alpha using validation data instead of assuming that 1.0 is optimal.

7.5 Polynomial regression: nonlinear in the input, linear in coefficients

If a relationship curves, a straight line may underfit. Polynomial regression expands the features:

The output is nonlinear as a function of , but the model remains linear in the coefficients .

Python
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

quadratic = make_pipeline(
    PolynomialFeatures(degree=2, include_bias=False),
    LinearRegression(),
)
quadratic.fit(X, y)  # Uses the synthetic regression data above.

Polynomial expansion can fit curved structure without changing the underlying regression estimator. But high degrees can add many terms, amplify noise, and overfit. Use validation performance rather than training fit to choose the degree.

7.6 Regression trees and random forests

A regression tree recursively partitions feature space and predicts a value, often the average target of training observations in the reached leaf. Trees can capture threshold effects and nonlinear interactions without manual polynomial features.

Random forest regression averages many trees trained with bootstrap samples and feature randomness. Averaging typically helps stabilize predictions that would vary widely across individual deep trees.

Python
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor

tree = DecisionTreeRegressor(max_depth=3, random_state=1)
forest = RandomForestRegressor(
    n_estimators=300,
    random_state=1,
    n_jobs=-1,
)

These estimators need a fit(X_train, y_train) call, followed by evaluation on unseen data. They generally do not require feature standardization, though handling missing or categorical values still depends on the chosen implementation.

A random forest may improve test performance over a simple linear model when the underlying relationship is nonlinear. That does not make a forest universally superior: its predictions are harder to interpret, and it can still overfit or perform poorly outside the training distribution.


8. Clustering: discover structure when labels do not exist

So far, most models have learned to predict a known target. Clustering changes the question: given only the observations, can we identify groups whose members are meaningfully similar?

Applications include grouping customers by behavior, organizing documents by topic, finding similarities among products, and exploring unusual observations. But without ground-truth labels, "good clustering" is not always objectively defined. Similarity must be expressed through the features and a suitable distance or density concept.

8.1 K-means: represent each group by a centroid

K-means partitions observations into clusters. Each cluster is represented by its centroid, the mean of its assigned observations.

The algorithm alternates between two steps:

  1. Assignment: send every observation to its nearest centroid.
  2. Update: recompute each centroid as the mean of its assigned observations.

Continue until assignments or centroid positions stop changing materially, or a maximum iteration limit is reached.

Its objective is the within-cluster sum of squared distances, called inertia in scikit-learn:

Undefined control sequence \boldsymbol

Here is the assigned cluster of observation , and Undefined control sequence \boldsymbol is that cluster's centroid.

Self-contained example — three synthetic groups:

Python
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

X, _ = make_blobs(
    n_samples=150,
    centers=3,
    cluster_std=0.5,
    random_state=0,
)

kmeans = KMeans(
    n_clusters=3,
    init="k-means++",
    n_init=10,
    random_state=0,
)
labels = kmeans.fit_predict(X)

print("Cluster sizes:", [(labels == i).sum() for i in range(3)])
print("Centroids:\n", kmeans.cluster_centers_)
print("Inertia:", kmeans.inertia_)

K-means is efficient and understandable, but it tends to prefer compact, roughly spherical clusters. It may split elongated groups incorrectly, and extreme outliers can move the centroids.

8.2 K-means++ and why initialization matters

K-means can reach different local solutions depending on where its initial centroids start. K-means++ chooses initial centroids more carefully, favoring candidate points relatively far from already selected centers.

It does not guarantee the global best solution, but it usually makes initialization more robust. Running multiple initializations through n_init provides another safeguard.

Feature scaling matters here too: K-means uses distances, so a large-range feature can dominate the clustering even when that feature isn't the most meaningful.

8.3 Choosing the number of clusters: elbow and silhouette

A natural question is: How many clusters should there be?

The elbow method fits K-means for several candidate values of and plots inertia against . Inertia must decrease (or remain unchanged) as increases, because the algorithm is allowed to assign more centers. Look for the point beyond which adding another cluster produces diminishing improvement.

Python
inertias = []
for k in range(1, 11):
    model = KMeans(n_clusters=k, n_init=10, random_state=0)
    model.fit(X)
    inertias.append(model.inertia_)

print(inertias)

This is a context-dependent continuation of the generated blobs example. An elbow can be subjective or absent entirely.

Silhouette analysis asks whether each observation is closer to its own cluster than to another cluster. For observation :

  • : average distance to other observations within its cluster.
  • : smallest average distance to observations in another cluster.

Silhouette coefficients normally range from to :

Value What it suggests
Near +1 Well placed within its cluster
Around 0 Between nearby clusters
Negative Potentially closer to another cluster
Python
from sklearn.metrics import silhouette_score, silhouette_samples

average = silhouette_score(X, labels)
individual = silhouette_samples(X, labels)
print("Mean silhouette:", average)

This snippet assumes X and labels are the results of the previous K-means example. Silhouette scores are not a universal truth about customer segments or scientific categories; they assess separation according to the selected representation and distance metric.

8.4 Hard versus fuzzy assignment

Standard K-means performs hard clustering: each observation has exactly one assigned cluster.

Fuzzy C-Means takes a softer approach. An observation receives membership degrees across clusters, such as 0.7 for cluster A, 0.2 for B, and 0.1 for C. Those membership values sum to one for each observation.

A fuzziness parameter controls how sharply the membership is concentrated. This can be useful when groups overlap naturally, although the extra flexibility also introduces complexity. A fuzzy membership score should not automatically be interpreted as a calibrated probability of belonging to a real-world category.

8.5 Hierarchical clustering: build a tree of similarity

Unlike K-means, hierarchical clustering builds a nested structure. In agglomerative clustering, each observation begins as its own cluster, and the algorithm repeatedly merges the closest groups.

What does closest mean for two groups rather than two points? That depends on the linkage:

Linkage Distance between groups
Single Distance between the closest pair of members
Complete Distance between the farthest pair
Average Average pairwise distance
Ward Increase in within-cluster squared error

The resulting dendrogram shows the order of merges and the dissimilarity at which they occurred. By cutting the tree at different heights, we can inspect different numbers of clusters without repeating the entire conceptual search from scratch.

Self-contained example — a small dendrogram:

Python
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram

rng = np.random.default_rng(123)
X = rng.random((5, 3)) * 10

Z = linkage(X, method="complete", metric="euclidean")
dendrogram(Z)
plt.title("Hierarchical clustering")
plt.show()

The same idea can be used with scikit-learn:

Python
from sklearn.cluster import AgglomerativeClustering

hierarchical = AgglomerativeClustering(
    n_clusters=3,
    metric="euclidean",
    linkage="complete",
)
labels = hierarchical.fit_predict(X)

This second snippet follows the five-observation example; it simply demonstrates the interface. In a realistic analysis, choose a number of clusters based on the dendrogram, domain interpretation, and possibly additional validation.

Hierarchical clustering is attractive when the hierarchy itself carries meaning, but some linkage methods are sensitive to noise, and building a full hierarchy can be expensive for very large datasets.

8.6 DBSCAN: discover irregular shapes and label noise

K-means struggles when groups curve around each other. DBSCAN instead defines clusters by regions of sufficient local density.

Two parameters control the idea:

  • eps: radius of a local neighborhood.
  • min_samples: minimum number of observations in the neighborhood (including the observation itself in scikit-learn) needed for a core point.

The algorithm distinguishes:

  • Core points: have enough nearby observations.
  • Border points: can be reached from dense regions but lack enough neighbors to be core points themselves.
  • Noise points: not density-connected to any identified cluster; labeled -1 in scikit-learn.

DBSCAN does not require specifying the number of clusters. It can discover connected curved groups, like the familiar two half-moon shapes.

Self-contained example — compare K-means with DBSCAN on curved data:

Python
import numpy as np
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans, DBSCAN

X, _ = make_moons(n_samples=200, noise=0.05, random_state=0)

kmeans_labels = KMeans(
    n_clusters=2, n_init=10, random_state=0
).fit_predict(X)

dbscan_labels = DBSCAN(
    eps=0.2, min_samples=5, metric="euclidean"
).fit_predict(X)

print("K-means labels:", np.unique(kmeans_labels))
print("DBSCAN labels:", np.unique(dbscan_labels))
print("DBSCAN noise points:", np.sum(dbscan_labels == -1))

K-means typically separates the two moons with relatively simple regions; DBSCAN can follow the curved shapes because it uses density connectivity rather than distance to a single center.

The tradeoffs are substantial. If eps is too small, genuine groups fragment and many observations become noise. If it is too large, distinct groups can merge. Clusters with very different densities are especially hard to capture with one global radius. Distance calculations also become less informative in high-dimensional spaces—the curse of dimensionality affects K-means and hierarchical methods too.

8.7 Choosing a clustering method is part of defining similarity

Method Need upfront? Irregular shapes? Noise handling? Useful when
K-means Yes Usually poor No explicit noise class Compact, roughly spherical groups
Fuzzy C-Means Yes Usually poor Soft memberships, not explicit noise detection Overlapping groups
Hierarchical Not to build the tree Depends on linkage Not explicit Nested relationships matter
DBSCAN No Often good Labels noise Curved/density-connected structure

No metric can rescue a meaningless feature representation. Clustering customers by raw transaction IDs will not become meaningful just because the algorithm finds three clusters. Start by asking what similarity should mean in the application, then choose the features, scaling, distance measure, and algorithm accordingly.


9. Putting the pieces together: a defensible classical ML workflow

These methods are not a checklist in which every item must be used. They are options for specific problems. A simple logistic regression with sound preprocessing may be preferable to a complex ensemble; a PCA plot may help inspect data while offering no improvement to classification accuracy; DBSCAN may reveal structure that K-means misses, but only with a sensible density scale.

A practical end-to-end supervised workflow looks like this:

  1. Define the target and relevant costs. Is this classification or regression? Is missing a positive worse than generating a false alarm?
  2. Inspect the raw data. Examine missingness, distributions, outliers, class balance, and categorical cardinality.
  3. Create the held-out split. Preserve the test data for final evaluation.
  4. Construct leakage-safe preprocessing. Use ColumnTransformer and Pipeline for the appropriate numerical, categorical, and text transformations.
  5. Establish a baseline. Train a simple interpretable estimator before optimizing complexity.
  6. Use cross-validation for model selection. Compare candidates, learning curves, and validation curves with suitable metrics.
  7. Tune only what matters. Use GridSearchCV, randomized search, or another budget-aware procedure.
  8. Consider feature reduction or ensembles when justified. PCA, L1 selection, bagging, or boosting are tools, not mandatory upgrades.
  9. Report independent test results and error breakdowns. Include enough detail to understand what the model gets wrong.
  10. Evaluate the operational tradeoff. Accuracy, training cost, inference latency, explainability, and maintainability all matter.

A complete baseline you can actually run

The following script ties the most important practices together: a real bundled dataset, train/test separation, preprocessing inside a pipeline, cross-validated hyperparameter search, final held-out metrics, and the confusion matrix.

Self-contained example — binary classification, end to end:

Python
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    confusion_matrix, classification_report, roc_auc_score
)

X, y = load_breast_cancer(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X, y,
    test_size=0.3,
    stratify=y,
    random_state=42,
)

pipeline = make_pipeline(
    StandardScaler(),
    LogisticRegression(max_iter=2000),
)

search = GridSearchCV(
    estimator=pipeline,
    param_grid={"logisticregression__C": [0.01, 0.1, 1.0, 10.0]},
    scoring="roc_auc",
    cv=5,
    refit=True,
)
search.fit(X_train, y_train)

predictions = search.predict(X_test)
probabilities = search.predict_proba(X_test)[:, 1]

print("Selected C:", search.best_params_)
print("Cross-validated ROC AUC:", round(search.best_score_, 3))
print("Held-out ROC AUC:", round(roc_auc_score(y_test, probabilities), 3))
print("Confusion matrix:\n", confusion_matrix(y_test, predictions))
print(classification_report(y_test, predictions))

This example has no external dataset download. It is a baseline, not a medical decision system. Also, in the bundled breast-cancer dataset, the encoded positive class (1) represents benign cases. If your operational objective is detecting malignant cases, explicitly set the positive-class convention, corresponding score direction, and metrics accordingly. Treat the disease-oriented labels as a dataset illustration, not advice for medical use.

The mechanics are more important than any particular score it prints: only the training portion influences scaling, parameter selection, and model fitting; the test portion is used afterward for the first final assessment.

Failure patterns worth recognizing early

Symptom Likely place to investigate
Unexpectedly spectacular CV score Leakage, duplicated records, inappropriate split, target-derived features
Good training score, poor CV score Overfitting, irrelevant features, overcomplex model
Poor training and CV scores Underfitting, inadequate features, wrong task formulation
Strong accuracy, terrible minority recall Class imbalance, thresholds, metric choice
Stable CV, weak held-out test result Distribution differences, small samples, selection bias
K-means produces implausible customer groups Scaling, feature relevance, distance, unsuitable cluster geometry
t-SNE shows dramatic clusters that disappear on rerun Hyperparameter sensitivity and visualization instability
Large text vocabulary creates memory problems Sparse representations, hashing, incremental learning
Regression errors grow with price Heteroscedasticity, missing structure, outliers, target scale
Ensemble adds complexity but little value Highly correlated base errors, weak baseline comparison

Closing thought

The most useful classical machine-learning skills are not simply knowing the names of algorithms. They are knowing which problem an algorithm addresses, what information it is allowed to learn from, and how to test whether the apparent improvement is real.

Missing-value imputation and scaling make data usable. Regularization and dimensionality reduction control complexity. Cross-validation and proper metrics make model comparison more credible. Ensembles can combine different learners. TF-IDF turns text into numerical inputs; regression predicts continuous outcomes; clustering exposes structure without labels.

The connecting principle is simple: prepare carefully, start with a baseline, validate honestly, and add complexity only when the evidence supports it.

← Back to all blogs

ML Engineering · AI Engineering

Pandas, from First Principles to Real-World Data: A Practical Guide for Data Science and Machine Learning

Learn how to turn raw tables into reliable datasets. Start with Series and DataFrames, build an intuition for indexing and filtering, clean imperfect records, combine tables, explore distributions, engineer features, and prepare data for machine learning.

Scope: This guide synthesizes four Pandas tutorials and earlier practical learning discussions. It targets broad, everyday competence rather than memorizing the entire API. The small datasets are original teaching examples modeled on the source exercises, not copies of the original datasets or reported real-world findings. Core examples use Pandas 2.2-compatible syntax. Optional formats and libraries are identified separately. The ML and defensive-validation examples extend the source material to connect Pandas to practical engineering.

How to use this tutorial

Learning stage Sections Main goal
Foundations 1–8 Understand tables, indexes, filters, sorting and edits
Cleaning and transformation 9–12 Fix missing, invalid and duplicate values; create features
Analysis and combining data 13–18 Group, join, reshape, work with dates and explore distributions
Worked projects 19–22 Combine operations in realistic analysis and cleaning tasks
ML and engineering 23–25 Prepare features safely, understand performance, translate SQL concepts
Independent practice 26–27 Test your understanding with 40 practical challenges

If you are new to Pandas, work through the stages in order. If you already know the basics, use the examples as a reference and attempt the challenges before rereading their relevant sections.

The big idea: Pandas is a programmable table

Think about an Excel spreadsheet or a SQL table. A row represents an observation, a column represents an attribute, and a cell contains a value. Pandas gives us a way to perform these operations in Python, reproduce them, and build them into a larger application or machine-learning workflow.

If a company gives you a million customer records, you probably do not want to inspect each one manually. You might need to find missing values, identify invalid ages, remove duplicate customer IDs, attach information from another table, calculate average spending by region, or generate features for a prediction model. Each of those tasks is a table operation.

Text
Raw data (CSV, Excel, JSON, Parquet)
    ↓
Load into a DataFrame
    ↓
Inspect schema, distributions and data quality
    ↓
Select, filter, clean and validate
    ↓
Combine tables and engineer features
    ↓
Aggregate, analyze and visualize
    ↓
Export or prepare features and target for ML

Pandas is primarily a tool for data manipulation and analysis, not a machine-learning model. Scikit-learn and PyTorch take over when we need to fit models. A reliable model begins with reliable data, which is why the work before fit() matters so much.

1. Getting started: installation and the working dataset

Install Pandas and NumPy in your Python environment. NumPy is useful for numerical operations and conditional features. If you work interactively, a Jupyter notebook allows you to execute one cell at a time, inspect intermediate tables, and quickly try different approaches.

Shell
python -m pip install pandas numpy

For a fresh local project, an isolated environment is preferable. With standard Python, create one using python -m venv .venv, activate it using .venv\Scripts\activate in Windows PowerShell (or source .venv/bin/activate on macOS/Linux), and install packages inside it. In PowerShell the explicit activation script is .\.venv\Scripts\Activate.ps1.

Alternatively, with uv already installed:

Shell
uv init
uv add pandas numpy
uv run python main.py

uv init initializes the project; uv add creates or synchronizes its environment as needed. uv venv explicitly creates an environment. In VS Code, install the Python and Jupyter extensions, create an .ipynb file, and select the correct kernel. Google Colab is another option if you prefer a browser-based notebook. Notebook cells share state, so running cells out of order can produce confusing results. Restart the kernel and run all cells to verify a notebook from a clean state.

Import Pandas with its conventional alias, pd. Throughout the tutorial, we will use the following small employee table as a common starting point.

Python
import pandas as pd
import numpy as np

print(pd.__version__)

employees = pd.DataFrame({
    "EmployeeID": [101, 102, 103, 104, 105],
    "Name": ["Alice", "Bob", "Charlie", "David", "Emma"],
    "Age": [25, 30, 35, 28, 40],
    "Salary": [5000, 7000, 6000, 4500, 9000],
    "Department": ["IT", "HR", "IT", "Sales", "HR"]
})

df = employees.copy()
print(df)
Index EmployeeID Name Age Salary Department
0 101 Alice 25 5000 IT
1 102 Bob 30 7000 HR
2 103 Charlie 35 6000 IT
3 104 David 28 4500 Sales
4 105 Emma 40 9000 HR

Reading the code: pd.DataFrame() creates a table. The dictionary keys become column names and the corresponding lists supply values. employees and df are ordinary variable names, not special Pandas keywords. A DataFrame can have many columns with different data types.

Run the Python setup above first. Most subsequent examples use df, which remains the original five-row teaching table unless explicitly changed. Examples that demonstrate changes use separate variables. Run the examples in order; new project datasets are defined in their respective sections. Shell commands belong in a terminal, not a Python cell.

2. Series, DataFrames, indexes and data alignment

Pandas has two fundamental structures: a Series, which is a one-dimensional labeled array, and a DataFrame, which is a two-dimensional labeled table. A Series has an index and values. A DataFrame has row labels and column labels. Index labels identify rows; they need not be integers, consecutive, or unique.

Creating a Series

Python
scores = pd.Series([85, 92, 78], index=["Alice", "Bob", "Charlie"])
print(scores)
print(scores.loc["Bob"])  # 92: label
print(scores.iloc[1])      # 92: position

The Series can also come from a dictionary, where keys automatically become labels.

Python
scores = pd.Series({"Alice": 85, "Bob": 92, "Charlie": 78})
scores.loc["Charlie"] += 5
print(scores[scores >= 85])  # Alice and Bob

An ordinary Python list stores ordered values. A Series additionally associates values with labels, supports vectorized operations, and can represent missing data. When two Series are added, Pandas aligns matching index labels rather than blindly pairing the first elements together.

Python
base = pd.Series([100, 200], index=["A", "B"])
bonus = pd.Series([30, 10], index=["B", "A"])
print(base + bonus)  # A: 110, B: 230

This is convenient when labels represent identities, but dangerous when you assume calculations are strictly positional. Unmatched labels typically produce missing values. Check the indexes before combining independently created Series.

Creating DataFrames in different ways

Besides dictionaries of lists, you can create tables from a list of dictionaries (one dictionary per row) or from a two-dimensional list with column names.

Python
records = pd.DataFrame([
    {"Name": "Alice", "Age": 25},
    {"Name": "Bob", "Age": 30}
])

matrix = pd.DataFrame(
    [[1, 2], [3, 4]],
    columns=["A", "B"],
    index=["row1", "row2"]
)

print(records)
print(matrix)

Compare these expressions:

Expression Result type Meaning
df DataFrame Entire table
df["Salary"] Series One column
df[["Salary"]] DataFrame One-column table
df[["Name", "Salary"]] DataFrame Two-column table
df.iloc[0] Series First row
df.iloc[[0]] DataFrame First row as a table

The double brackets in df[["Name", "Salary"]] are not a special operator. The inner brackets create a Python list of column names; the outer brackets pass that list to the DataFrame. The difference between a one-dimensional Series and a two-dimensional DataFrame matters in ML, where input features generally need shape (n_samples, n_features).

Setting and resetting an index

Python
indexed = df.set_index("EmployeeID")
print(indexed.loc[103])  # Charlie's row
restored = indexed.reset_index()
print(restored.head())

set_index() moves a column into the row index by default. reset_index() turns the previous index into a column; reset_index(drop=True) discards it. Resetting an index does not remove duplicates. Keep a meaningful ID as a column when you need it for joins or auditability. If the index represents identity, verify that it is unique before assuming one label selects one record.

3. Loading and saving data: CSV, JSON, Excel and Parquet

Most practical Pandas work starts with a file. CSV is a widely supported text format, JSON is common in APIs, Excel is useful for collaboration, and Parquet is a compressed column-oriented format often used in analytics pipelines. Feather is another efficient binary table format.

The following example writes the teaching table to a temporary directory, then loads it back. It does not require an external dataset and does not overwrite any existing files.

Python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    root = Path(folder)
    csv_path = root / "employees.csv"
    json_path = root / "employees.json"

    df.to_csv(csv_path, index=False)
    df.to_json(json_path, orient="records")

    csv_df = pd.read_csv(csv_path)
    json_df = pd.read_json(json_path, orient="records")
    selected = pd.read_csv(csv_path, usecols=["Name", "Salary"])
    indexed_csv = pd.read_csv(csv_path, index_col="EmployeeID")
    print(csv_df.head())

index=False prevents the default row index from becoming an unwanted extra CSV column. usecols loads only requested columns. index_col selects an existing column as the index while loading. The JSON orient="records" represents each row as an object.

A few useful CSV loading parameters are worth understanding:

Argument Purpose
sep=";" Read a semicolon-separated file
header=None Treat the first row as data rather than headers
names=[...] Supply your own column names
usecols=[...] Load a subset of columns
dtype={"CustomerID": "string"} Preserve IDs, including leading zeros
na_values=["?", "unknown"] Interpret selected tokens as missing
parse_dates=["Date"] Attempt to load selected columns as dates
nrows=100 Inspect only the first 100 records
encoding="utf-8" Specify the file's text encoding

These options are schema decisions: an ID such as 0012 is usually an identifier, not the number twelve. Do not mark a legitimate category as missing merely because it resembles a placeholder.

Other formats

Excel .xlsx operations typically require openpyxl; Parquet and Feather can use pyarrow. Install these optional dependencies if you need those formats.

Shell
python -m pip install openpyxl pyarrow

This optional Excel example uses a temporary file with two worksheets. sheet_name selects a worksheet by name or position; sheet_name=None returns a dictionary of all worksheets.

Python
with TemporaryDirectory() as folder:
    excel_path = Path(folder) / "employees.xlsx"
    with pd.ExcelWriter(excel_path, engine="openpyxl") as writer:
        df.to_excel(writer, sheet_name="Employees", index=False)
        df[["Name", "Salary"]].to_excel(writer, sheet_name="Payroll", index=False)
    payroll = pd.read_excel(excel_path, sheet_name="Payroll")
    print(payroll)

The following optional Parquet and Feather patterns require pyarrow. They are intentionally commented out so that the core tutorial can run without that optional package. Uncomment them in a writable working directory if you have installed it.

Python
# df.to_parquet("employees.parquet", index=False)
# parquet_df = pd.read_parquet("employees.parquet")
# df.reset_index(drop=True).to_feather("employees.feather")
# feather_df = pd.read_feather("employees.feather")

A URL to an accessible raw CSV can be passed to pd.read_csv() as well. For GitHub, use the raw file URL, not the HTML page showing the file. Network access and permissions must be available. CSV is easy to share, but may not preserve types accurately; Parquet often preserves types and is more compact and faster to read for analytical workloads. The actual size and speed depend on the data, compression and environment, so benchmark rather than assume.

4. Inspecting a dataset before changing it

Before filtering or cleaning, discover the table's shape, columns, data types, missing values and distributions. Inspection is not a ceremonial step: it tells you what operations are actually valid.

Python
print(df.head())           # First five rows
print(df.tail(2))          # Last two rows
print(df.sample(n=2, random_state=42))
print(df.shape)            # (5, 5): rows, columns
print(df.size)             # 25 cells (including missing cells)
print(len(df))             # 5 rows
print(df.columns.tolist()) # Column names
print(df.index.tolist())   # Row labels
print(df.dtypes)           # Column data types

df.info()                  # Prints schema and non-null counts
print(df.describe())       # Numeric summary statistics
print(df.describe(include="all"))

sample() selects random rows, with random_state making repeated calls reproducible for the same input and environment. Unlike head(), a sample can expose problems away from the beginning of a file. info() prints a report and returns None; don't expect print(df.info()) to give another table. shape, size, columns, index, and dtypes are attributes rather than methods, so they do not take parentheses.

describe() summarizes numeric distributions by default. Its usual output includes count, mean, sample standard deviation, minimum, the 25th/50th/75th percentiles, and maximum. For the salaries, sorted values are 4500, 5000, 6000, 7000 and 9000. The mean is 6300 and the median is 6000. The median is the middle value, whereas the mean is affected more by extreme observations.

Python
print(df["Salary"].mean())       # 6300.0
print(df["Salary"].median())     # 6000.0
print(df["Salary"].std())        # Sample standard deviation, ddof=1
print(df["Salary"].min())        # 4500
print(df["Salary"].max())        # 9000
print(df["Salary"].quantile(0.25))  # 5000.0
print(df["Salary"].quantile([0.05, 0.5, 0.95]))
print(df["Department"].unique())
print(df["Department"].nunique())  # 3
print(df["Department"].mode())     # HR and IT: a Series
print(df["Department"].value_counts())

The 5th and 95th percentiles delimit the central part of a distribution; ties and interpolation mean the retained fraction may differ from exactly 90%. They are useful exploratory thresholds, not automatically correct outlier-removal rules. For ML, if percentile thresholds form part of preprocessing, learn them from training data only.

Department Frequency
IT 2
HR 2
Sales 1

.unique() returns distinct values, .nunique() counts distinct values (excluding missing values by default), and .value_counts() gives their frequencies. .mode() can return several values in a tie. If you need ordinary Python values for another function, df["Department"].unique().tolist() gives a list of the distinct departments; .tolist() on a Series preserves repeated entries. Use .value_counts(normalize=True, dropna=False) for relative frequencies including missing categories. df.to_string() prints an untruncated representation, which is useful for tiny tables but not sensible for millions of records.

5. Selection: understand the brackets, loc and iloc

Selection answers which rows and columns do I want to see? There are two main indexers: loc uses labels or Boolean masks, and iloc uses integer positions. The syntax for both is df.loc[rows, columns] or df.iloc[rows, columns].

Python
print(df["Salary"])                       # One column, Series
print(df[["Name", "Salary"]])             # Two columns, DataFrame
print(df.loc[2, "Name"])                  # Charlie
print(df.loc[1:3, ["Name", "Salary"]])    # Labels 1, 2, 3
print(df.loc[:, ["Name", "Department"]])  # All rows, selected columns
print(df.iloc[0:3, 1:4])                  # Positions 0,1,2 and 1,2,3
print(df.iloc[[0, 4], [1, 3]])            # Alice and Emma, names/salaries
print(df.iloc[::2])                       # Every second row
Indexer Uses End of a slice Example
.loc[] Index and column labels Inclusive for label slices when valid df.loc[0:2] gives 0, 1, 2
.iloc[] Integer positions Exclusive df.iloc[0:2] gives positions 0, 1
.at[] One scalar by labels Not for slicing df.at[0, "Name"]
.iat[] One scalar by positions Not for slicing df.iat[0, 1]

In the default table, the labels and positions happen to match. That is not always true. If you set EmployeeID as the index, indexed.loc[101] selects Alice, while indexed.iloc[0] selects the first row regardless of its label. indexed.loc[0] fails because no employee has index label zero.

Python
print(indexed.loc[101, "Salary"])  # 5000
print(indexed.iloc[0, 2])          # 5000: Salary is now column position 2
print(df.at[0, "Name"])            # Alice
print(df.iat[0, 1])                # Alice

Use loc and iloc for most work. at and iat are useful shortcuts when you specifically need a single scalar and labels are unambiguous. A safe lookup in an indexed table can handle KeyError when a requested ID does not exist.

Python
try:
    print(indexed.loc[999])
except KeyError:
    print("Employee not found")

Common mistake: df.iloc[10] refers to the eleventh row, not the tenth. df.iloc[:10] selects up to the first ten rows. Avoid ambiguous integer indexing into a Series; use .iloc[0] for its first element and .loc[label] for a label.

6. Filtering: from a Boolean mask to SQL-like queries

Filtering is a two-step process. First, a comparison produces a Series of Boolean values. Then Pandas keeps the rows for which the mask is true.

Python
mask = df["Age"] > 30
print(mask)
print(df[mask])
Name Age Age > 30
Alice 25 False
Bob 30 False
Charlie 35 True
David 28 False
Emma 40 True

So df[df["Age"] > 30] simply means: calculate a mask using the Age column, and apply it to the whole DataFrame. The result contains Charlie and Emma. A filtered table preserves original row labels unless you reset the index.

Multiple conditions, membership and exclusion

Python
print(df[(df["Department"] == "IT") & (df["Age"] > 30)])
print(df[(df["Department"] == "IT") | (df["Salary"] > 8000)])
print(df[df["Department"].isin(["IT", "HR"])])
print(df[~df["Department"].isin(["IT", "HR"])])
print(df[df["Salary"].between(5000, 7000)])
print(df.loc[df["Age"] > 30, ["Name", "Salary"]])
print((df["Age"] > 30).sum())  # 2 matching rows

Use & for elementwise AND, | for OR, and ~ to negate a Boolean mask. Python's scalar and, or, and not do not combine whole Series as intended. Parenthesize each comparison. Equality is ==, not assignment =. isin() replaces a chain of equality comparisons, while between() tests a range including both endpoints by default. Summing a Boolean mask counts true entries (with missing-value behavior depending on the dtype).

Filtering using query

Python
minimum_salary = 6000
print(df.query("Salary >= @minimum_salary and Department == 'IT'"))

spaced = df.rename(columns={"Salary": "Monthly Salary"})
print(spaced.query("`Monthly Salary` >= 7000"))

query() expresses the condition in a string. Use @ to access a Python variable from the surrounding scope and backticks for column names containing spaces. Boolean indexing remains the more universal option, particularly for complex or dynamically constructed conditions. Do not pass an untrusted string directly to query().

7. Sorting, ranking and comparing records

Sorting changes the order of rows; filtering changes which rows are retained. An ascending numeric sort goes from small to large, whereas descending goes from large to small.

Python
print(df.sort_values("Salary", ascending=False))
print(df.sort_values(["Department", "Salary"], ascending=[True, False]))
print(df.sort_values("Salary", ascending=False).head(2))
print(df.nlargest(2, "Salary"))
print(df.nsmallest(2, "Salary"))
print(df.sort_values("Salary").sort_index())

The second example groups equal departments next to each other in alphabetical order, then sorts employees within each department by descending salary. The two highest-paid employees are Emma and Bob. sort_index() sorts by index labels, not by cell values. The top/bottom helpers are convenient when you only need a few extreme rows.

Ranking is different: it creates a number showing a record's relative position without necessarily reordering the table.

Python
ranked = df.assign(
    SalaryRank=df["Salary"].rank(ascending=False, method="dense")
)
print(ranked[["Name", "Salary", "SalaryRank"]])

Emma receives rank 1. The dense method gives tied observations the same rank and leaves no gap before the next distinct value. The default average method averages tied ranks. Other tie rules include min, max, and first. Select one based on the meaning of the ranking rather than treating tied rows as automatically distinct.

8. Editing tables: adding, updating, deleting, renaming and copying

Pandas operations often return a new object instead of modifying the existing one. Explicitly assigning the returned object is usually the clearest style. Direct assignments, such as df.loc[...] = ..., mutate the selected DataFrame.

Python
edited = df.copy()
edited["Country"] = "Azerbaijan"   # Broadcast one value to all rows
edited["AnnualSalary"] = edited["Salary"] * 12
edited["Bonus"] = [100, 200, 150, 100, 300]  # One value per row

edited.loc[edited["Department"] == "IT", "Bonus"] = 250
edited.loc[edited["Salary"] < 5000, "Salary"] = 5000
edited["AnnualSalary"] = edited["Salary"] * 12  # Refresh derived column
edited = edited.rename(columns={"Salary": "MonthlySalary"})
edited = edited.drop(columns=["Bonus"])
edited = edited.drop(index=3)
print(edited)

You can also update a single cell by position or label. The following operations use another copy of the original data:

Python
position_edit = df.copy()
position_edit.iloc[0, 3] = 5100  # First row, fourth column (Salary)
position_edit.at[1, "Salary"] = 7100
position_edit.iat[2, 3] = 6200
print(position_edit[["Name", "Salary"]])

A scalar is broadcast to every row; a list assigned as a column must have the correct length. Assigning a Series aligns by index. Note that derived columns do not automatically recalculate when their input columns change: here AnnualSalary is explicitly recomputed after updating salary. drop(index=3) deletes a row with label 3; it does not necessarily delete the fourth row. drop(columns=[...]) deletes columns.

Why copy matters

Python
original = df.copy()
alias = original
alias.loc[0, "Salary"] = 1234
assert original.loc[0, "Salary"] == 1234

independent = original.copy()
independent.loc[0, "Salary"] = 9999
assert original.loc[0, "Salary"] == 1234

alias = original does not create an independent table; both variables point to the same object. copy() creates a separate DataFrame for ordinary scalar tabular data. Nested mutable Python objects inside object-dtype cells can still share underlying references, so this is not a general-purpose recursive deep copy of arbitrary Python objects.

Avoid chained assignment such as df[df["Age"] > 30]["Salary"] = 0. Use one .loc operation on the actual table you intend to edit. This avoids ambiguous behavior across Pandas versions and copy-on-write settings. inplace=True is available on some methods; it returns None for those operations, so df = df.drop(..., inplace=True) would lose your DataFrame reference. Prefer explicit reassignment unless there is a reason to do otherwise.

Adding rows

Python
new_employee = pd.DataFrame([{
    "EmployeeID": 106, "Name": "John", "Age": 29,
    "Salary": 6500, "Department": "IT"
}])
expanded = pd.concat([df, new_employee], ignore_index=True)
print(expanded.tail(2))

The result has six rows. ignore_index=True generates a fresh sequential index. The historical DataFrame.append() method was removed in Pandas 2.0; use pd.concat() instead. When adding many records, build a list of dictionaries and concatenate once rather than repeatedly reallocating a growing DataFrame in a loop.

9. Missing values: detect first, then decide what they mean

Missing data is one of the most common real-world problems. Pandas may represent missing values with np.nan, pd.NA, None, or NaT (for missing datetimes), depending on the data type. A missing value is not automatically zero, an empty string, or a negative result. A missing salary means we do not know the salary; a salary of zero means something quite different.

Create a small imperfect version of the employee data.

Python
missing = df.copy()
missing.loc[1, "Salary"] = np.nan
missing.loc[3, "Salary"] = np.nan
missing.loc[4, "Department"] = None

print(missing)
print(missing.isna())
print(missing.isna().sum())
print(missing.isna().mean() * 100)  # Percentage missing per column
print(missing[missing["Salary"].isna()])
print(missing[missing["Salary"].notna()])
print(missing[missing.isna().any(axis=1)])
Column Missing count Missing percentage
EmployeeID 0 0%
Name 0 0%
Age 0 0%
Salary 2 40%
Department 1 20%

isnull() and notnull() are aliases for isna() and notna(). Use isna() and notna() rather than == np.nan, which is not a reliable missing-value test. any(axis=1) checks whether at least one column is missing in each row. all(axis=1) checks whether every column is missing in a row. A Boolean column's mean is the fraction of true entries when all entries are known.

Removing and filling missing values

Python
complete = missing.dropna()  # Remove rows with any missing value
known_salary = missing.dropna(subset=["Salary"])
filled_constant = missing.fillna({"Salary": 5000, "Department": "Unknown"})

filled_stat = missing.copy()
filled_stat["Salary"] = filled_stat["Salary"].fillna(
    filled_stat["Salary"].median()
)
filled_stat["Department"] = filled_stat["Department"].fillna("Unknown")
print(filled_stat)

In this example the known salaries are 5000, 6000 and 9000, so their median is 6000. The two missing salaries in filled_stat become 6000. A dictionary allows different replacements for different columns. dropna(subset=["Salary"]) only considers the Salary column; a missing Department alone will not cause a row to be dropped.

Method When it may make sense Main caution
Drop rows Critical values are absent and enough valid data remains May introduce selection bias
Constant filling A domain-specific default or explicit Unknown category Zero is not necessarily a meaningful default
Mean filling Roughly symmetric numeric distribution Sensitive to extreme values
Median filling Skewed numeric distribution Reduces apparent variability
Mode filling A reasonable frequent categorical value May hide important missingness patterns
Leave missing Downstream model or analysis supports missingness Verify compatibility

.count() counts non-missing values; len() counts rows regardless of missingness. For example, missing["Salary"].count() is 3, but len(missing) is 5. This distinction is important when calculating averages, group counts and rates.

Interpolation for ordered data

Python
measurements = pd.Series([10.0, np.nan, 30.0, np.nan, 50.0])
print(measurements.interpolate(method="linear", limit_area="inside"))
# 10, 20, 30, 40, 50

Linear interpolation fills an interior gap using its neighbors. This makes sense for some measurements taken in order, not for unrelated employees or unordered categories. If sampling intervals are irregular, a time-indexed method may be more appropriate than equal row spacing. ffill() carries the last known value forward, and bfill() carries the next value backward. Both can be useful, but neither is automatically justified. Interpolation and backward filling can use future observations, which may leak information into a forecasting model. The ML section explains why imputation statistics also must be fitted only on training data.

10. Cleaning data types, text and invalid values

A value that looks numeric can still be stored as a string. For instance, the string "7,000" is not the same as integer 7000. A column of numbers mixed with text may be read as an object or string column, preventing sensible arithmetic. Inspect types with df.dtypes or df.info().

Python
raw_salary = pd.Series(["$5,000", "7,000", "unknown", "4500", None])
clean_salary = pd.to_numeric(
    raw_salary.astype("string").str.replace(r"[$,]", "", regex=True),
    errors="coerce"
)
print(clean_salary)
print(clean_salary.isna())

First remove currency symbols and separators, then convert using pd.to_numeric(). errors="coerce" turns unparseable values into missing values instead of aborting the operation. Do not confuse this with successfully recovering the original number: investigate what failed to convert. In a European-style number such as 1.234,50, the comma and period may have a different meaning, so this specific cleaning rule is not universally applicable.

Casting types with astype

Python
print(df["Age"].astype("float64"))
print(clean_salary.astype("Int64"))  # Nullable integer type
print(pd.Series([0, 1, 0, 1]).astype(bool))
print(df["Department"].astype("category"))

astype() casts a column to a specified dtype when its values are compatible. Pandas' nullable Int64 (capital I) supports missing integer values; ordinary NumPy int64 does not. astype(bool) is appropriate for verified numeric 0/1 values, but not for strings such as "False", which are nonempty and can become true. Validate the allowed values before casting. Repeated categorical labels may benefit from category; use explicit categories when their order matters.

Text cleaning and pattern filtering

Python
text = pd.Series(["  Alice Smith  ", "BOB JONES", "charlie brown", None],
                 dtype="string")
normalized = text.str.strip().str.lower()
print(normalized)
print(normalized.str.upper())
print(normalized.str.capitalize())
print(normalized.str.title())
print(normalized.str.len())
print(normalized.str.split().str[0])  # First token, not always a legal first name

The .str accessor applies string operations to each element of the Series. Chaining operations such as strip() and lower() helps normalize formatting. .str.split().str[0] extracts the first token; real names are more complicated than a first-token rule, so treat this as a string operation, not a universal method of identifying first names.

Python
print(df[df["Name"].str.startswith("A", na=False)])
print(df[df["Name"].str.endswith("a", na=False)])
print(df[df["Name"].str.contains("AL", case=False, regex=False, na=False)])
print(df[df["Name"].str.contains(r"^[AE]", na=False)])
print(df[df["Name"].str.contains(r"Alice|Bob", na=False)])

The final filter keeps names that start with A or E. case=False ignores capitalization. na=False prevents a missing string from becoming an unknown mask value. regex=False interprets the search string literally; regular expressions are useful for structured patterns.

Regex example Meaning
^[AEIOUaeiou] Starts with a vowel
son$ Ends in son
Alice|Bob Contains Alice or Bob (regex alternation; the backslash here only escapes the Markdown table separator)
\d+ One or more digits
^[A-Za-z]+$ Entire value contains ASCII letters only
(.)\1 Repeated consecutive character

Regex is a supporting skill, not a prerequisite for Pandas. Begin with exact matching, contains(), startswith(), endswith() and simple replacement. Reach for regex when a pattern actually requires it.

Replace exact values, map categories and validate ranges

Python
raw_departments = pd.Series(["Information Technology", "HR", "Sales", "?"])
print(raw_departments.replace({"Information Technology": "IT", "?": pd.NA}))

codes = pd.Series(["IT", "HR", "X"])
labels = {"IT": "Information Technology", "HR": "Human Resources"}
print(codes.map(labels))
print(codes.replace(labels))

replace() changes matching values and leaves other values alone. map() translates each element through a mapping; an unmapped key usually becomes missing. .str.replace() changes substrings within strings, whereas .replace() is useful for entire categorical values. When cleaning categories, preserve the original if the transformation is uncertain.

Python
ratings = pd.DataFrame({"App": ["A", "B", "C", "D"],
                        "Rating": [4.5, 7.0, -1.0, 3.9]})
invalid_rating = ~ratings["Rating"].between(0, 5)
ratings.loc[invalid_rating, "Rating"] = np.nan
print(ratings)

Ratings outside the permitted range are invalid under the teaching example's schema. They are changed to missing rather than clipped to an apparently valid value. In a real data source, check whether an invalid value is evidence of a parsing error or shifted column before fixing it. Never silently overwrite or delete the raw input.

11. Duplicates: define what makes two records the same

Duplicate detection has two separate questions: are two entire rows identical, and do two rows represent the same real-world entity? Those are not always the same question.

Python
repeated = pd.DataFrame({
    "App": ["Notes", "Notes", "Calendar", "Calendar", "Maps"],
    "Reviews": [100, 130, 50, 50, 20],
    "Rating": [4.2, 4.3, 4.0, 4.0, 4.5]
})
print(repeated.duplicated())
print(repeated[repeated.duplicated(subset=["App"], keep=False)])
print(repeated.drop_duplicates())

duplicated() returns a Boolean mask. Its default marks later duplicates; keep=False marks all rows belonging to a duplicate group. drop_duplicates() returns a table after removing duplicates. subset defines the columns used to compare rows.

Python
best_records = (
    repeated.sort_values("Reviews", ascending=False, kind="stable")
            .drop_duplicates(subset=["App"], keep="first")
            .reset_index(drop=True)
)
print(best_records)
App Reviews Rating
Notes 130 4.3
Calendar 50 4.0
Maps 20 4.5

This explicitly implements the app-store exercise's policy of preferring the record with the most reviews. It is a teaching rule, not proof that the highest-review row is always the correct one. If the table has reliable update timestamps, choosing the latest valid record may be better. Ties should be resolved with an explicit secondary criterion where relevant. Do not deduplicate solely on names when different people can share a name; prefer a verified stable key.

12. Creating features: arithmetic, conditions and custom functions

Feature engineering converts existing data into more useful representations. Pandas can compute an entire new column in one operation. This is generally clearer and faster than writing a Python loop to visit each row individually.

Python
features = df.copy()
features["AnnualSalary"] = features["Salary"] * 12
features["SalaryThousands"] = features["Salary"] / 1000
features["Senior"] = features["Age"] >= 35
features["IncomeLevel"] = np.where(features["Salary"] > 6000, "High", "Other")
print(features[["Name", "AnnualSalary", "Senior", "IncomeLevel"]])

np.where(condition, value_if_true, value_if_false) applies the condition elementwise. Here Bob and Emma get the High label; Charlie has exactly 6000 and therefore receives Other. For nullable conditions or missing numeric values, decide how unknown values should be handled instead of automatically assigning them to the false branch.

Multiple categories can be represented through thresholds. A compact np.select() example and a custom Python function accomplish the same teaching objective in different ways.

Python
features["SalaryBand"] = np.select(
    [features["Salary"] < 5000, features["Salary"] < 8000],
    ["Low", "Middle"],
    default="High"
)

# Equivalent custom function for this complete numeric column.
def salary_band(salary):
    if salary < 5000:
        return "Low"
    if salary < 8000:
        return "Middle"
    return "High"

features["BandFromFunction"] = features["Salary"].apply(salary_band)
assert features["SalaryBand"].equals(features["BandFromFunction"])
print(features["Age"].apply(lambda age: age + 1))

Series.apply() calls a function with individual values in this example. A lambda is simply a short anonymous function. If a built-in arithmetic operation already accomplishes the task, features["Age"] + 1 is simpler than .apply(lambda age: age + 1).

Row-wise versus column-wise operations

A custom rule may depend on more than one column. DataFrame.apply(..., axis=1) passes each row to your function as a Series. axis=0 applies the function to each column instead.

Python
def eligible_for_bonus(row):
    return row["Age"] >= 30 and row["Department"] == "IT"

features["Eligible"] = features.apply(eligible_for_bonus, axis=1)
features["EligibleVectorized"] = (
    (features["Age"] >= 30) & (features["Department"] == "IT")
)
assert features["Eligible"].equals(features["EligibleVectorized"])
print(features[["Name", "Eligible"]])

Charlie is the only eligible employee under this invented rule. The row-wise function can be useful for complex logic; the vectorized version is preferable when the condition is already expressible with array operations.

The two meanings of axis

Python
print(df[["Age", "Salary"]].sum(axis=0))  # One result per column
print(df.isna().sum(axis=1))               # One result per row

With aggregation, axis=0 reduces across rows for each column, and axis=1 reduces across columns for each row. The latter example counts missing cells per employee. Do not add unrelated quantities such as Age and Salary merely because a row-wise sum is possible.

Iterating over rows when necessary

Python
for index, row in df.iterrows():
    print(index, row["Name"], row["Salary"])

for row in df.itertuples(index=False):
    print(row.Name, row.Salary)

iterrows() yields an index and a Series for each row, which may not preserve every original dtype in the row. itertuples() generally has lower Python overhead. Avoid mutating the returned row and expecting the DataFrame to update; use vectorized assignment or .loc instead. Loops can still be appropriate for inherently sequential work or external operations, such as sending one request per record. For arithmetic on millions of cells, prefer vectorized Pandas or NumPy operations and measure actual performance rather than assuming every .str or .apply operation is fast.

13. Grouping and aggregation: split, apply, combine

Suppose you want to know the average salary in each department. You could filter each department one by one, but groupby() expresses the entire calculation at once. It groups rows with the same key, applies an operation to each group, and combines the results.

Python
print(df.groupby("Department")["Salary"].mean())
print(df.groupby("Department")["Salary"].sum())
print(df.groupby("Department")["Salary"].min())
print(df.groupby("Department")["Salary"].max())
print(df.groupby("Department")["Salary"].count())
print(df.groupby("Department").size())
Department Employee count Total salary Average salary
HR 2 16000 8000
IT 2 11000 5500
Sales 1 4500 4500

The groupby() call creates a GroupBy object, not the final summary. Selecting Salary and calling mean() then computes the mean for each group. Use .size() to count rows and .count() to count non-null values in a column. Group keys with missing values are excluded by default; dropna=False includes a missing-key group.

Summarize several columns at once

Python
summary = df.groupby("Department").agg({
    "Salary": ["mean", "min", "max"],
    "Age": "mean"
})
print(summary)

named_summary = df.groupby("Department", as_index=False).agg(
    Employees=("EmployeeID", "size"),
    MeanSalary=("Salary", "mean"),
    TotalSalary=("Salary", "sum"),
    MeanAge=("Age", "mean")
)
print(named_summary.sort_values("TotalSalary", ascending=False))

The first example creates hierarchical column labels when several functions apply to a column. Named aggregation in the second creates readable flat column names. as_index=False keeps the group key as a regular column; .reset_index() is an alternative after grouping.

Python
print(df.mean(numeric_only=True))
print(df.select_dtypes(include="number").columns.tolist())
print(features.groupby(["Department", "IncomeLevel"], as_index=False)
              .agg(People=("EmployeeID", "size")))

numeric_only=True restricts applicable aggregations to numeric columns; select_dtypes() lets you explicitly choose types. A numeric ID can still be meaningless to average, so selecting numeric columns is not a replacement for understanding their role. Grouping by two columns produces one group per combination of keys, like SQL's GROUP BY Department, IncomeLevel.

Aggregation versus transform

An aggregation usually reduces the number of rows. Sometimes you need the group statistic on every original record, such as each employee's difference from their department's average salary. Use transform() to produce a Series aligned to the original rows.

Python
relative = df.copy()
relative["DepartmentMean"] = relative.groupby("Department")["Salary"].transform("mean")
relative["DifferenceFromMean"] = relative["Salary"] - relative["DepartmentMean"]
relative["DepartmentMax"] = relative.groupby("Department")["Salary"].transform("max")
print(relative[["Name", "DepartmentMean", "DifferenceFromMean"]])
print(relative[relative["Salary"] == relative["DepartmentMax"]])
Name DepartmentMean DifferenceFromMean
Alice 5500 −500
Bob 8000 −1000
Charlie 5500 500
David 4500 0
Emma 8000 1000

The maximum comparison retains all employees tied for highest salary within their department. Unlike agg(), transform() preserves the original row count, so its output can be assigned directly as a column.

Group-specific missing-value filling and custom group rules

Python
by_department = missing.copy()
group_median = by_department.groupby("Department")["Salary"].transform("median")
by_department["Salary"] = by_department["Salary"].fillna(group_median)
by_department["Salary"] = by_department["Salary"].fillna(missing["Salary"].median())
print(by_department)

# A custom rule using one selected Series per group.
spread = df.groupby("Department")["Salary"].apply(lambda s: s.max() - s.min())
print(spread)

Groups with no usable salary need an explicit fallback, here the overall median. groupby().apply() can handle custom group logic, but prefer .agg() or .transform() for common reductions and row-aligned calculations. Group statistics used as predictive features must be learned from appropriate training or historical records only; computing them on the full dataset can leak information.

14. Combining datasets: merge, join and concat

A common situation is that one table contains the facts you need to analyze, while another contains descriptive information. The employee table contains a department code, but not the manager. Create a small lookup table.

Python
departments = pd.DataFrame({
    "Department": ["IT", "HR", "Sales"],
    "Manager": ["John", "Sarah", "Mike"]
})

merged = pd.merge(df, departments, on="Department", how="left")
print(merged[["Name", "Department", "Manager"]])
Name Department Manager
Alice IT John
Bob HR Sarah
Charlie IT John
David Sales Mike
Emma HR Sarah

on identifies the matching column, and how describes which keys to retain. The department table has one manager per department, so many employees can match the same manager. This is a many-to-one join.

All four common join types, side by side

Python
left = pd.DataFrame({"ID": [1, 2, 3], "Name": ["A", "B", "C"]})
right = pd.DataFrame({"ID": [2, 3, 4], "Score": [80, 90, 95]})

for how in ["inner", "left", "right", "outer"]:
    print(how)
    print(left.merge(right, on="ID", how=how).sort_values("ID"))
Key Left name Right score Inner Left Right Outer
1 A missing — ✓ — ✓
2 B 80 ✓ ✓ ✓ ✓
3 C 90 ✓ ✓ ✓ ✓
4 missing 95 — — ✓ ✓

Inner join keeps matches on both sides. Left join keeps all left records and any matching right data. Right join preserves the right records. Outer join keeps all keys from both sides. Unmatched fields become missing. A left join is a common choice when enriching a primary dataset without intentionally losing observations; it does not guarantee the same number of rows if right-hand keys repeat.

Different key names, overlapping columns and join validation

Python
lookup = departments.rename(columns={"Department": "DeptCode"})
joined = df.merge(lookup, left_on="Department", right_on="DeptCode",
                  how="left", validate="many_to_one", indicator=True)
print(joined["_merge"].value_counts())
print(joined[joined["_merge"] == "left_only"])
assert len(joined) == len(df)

old = pd.DataFrame({"ID": [1], "Salary": [5000]})
new = pd.DataFrame({"ID": [1], "Salary": [5500]})
print(old.merge(new, on="ID", suffixes=("_old", "_new")))

left_on and right_on allow different key names. suffixes distinguishes overlapping non-key columns. indicator=True adds _merge with values left_only, right_only or both, helping diagnose unmatched rows; it is more explicit than assuming every null in the joined table indicates a missing match. validate="many_to_one" rejects non-unique right keys. Other validation options include one_to_one, one_to_many, and many_to_many (the last does not impose uniqueness).

A join can multiply the row count when repeated keys occur on both sides. If two rows on the left match three on the right, that key produces six output rows. This is one of the most consequential mistakes in data preparation. Also, Pandas can match null join keys to each other, unlike typical SQL null-equality semantics. Explicitly handle missing keys if this is not desired.

A DataFrame's join() method is especially useful for matching by index. This example uses the Department column on the left and the index of the lookup table on the right.

Python
print(df.join(departments.set_index("Department"), on="Department"))

Concatenate: stack tables rather than match keys

Python
january = pd.DataFrame({"Month": ["Jan", "Jan"], "Sales": [10, 20]})
february = pd.DataFrame({"Month": ["Feb"], "Sales": [30]})
all_months = pd.concat([january, february], ignore_index=True)
print(all_months)

extra = pd.DataFrame({"Location": ["Baku", "Ganja"]})
print(pd.concat([january, extra], axis=1))

concat(axis=0) stacks rows, aligning columns by label. Different schemas produce missing values for columns absent from one input. concat(axis=1) places tables side by side and aligns their row indexes. If the datasets need to match by an ID, use a merge rather than assuming they have the same row order. The analogy is SQL UNION ALL for vertical concatenation (with column-name alignment in Pandas) and JOIN for key-based matching.

15. Pivot tables: change the shape to answer a different question

Grouping produces a summary, but sometimes a matrix is easier to compare. Suppose the data describes coffee sales by day and product.

Python
coffee = pd.DataFrame({
    "Day": ["Monday", "Monday", "Tuesday", "Tuesday", "Wednesday", "Wednesday"],
    "Type": ["Espresso", "Latte"] * 3,
    "Units": [25, 15, 35, 28, 40, 25]
})
coffee["Price"] = np.where(coffee["Type"] == "Espresso", 4.0, 6.0)
coffee["Revenue"] = coffee["Units"] * coffee["Price"]

wide = coffee.pivot(index="Day", columns="Type", values="Revenue")
print(wide)
Day Espresso Latte
Monday 100 90
Tuesday 140 168
Wednesday 160 150

A long table contains one record per day-product combination. The pivot places the product categories across columns so each day can be compared directly. pivot() requires that each index-column combination have at most one input value. If Monday contains multiple Espresso records, use pivot_table() with an explicit aggregation.

Python
more_coffee = pd.concat([coffee, coffee.iloc[[0]]], ignore_index=True)
report = more_coffee.pivot_table(index="Day", columns="Type", values="Revenue",
                                aggfunc="sum", fill_value=0)
print(report)
print(wide.sum(axis=0))  # Total revenue by type
print(wide.sum(axis=1))  # Total revenue by day

ordered_days = ["Monday", "Tuesday", "Wednesday"]
wide = wide.reindex(ordered_days)
print(wide.loc["Monday", "Latte"])  # 90

pivot_table() can aggregate repeated combinations (its default is mean, so explicitly choose the operation). A missing combination is not automatically zero: fill_value=0 is suitable only if the absence of records genuinely means zero activity. Use reindex() or an ordered categorical dtype for a meaningful day or month order rather than alphabetical sorting.

Reverse the shape with melt

This companion operation extends the transcript's reshape examples: if data arrives in a wide spreadsheet, you may need it back in long format.

Python
long = wide.reset_index().melt(id_vars="Day", var_name="Type", value_name="Revenue")
print(long)

melt() keeps identifier columns and converts other columns into variable-value pairs. pivot and melt are not always exact inverses, especially when an earlier pivot_table aggregated several original observations. Reshaping changes how information is organized, not necessarily the information itself.

16. Dates, timestamps and time-based features

Date strings do not provide reliable chronological operations until converted to datetime values. A string like 03/04/2025 is ambiguous without knowing the intended format.

Python
events = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie", "David"],
    "Date": ["2025-01-05", "2025-02-10", "2025-02-20", "invalid"]
})
events["Date"] = pd.to_datetime(events["Date"], format="%Y-%m-%d", errors="coerce")
events["Year"] = events["Date"].dt.year
events["Month"] = events["Date"].dt.month
events["Day"] = events["Date"].dt.day
events["Weekday"] = events["Date"].dt.day_name()
events["MonthDay"] = events["Date"].dt.strftime("%m-%d")
print(events)

pd.to_datetime() parses the values; errors="coerce" changes invalid dates to NaT. The .dt accessor is to datetimes what .str is to strings. Extracting year, month, day, weekday or hour creates features without manually slicing date strings. .dt.strftime() formats a datetime into text and should be used for labels or display rather than replacing a datetime column you still need for chronological calculations.

Directive Meaning
%Y Four-digit year
%m Numeric month
%d Day of month
%H Hour, 24-hour clock
%M Minute
%S Second

For example, format="%d/%m/%Y" interprets 03/04/2025 as April 3, while format="%m/%d/%Y" interprets it as March 4. Explicit formats reduce accidental ambiguity. Timezones matter when combining records from different systems; choose a consistent timezone before calculating differences.

Python
reference = pd.Timestamp("2025-03-01")
events["DaysSinceEvent"] = (reference - events["Date"]).dt.days
print(events[["Name", "DaysSinceEvent"]])
print(events.groupby(events["Date"].dt.year)["Name"].count())
print(events.dropna(subset=["Date"]).groupby(events["Date"].dt.to_period("M")).size())

Subtracting dates produces a timedelta, from which .dt.days extracts whole days. For age, dividing a difference in days by 365 gives only an approximation; age in completed years requires checking whether the birthday has occurred as of the reference date. If predicting outcomes at a historical date, use the historical reference date, not today's date.

Aggregate events over time

Python
daily = pd.DataFrame({
    "Date": pd.to_datetime(["2025-01-01", "2025-01-02", "2025-02-01"]),
    "Revenue": [100, 150, 200]
})
monthly = daily.groupby(daily["Date"].dt.to_period("M"))["Revenue"].sum()
print(monthly)  # January 250; February 200

Grouping by month number alone can combine January from different years. A monthly period preserves both year and month. For regularly spaced time-indexed data, resample() is a related operation that can construct time buckets. A missing date bucket must be interpreted according to the underlying process.

17. Sequential data: shift, rolling windows and cumulative calculations

A time series is not simply a table with a Date column. The order matters. Before applying lag or rolling operations, make sure the data is sorted and that unrelated entities do not mix.

Python
time_data = pd.DataFrame({
    "Date": pd.date_range("2025-01-01", periods=5),
    "Sales": [10, 20, 30, 40, 50]
}).sort_values("Date")

time_data["PreviousSales"] = time_data["Sales"].shift(1)
time_data["Change"] = time_data["Sales"] - time_data["PreviousSales"]
time_data["CumulativeSales"] = time_data["Sales"].cumsum()
time_data["Rolling3Sum"] = time_data["Sales"].rolling(3).sum()
time_data["Rolling3Mean"] = time_data["Sales"].rolling(3).mean()
print(time_data)
Date Sales PreviousSales Change CumulativeSales Rolling3Sum Rolling3Mean
Jan 1 10 — — 10 — —
Jan 2 20 10 10 30 — —
Jan 3 30 20 10 60 60 20
Jan 4 40 30 10 100 90 30
Jan 5 50 40 10 150 120 40

shift(1) moves values down one row to provide the previous observation. shift(-1) exposes the next observation and can be useful for defining a future target, but should not be used as an input feature when the future is unknown. cumsum() calculates a running total. rolling(3) creates a three-row sliding window and requires three non-missing observations by default; min_periods=1 permits shorter initial windows. A three-row window is three days only if there is exactly one ordered observation per day.

Avoid time leakage and mixing groups

If we predict today's sales before today's actual sales are known, today's sales cannot be part of its input feature. Shift before calculating a rolling statistic.

Python
time_data["Past3Mean"] = time_data["Sales"].shift(1).rolling(3).mean()
print(time_data[["Date", "Sales", "Past3Mean"]])

store_sales = pd.DataFrame({
    "Store": ["A", "B", "A", "B", "A", "B"],
    "Date": pd.to_datetime(["2025-01-01", "2025-01-01", "2025-01-02",
                            "2025-01-02", "2025-01-03", "2025-01-03"]),
    "Sales": [10, 100, 20, 200, 30, 300]
}).sort_values(["Store", "Date"])
store_sales["Lag1"] = store_sales.groupby("Store")["Sales"].shift(1)
store_sales["Past2Mean"] = store_sales.groupby("Store")["Sales"].transform(
    lambda s: s.shift(1).rolling(2).mean()
)
print(store_sales)

For Store A's third observation, the past-two mean is 15; for Store B's third, it is 150. The first observation of each store has no previous record, so its lag is missing. Group-aware operations prevent the last sale of one store from becoming the previous sale of a different store. In production, define exactly what is known at prediction time, handle duplicate timestamps, and use chronological evaluation rather than random splitting for forecasting.

18. Exploratory data analysis: look at distributions, not just averages

A table of summary statistics does not tell the whole story. Two groups can have the same mean but very different spreads, shapes or outliers. Histograms reveal the distribution of numeric observations, box plots summarize spread and potential extreme observations, and bar charts compare discrete categories.

The following optional visualization example requires Matplotlib (python -m pip install matplotlib). It uses a small, invented salary dataset; the plots are demonstrations, not evidence about a population.

Python
import matplotlib.pyplot as plt

pay = pd.Series([4000, 4200, 4600, 5000, 5100, 5500, 6000, 6500, 7000, 15000])
low, high = pay.quantile([0.05, 0.95])

ax = pay.plot.hist(bins=8, title="Illustrative salary distribution")
ax.axvline(low, linestyle="--", label="5th percentile")
ax.axvline(high, linestyle="--", label="95th percentile")
ax.set_xlabel("Salary")
ax.legend()
plt.show()
plt.close()

pay.plot.box(title="Illustrative salary box plot")
plt.show()
plt.close()

df["Department"].value_counts().plot.bar(title="Employees per department")
plt.ylabel("Number of employees")
plt.tight_layout()
plt.show()
plt.close()

A histogram groups continuous values into bins. A box plot typically shows the median, quartiles and whiskers, with points beyond the whiskers flagged according to a convention such as 1.5 times the interquartile range. Those points are not automatically errors. A genuine high salary and a misplaced decimal point can both appear unusual statistically, but require different actions.

Python
q1, q3 = pay.quantile([0.25, 0.75])
iqr = q3 - q1
outlier_candidates = pay[(pay < q1 - 1.5 * iqr) | (pay > q3 + 1.5 * iqr)]
print(outlier_candidates)

For categorical distributions, value_counts() followed by .plot.bar() is often sufficient. Missing-value counts can similarly be plotted with .isna().sum().plot.bar(). A logarithmic frequency axis can help visualize rare bins in a large, skewed dataset, but remember that logarithmic axes cannot represent zero directly. Use visualizations to diagnose the data, then use explicit domain rules to determine what to change.

19. Practice project: words, scores and percentile filters

The first source tutorial explores word scores and Pokémon statistics. Rather than requiring their original files, we can reproduce their important techniques using two small tables. The first asks whether a long word is necessarily more valuable per character.

Python
words = pd.DataFrame({
    "Word": ["cat", "quiz", "tree", "jazz", "apple"],
    "Value": [5, 22, 4, 29, 9]
})
words["Characters"] = words["Word"].str.len()
words["Ratio"] = words["Value"] / words["Characters"]
print(words.sort_values("Ratio", ascending=False))
print(words.loc[words["Ratio"] == words["Ratio"].max(), ["Word", "Ratio"]])
print(words.query("Characters >= 4 and Value > 10"))

The values are illustrative, not a validated dictionary of Scrabble scores. The ratio represents score per character. In a dataset that permits empty words, first check for zero-length strings before division. Notice how filtering on equality with .max() returns every tied winner; .head(1) after sorting returns only the first. Continuous ratios are usually better explored using describe(), percentiles or a histogram than with a frequency table of every distinct floating-point value.

Now consider an invented creature-statistics dataset. It illustrates filtering combinations, sorting by more than one property and selecting values in the middle of a distribution.

Python
creatures = pd.DataFrame({
    "Name": ["A", "B", "C", "D", "E", "F"],
    "Type": ["Fire", "Water", "Fire", "Grass", "Water", "Fire"],
    "Speed": [20, 50, 70, 80, 100, 160],
    "Power": [40, 55, 90, 60, 95, 120],
    "Legendary": [False, False, False, False, False, True]
})
lo, hi = creatures["Speed"].quantile([0.05, 0.95])
central = creatures[creatures["Speed"].between(lo, hi)]
chosen = central[central["Type"].isin(["Fire", "Water"]) & ~central["Legendary"]]
print(chosen.sort_values(["Power", "Speed"], ascending=[False, True]))
print(creatures["Legendary"].sum())  # 1

The important part is not the identity of the creatures. It is the pattern: compute useful thresholds, construct a mask, select a subset and order the result to answer a specific question. On a tiny dataset, removing both tails can discard a substantial fraction of rows. On a real dataset, decide whether the purpose is to investigate a central subset or to clean actual invalid records; these are different tasks.

20. Practice project: birthday pairs, combinations and fuzzy matching

These two intermediate projects from the source material demonstrate a useful idea: sometimes the information you need does not appear in one existing row. You must construct relationships between rows before analyzing them.

The birthday-pair problem

If a group has people, the number of unordered pairs is:

For five people, there are ten pairs. For 100 people, there are 4950. A pair is a comparison between two distinct people; comparing Alice to Bob and then Bob to Alice would count the same pair twice.

Under the simplified birthday-paradox model (365 equally likely independent birthdays, no leap days), the probability of at least one shared birthday among people, for , is:

For 23 people this probability is approximately 50.7%. This is the chance of at least one match somewhere in the group, not the chance of someone matching one specified person's birthday. The observed fraction of matching pairs in a real dataset is a different quantity from this model probability.

Python
from itertools import combinations
from math import comb, prod

people = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie", "David", "Emma"],
    "Birthday": pd.to_datetime(["1990-03-05", "1991-09-10", "1994-03-05",
                                "1997-01-20", "2000-09-10"])
})
people["MonthDay"] = people["Birthday"].dt.strftime("%m-%d")
pair_rows = []
for a, b in combinations(people.itertuples(index=False), 2):
    pair_rows.append({"PersonA": a.Name, "PersonB": b.Name,
                      "SameBirthday": a.MonthDay == b.MonthDay})
pairs = pd.DataFrame(pair_rows)
print(pairs[pairs["SameBirthday"]])
print(len(pairs), pairs["SameBirthday"].sum())  # 10 pairs, 2 matching
print(comb(5, 2))  # 10
print(1 - prod((365 - k) / 365 for k in range(23)))

Two pairs match: Alice/Charlie and Bob/Emma. If you only need the number of matching pairs, rather than the identities of the people, count the birthdays first and sum the combinations inside each birthday group.

Python
counts = people["MonthDay"].value_counts()
match_count = (counts * (counts - 1) // 2).sum()
assert match_count == pairs["SameBirthday"].sum()
print(match_count)

The second method avoids materializing every pair. This matters because all-pair comparisons grow quadratically. For the original team-based exercise, repeat the calculation within each team rather than comparing players from different teams. With real data, also exclude unknown birthdays and ensure people are not duplicated before generating pairs.

Cartesian products: compare everything to everything

itertools.combinations() selects unordered pairs within one collection. itertools.product() constructs every combination between different collections. Pandas can produce the same cross product with merge(how="cross").

Python
from itertools import product

print(list(product(["A", "B"], [1, 2, 3])))
first = pd.DataFrame({"LeftName": ["Acme Corporation", "Blue River LLC"]})
second = pd.DataFrame({"RightName": ["ACME Corp", "Blue River", "Green Tree"]})
candidates = first.merge(second, how="cross")
assert len(candidates) == 2 * 3
print(candidates)

There are six pairs. In a fuzzy-joining problem, these are candidate matches, not actual matches. With 10,000 rows in each table, a full cross join produces 100 million pairs. Reduce candidates using known keys, geographic regions, normalized prefixes or other defensible blocking rules before expensive comparisons.

Fuzzy string matching: similar is not necessarily identical

An exact merge fails if two tables use inconsistent names such as Acme Corporation and ACME Corp. Levenshtein distance counts the minimum number of insertions, deletions and substitutions necessary to transform one string into another. A distance of zero means identical strings under the chosen normalization. Similarity functions instead often produce a score where higher is more similar. Their precise formula depends on the algorithm.

The original transcript uses fuzz.ratio() and fuzz.partial_ratio(). The following optional example uses the compatible RapidFuzz library. Install it with python -m pip install rapidfuzz.

Python
from rapidfuzz import fuzz
from rapidfuzz.distance import Levenshtein

print(Levenshtein.distance("cat", "cut"))  # 1 substitution
candidates["Score"] = candidates.apply(
    lambda row: fuzz.ratio(row["LeftName"].casefold(), row["RightName"].casefold()),
    axis=1
)
candidates["PartialScore"] = candidates.apply(
    lambda row: fuzz.partial_ratio(row["LeftName"].casefold(), row["RightName"].casefold()),
    axis=1
)
possible = candidates[candidates["PartialScore"] >= 80]
print(possible.sort_values("PartialScore", ascending=False))

A partial ratio can score highly when one string is contained in another. That is useful for abbreviations and added suffixes but can create false positives if unrelated organizations share a generic word. A score of 90 is not a 90% probability of a true match. Choose thresholds using labeled examples if possible, inspect ambiguous candidates, and consider exact identifiers or additional attributes. The correct match may not exist in the second table. Do not force every left row to match a right row merely because a best candidate exists.

21. Practice project: clean an app-store dataset end to end

The Google Play Store exercise from the first transcript combines several essential skills: inspecting columns, handling invalid ratings, converting review counts and install counts, cleaning price and size strings, investigating duplicates and saving a clean dataset. This self-contained adaptation recreates the reasoning with invented records.

Step 1: construct the raw dataset

Python
apps_raw = pd.DataFrame({
    "App": ["Notes", "Notes", "Maps", "Calendar", "Timer", "Weather"],
    "Category": [" Productivity ", "productivity", "TRAVEL", "productivity", "Tools", "Tools"],
    "Rating": ["4.2", "4.4", "6.0", None, "4.0", "3.8"],
    "Reviews": ["100", "150", "2,000", "bad", "25", "40"],
    "Installs": ["1,000+", "5,000+", "10,000+", "100+", "50+", "500+"],
    "Size": ["12M", "12M", "850k", "Varies with device", "2.5M", "600k"],
    "Price": ["$0", "$0", "$2.99", "$0", "$1.99", "$0"]
})
apps_raw.info()
print(apps_raw.isna().sum())
print(apps_raw.head())

The numeric columns are strings. One rating is outside the expected range, another is missing, one review count is not numeric, and one size is not a fixed measurement. Notes appears twice. The plus sign in the install count indicates a lower-bound bucket, not an exact count.

Step 2: normalize and validate

Python
apps = apps_raw.copy()
apps["Category"] = apps["Category"].str.strip().str.lower()
apps["Rating"] = pd.to_numeric(apps["Rating"], errors="coerce")
apps.loc[~apps["Rating"].between(0, 5) & apps["Rating"].notna(), "Rating"] = np.nan
apps["Reviews"] = pd.to_numeric(apps["Reviews"].str.replace(",", "", regex=False),
                                errors="coerce").astype("Int64")
apps["InstallsLowerBound"] = pd.to_numeric(
    apps["Installs"].str.replace(r"[,+]", "", regex=True), errors="coerce"
).astype("Int64")
apps["PriceUSD"] = pd.to_numeric(apps["Price"].str.replace("$", "", regex=False),
                                 errors="coerce")
apps["Paid"] = apps["PriceUSD"].gt(0)
print(apps.isna().sum())

The script deliberately uses InstallsLowerBound as the new column name. Converting "10,000+" to 10000 is parsing a lower bound, not recovering the exact number of installations. All prices in this synthetic dataset are USD; real multi-currency data needs a currency column and an explicit conversion policy.

Step 3: convert size units consistently

Python
size_parts = apps["Size"].str.extract(r"^\s*(\d+(?:\.\d+)?)\s*([kKmM])\s*$")
size_value = pd.to_numeric(size_parts[0], errors="coerce")
unit_factor = size_parts[1].str.lower().map({"k": 1 / 1000, "m": 1})
apps["SizeMB"] = size_value * unit_factor
print(apps[["App", "Size", "SizeMB"]])

For this example, 1000 kB is defined as 1 MB; if the original dataset uses binary units, the conversion factor would differ. Varies with device does not represent a known size and stays missing. We keep the original Size column for traceability. str.extract() returns the regex capture groups, so the two columns represent the number and the unit respectively.

Step 4: deduplicate according to an explicit rule

Python
print(apps[apps.duplicated(subset=["App"], keep=False)])
apps = (apps.sort_values("Reviews", ascending=False, na_position="last", kind="stable")
            .drop_duplicates(subset=["App"], keep="first")
            .reset_index(drop=True))
print(apps[["App", "Rating", "Reviews", "InstallsLowerBound", "PriceUSD", "SizeMB"]])

The Notes record with 150 reviews is retained. In real app-store data, an app's title may not be unique; prefer its package identifier if available. Retain an audit record of what was removed and why.

Step 5: report and validate, then export

Python
assert apps["App"].is_unique
assert apps["Rating"].dropna().between(0, 5).all()
assert apps["PriceUSD"].dropna().ge(0).all()
assert apps["Reviews"].dropna().ge(0).all()
assert len(apps) == 5

print(apps.groupby("Category", as_index=False).agg(
    Apps=("App", "size"),
    AverageRating=("Rating", "mean"),
    KnownRatings=("Rating", "count")
))
print(apps.isna().sum())

with TemporaryDirectory() as folder:
    apps.to_csv(Path(folder) / "apps_clean.csv", index=False)
    reloaded = pd.read_csv(Path(folder) / "apps_clean.csv")
    assert len(reloaded) == len(apps)
App Rating Reviews Install lower bound Price USD Size MB
Maps missing 2000 10000 2.99 0.85
Notes 4.4 150 5000 0 12
Weather 3.8 40 500 0 0.6
Timer 4.0 25 50 1.99 2.5
Calendar missing missing 100 0 missing

The five-row result retains unknown measurements rather than inventing values. If the intended analysis needs every rating, choose an appropriate missing-data strategy and describe it. If the target is rating prediction, an unknown rating is not a valid supervised training label. That distinction is why data cleaning should be driven by the actual problem, not a universal checklist that replaces every null.

22. Practice project: sports analysis using groups, joins and transforms

The Premier League and NBA projects in the first tutorial show how basic operations combine into a more complex analysis. The key skills are checking logical consistency, translating codes, grouping data, combining different levels of granularity, and selecting top performers within groups. The examples below use invented teams and players; no actual season results are claimed.

Football: validate match results before counting wins

Python
matches = pd.DataFrame({
    "Season": ["2025", "2025", "2025", "?"],
    "Home": ["A", "B", "A", "C"],
    "Away": ["B", "C", "C", "A"],
    "HomeGoals": [2, 0, 1, 3],
    "AwayGoals": [1, 0, 2, 1],
    "RecordedResult": ["H", "D", "H", "?"]
})
matches["Season"] = matches["Season"].replace({"?": "Unknown"})
matches["ComputedResult"] = np.select(
    [matches["HomeGoals"] > matches["AwayGoals"],
     matches["HomeGoals"] < matches["AwayGoals"]],
    ["H", "A"], default="D"
)
conflicts = matches[matches["RecordedResult"] != matches["ComputedResult"]]
print(conflicts)
print((matches["ComputedResult"] == "H").sum())
matches["GoalDifference"] = matches["HomeGoals"] - matches["AwayGoals"]
matches["GoalMargin"] = matches["GoalDifference"].abs()

The third row's recorded home win conflicts with its score, and the fourth row lacks a recorded result. In this teaching example the goals are known and valid, so we use the computed result for further analysis. In real data, the source of truth may instead be the recorded result, or both fields may require verification. Do not automatically assume one field is more reliable.

Python
home_summary = matches.groupby("Home", as_index=False).agg(
    HomeGames=("Away", "size"),
    GoalsScored=("HomeGoals", "sum"),
    GoalsConceded=("AwayGoals", "sum")
)
home_summary["ConcededPerHomeGame"] = (
    home_summary["GoalsConceded"] / home_summary["HomeGames"]
)
print(home_summary.sort_values("ConcededPerHomeGame"))

A ratio must use the correct denominator: goals conceded per home game means total goals conceded as the home team divided by its number of home matches. Comparing teams by total conceded goals alone would be misleading if they played different numbers of games.

To compute total points, transform home and away information into the same shape before concatenating.

Python
home = matches[["Home", "ComputedResult", "HomeGoals", "AwayGoals"]].rename(
    columns={"Home": "Team", "HomeGoals": "GF", "AwayGoals": "GA"}
)
away = matches[["Away", "ComputedResult", "AwayGoals", "HomeGoals"]].rename(
    columns={"Away": "Team", "AwayGoals": "GF", "HomeGoals": "GA"}
)
home["Points"] = home["ComputedResult"].map({"H": 3, "D": 1, "A": 0})
away["Points"] = away["ComputedResult"].map({"A": 3, "D": 1, "H": 0})
team_games = pd.concat([home, away], ignore_index=True)
standings = team_games.groupby("Team", as_index=False).agg(
    Games=("Points", "size"), Points=("Points", "sum"),
    GoalsFor=("GF", "sum"), GoalsAgainst=("GA", "sum")
)
standings["GoalDifference"] = standings["GoalsFor"] - standings["GoalsAgainst"]
print(standings.sort_values(["Points", "GoalDifference"], ascending=False))

Each match produces two team-game records, one for each participant. This is intentional reshaping: a match table and a team-game table have different meanings for one row.

Basketball: enrich player statistics without losing players

Python
player_stats = pd.DataFrame({
    "PlayerID": [1, 2, 3, 4, 5],
    "Team": ["AA", "AA", "BB", "BB", "CC"],
    "Points": [300, 280, 450, 450, 200],
    "Games": [20, 14, 25, 30, 20],
    "ThreeMade": [30, 35, 60, 50, 0],
    "ThreeAttempts": [100, 90, 150, 125, 0]
})
player_bios = pd.DataFrame({
    "ID": [1, 2, 3, 4],
    "Player": ["Alex", "Sam", "Jordan", "Taylor"],
    "BirthDate": ["1995-01-01", "1998-06-03", "1994-12-31", "1999-05-15"]
})
players = player_stats.merge(player_bios, left_on="PlayerID", right_on="ID",
                             how="left", validate="one_to_one", indicator=True)
print(players[players["_merge"] == "left_only"])
players["TeamName"] = players["Team"].replace({"AA": "Arrows", "BB": "Bears", "CC": "Comets"})
players["BirthDate"] = pd.to_datetime(players["BirthDate"], errors="coerce")
players["AgeDays"] = (pd.Timestamp("2025-06-30") - players["BirthDate"]).dt.days
players["PointsPerGame"] = players["Points"] / players["Games"].replace(0, np.nan)
players["ThreeAccuracy"] = players["ThreeMade"] / players["ThreeAttempts"].replace(0, np.nan)
players["TeamMaxPoints"] = players.groupby("Team")["Points"].transform("max")
leaders = players[players["Points"] == players["TeamMaxPoints"]]
print(leaders[["PlayerID", "Player", "TeamName", "Points", "PointsPerGame"]])

A left join keeps PlayerID 5 even though the bio table lacks that player. The missing match is identified by _merge. The total-points leaders are Alex for AA, both Jordan and Taylor for BB, and PlayerID 5 for CC. Sam scores 20 points per game while Alex scores 15, illustrating that a leader by total points is not necessarily a leader by average points.

Three-point accuracy is defined as made shots divided by attempts. Zero attempts make the ratio undefined, not zero; the example explicitly converts a zero denominator to missing. It may be sensible to require a minimum number of attempts before ranking accuracy. Again, define the metric first and use Pandas to implement it.

23. From a clean table to machine learning: a complete preparation workflow

Pandas is often the last data-manipulation layer before a model receives its features. This section is an engineering extension of the tutorials, connecting their cleaning and transformation methods to supervised ML. The basic idea is to separate deterministic cleaning from transformations that learn statistics about the data.

Imagine we want to predict a customer's monthly spending from age, number of visits and membership tier. The target is MonthlySpend. The following invented dataset deliberately contains missing features, numeric strings, one duplicate and one missing target. It is too small to establish model quality; it exists to demonstrate mechanics.

Python
customers_raw = pd.DataFrame({
    "CustomerID": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2],
    "Age": ["25", "30", "unknown", "40", "28", "35", "50", "22", "45", "31", "30"],
    "Visits": [3, 5, 2, 8, np.nan, 7, 10, 1, 6, 4, 5],
    "Tier": [" Basic ", "Premium", "basic", "premium", "basic", None,
             "premium", "basic", "premium", "basic", "Premium"],
    "MonthlySpend": [90, 160, 70, 240, 100, 200, 300, 45, 180, np.nan, 160]
})

customers = customers_raw.copy().drop_duplicates()
customers["Age"] = pd.to_numeric(customers["Age"], errors="coerce")
customers.loc[~customers["Age"].between(18, 100) & customers["Age"].notna(), "Age"] = np.nan
customers["Tier"] = customers["Tier"].astype("string").str.strip().str.lower()
customers["Tier"] = customers["Tier"].fillna("unknown")
customers = customers.dropna(subset=["MonthlySpend"]).reset_index(drop=True)
assert customers["CustomerID"].is_unique
assert customers["MonthlySpend"].notna().all()

X = customers[["Age", "Visits", "Tier"]]
y = customers["MonthlySpend"]
print(X.shape, y.shape)  # (9, 3), (9,)

The Age bounds are illustrative schema rules for this example, not general rules for all customer datasets. CustomerID is retained for validation but not used as a predictor. X is a two-dimensional DataFrame of input features; y is a one-dimensional Series containing labels. Rows of X and y must refer to the same observations. Do not independently sort them. The duplicate here is an exact repeat, which we remove before splitting. A real longitudinal dataset may legitimately contain several records per customer, and those would require a different split policy.

What is data leakage?

Data leakage happens when training or preprocessing uses information that would not have been available when making a genuine prediction. If the median age is computed over the full dataset and then used to fill missing values before splitting, the training process has indirectly used test-set information. Group means, category vocabularies, scalers, outlier cutoffs and target-derived features can introduce similar problems. Deterministic rules known in advance—such as parsing numeric strings and normalizing case—do not generally learn from held-out data.

The following optional example requires scikit-learn (python -m pip install scikit-learn). The pipeline is the safest way to combine a Pandas feature table with preprocessing and a model.

Python
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42
)

numeric_features = ["Age", "Visits"]
categorical_features = ["Tier"]

numeric_pipeline = Pipeline([
    ("imputer", SimpleImputer(strategy="median")),
    ("scaler", StandardScaler())
])
preprocessor = ColumnTransformer([
    ("numeric", numeric_pipeline, numeric_features),
    ("category", OneHotEncoder(handle_unknown="ignore"), categorical_features)
])
model = Pipeline([
    ("preprocessor", preprocessor),
    ("regressor", LinearRegression())
])
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Teaching example MAE:", mean_absolute_error(y_test, predictions))

The pipeline fits imputation medians, scaling parameters and category vocabulary using X_train only. predict(X_test) reuses the fitted transformations rather than fitting them again. Scaling is included to demonstrate the pipeline pattern; it is not inherently necessary for ordinary least squares regression. handle_unknown="ignore" allows an unseen membership tier at inference time without a category-encoding exception. The error printed by this tiny synthetic example is not evidence of generalization.

In a notebook you can also explore pd.get_dummies(X, columns=["Tier"], dtype=int) to understand one-hot encoding; for real training and inference, prefer a fitted encoder that guarantees consistent output features. If exporting a dataset for another tool, record the expected schema, feature order, units and missing-value conventions. X.to_numpy() converts a DataFrame to a NumPy array when required, but can lose labels and may produce an object array if types are mixed; preprocess before handing numeric data to a tensor library.

For time-dependent tasks, a random train/test split is usually inappropriate. Sort by time, choose a historical training window and future evaluation window, and compute lagged features without using future observations. For repeated entities, decide whether a group-based split is needed to prevent near-identical records from leaking across sets.

24. Performance, memory and modern Pandas: what matters in practice

Do not optimize code that has not been measured. Most beginner-to-intermediate tasks benefit far more from correct filtering, clear transformations and valid joins than from aggressive micro-optimization. Once performance matters, inspect the size of the data and how much memory columns consume.

Python
print(df.memory_usage(deep=True))
print(df.memory_usage(deep=True).sum())
print(df.select_dtypes(include="number"))

compact = df.copy()
compact["Department"] = compact["Department"].astype("category")
compact["Age"] = pd.to_numeric(compact["Age"], downcast="integer")
print(compact.dtypes)

A NumPy int64 value uses 64 bits, or 8 bytes, for its raw storage—not 64 bytes. Overall DataFrame memory includes additional structures and, for some dtypes, separate Python objects. Downcasting is only appropriate when the smaller dtype can represent the full required range. For floating-point values, lower precision can change numerical results. Category storage is often useful for repeated labels but may not help columns containing nearly all distinct values.

The fourth transcript also discusses Apache Arrow-backed columns introduced into Pandas 2.x. They can be beneficial for string-heavy data and interoperability with other data tools. They are a storage and execution option, not a new DataFrame API that must be mastered before ordinary Pandas.

The following optional, version-dependent file pattern requires Pandas 2.0 or newer, PyArrow and an actual CSV file. It is not part of the core exercise execution.

Python
# Requires pyarrow and a real file.
# arrow_df = pd.read_csv("large_dataset.csv", dtype_backend="pyarrow")
# arrow_df.info()
# print(arrow_df.memory_usage(deep=True).sum())

If you use Arrow-backed columns, check whether downstream libraries support the resulting dtypes. Different Pandas versions also differ in string inference, nullable types and copy-on-write behavior. Prefer explicit type conversions and non-chained assignments rather than relying on version-specific quirks.

Useful practical habits include loading only the columns you need, using appropriate types, collecting rows in batches before concatenation, using vectorized operations, choosing efficient file formats and avoiding unnecessary cross joins. For a very large CSV, pd.read_csv(..., chunksize=...) yields manageable batches; however, some operations such as global deduplication and exact percentiles require coordination across chunks. A larger-than-memory workload may justify a different engine rather than forcing Pandas to handle everything in memory.

Use AI coding assistants deliberately

The fourth transcript shows GitHub Copilot and ChatGPT generating filters, toy datasets and plots. A useful prompt includes the column names, intended condition, expected result and any missing-value rules. For example: “Create a Pandas Boolean mask for customers whose membership is Premium or whose visits exceed 10. Keep unknown membership as false for the membership condition.” Ask for a small test dataset with edge cases, then verify the generated expression against those cases.

Never paste private customer data merely to obtain a filter; share a synthetic schema instead. AI assistance can speed up exploration, but you should still understand whether the code returns a Series or DataFrame, mutates data, changes row count or uses future information. Those are the details that determine whether the code is correct.

25. A practical SQL-to-Pandas reference

If you already know SQL, many Pandas operations will feel familiar. The comparison is conceptual; Pandas handles indexes, nulls and alignment differently from a relational database.

SQL idea Pandas equivalent
SELECT Name, Salary FROM employees df[["Name", "Salary"]]
SELECT * FROM employees WHERE Age > 30 df[df["Age"] > 30]
WHERE Department IN (...) df[df["Department"].isin([...])]
ORDER BY Salary DESC df.sort_values("Salary", ascending=False)
LIMIT 5 df.head(5)
SELECT DISTINCT Department df["Department"].unique()
COUNT(*) len(df)
COUNT(Salary) df["Salary"].count()
COUNT(DISTINCT Department) df["Department"].nunique()
GROUP BY Department with AVG(Salary) df.groupby("Department")["Salary"].mean()
HAVING COUNT(*) > 1 Group using .size(), then filter the result
LEFT JOIN pd.merge(left, right, on="ID", how="left")
UNION ALL pd.concat([a, b], ignore_index=True)
CASE WHEN ... THEN ... ELSE ... END np.where(condition, yes, no)
UPDATE ... WHERE ... df.loc[condition, "Column"] = value
DELETE ... WHERE ... df = df.loc[~condition].copy()
AVG(...) OVER (PARTITION BY Department) df.groupby("Department")["Salary"].transform("mean")

A compact example of a SQL-like analysis in Pandas might be:

Python
result = (
    df.loc[df["Age"] >= 28]
      .groupby("Department", as_index=False)
      .agg(EmployeeCount=("EmployeeID", "size"), MeanSalary=("Salary", "mean"))
      .query("EmployeeCount >= 2")
      .sort_values("MeanSalary", ascending=False)
)
print(result)

This filters employees first, then groups the remaining rows, filters groups with at least two employees, and sorts the summary. The result is HR with two employees and a mean salary of 8000. The order of operations matters: filtering before grouping changes which rows contribute to a statistic. Method chaining is convenient when each step has a clear purpose; avoid extremely long chains if intermediate results need to be inspected.

26. Practice checklist: prove you can use Pandas independently

Reading code is not the same as being able to write it. Try the following short tasks without copying the earlier examples. They deliberately progress from familiar operations to small engineering decisions. All table names refer to datasets already defined in this guide. The hints are pointers, not complete solutions.

# Challenge Hint
1 Construct a three-row DataFrame containing product, price and stock. Dictionary of lists
2 Create a Series containing three named student scores and update one score. Series, .loc
3 Save a copy of the employee dataset and reload only Name and Salary. to_csv, read_csv, usecols
4 Show the shape, data types and a random sample of two employees. Attributes, sample
5 Select Name and Department without selecting Age. List of columns
6 Select the second and fourth rows by position. .iloc
7 Set EmployeeID as the index and retrieve employee 104. set_index, .loc
8 Find employees older than 30 who earn at least 6000. Combine masks
9 Return employees outside IT and HR. ~, isin
10 Find all names ending with the letter e, ignoring case. .str.lower, .str.endswith
11 Sort salaries descending within departments. Multiple sort keys
12 Find the median salary and 90th percentile. median, quantile
13 Rank employees by salary, with highest first. rank
14 Add an annual salary feature and a monthly bonus of 5% of salary. Vectorized arithmetic
15 Give Sales employees a 10% raise without changing the original table. .copy, .loc
16 Append a new employee and reset the resulting row labels. concat
17 Remove the Salary column from a copy and rename Age to Years. drop, rename
18 Count missing values by column in missing. isna().sum()
19 Fill missing salaries using the median; keep the original unchanged. fillna, .copy
20 Keep only rows with a known Department and known Salary. dropna(subset=...)
21 Convert strings such as "$2,500" and "unknown" into numeric values. String cleanup, to_numeric
22 Inspect all duplicate app names before removing any. duplicated(keep=False)
23 Keep the highest-review row for each app in repeated. Sort, then deduplicate
24 Create a feature called Senior for ages of at least 35. Boolean comparison
25 Create Low, Medium and High salary categories. np.select or custom function
26 Count employees per department and sum their salaries. Named aggregation
27 Add each department's median salary to every employee row. transform
28 Attach the manager from the lookup table, retaining all employees. Left join
29 Identify unmatched keys after an outer join of left and right. indicator=True
30 Validate that a lookup table has a unique key before merging. validate
31 Stack January and February sales. Then calculate total sales by month. concat, groupby
32 Pivot coffee units by Day and Type. pivot
33 Convert the wide coffee table back to long format. melt
34 Extract year, month and weekday from events. .dt
35 Compute a previous-sale feature and a mean of the previous two sales. shift, rolling
36 Find matching birthday pairs without constructing every pair. Frequency counts, combinations formula
37 Plot the salaries and investigate possible extreme values. Histogram, box plot, quantile
38 Identify all tied points leaders within each basketball team. transform("max")
39 Clean the app data, report unknown values, and export it. Combine the main cleaning operations
40 Separate the customer features and target; explain where median imputation must be fitted. X, y, train-only preprocessing

Selected checkpoints for self-verification

Use these expected outcomes to catch mistakes without immediately looking up every solution. For the original employee table, employee 104 is David, the highest salary belongs to Emma, and IT and HR have two employees each. Challenge 8 returns Charlie and Emma. Challenge 9 returns David. Challenge 26 produces three group rows and total salary 31,500 across the groups. For challenge 29, key 1 is left-only and key 4 is right-only. The birthday dataset has two matching pairs. The app-cleaning project retains five apps; the cleaned customer dataset contains nine labeled observations and three input features. If your code gives a different result, inspect the mask, index alignment, join cardinality, or sequence of transformations.

27. Which Pandas skills should you actually memorize?

The goal is broad practical competence, not memorization of every method. It is reasonable to memorize the common syntax, understand less frequent operations, and look up specialized arguments when needed.

Priority Skills
Essential DataFrame/Series, reading files, inspection, column and row selection, Boolean masks, sorting, missing values, duplicates, dtype conversion, string operations, column arithmetic, groupby, merges and concat
Important query, map, apply, agg, transform, join validation, datetime features, pivot tables, exports, visualization, leakage-aware preparation
Context dependent shift, rolling, interpolation, ranking, cross joins, combinations, fuzzy matching, regex, Parquet and Arrow storage
Reference as needed Scalar indexers, advanced memory tuning, exotic reshapes, specialized file formats and version-specific APIs

If you can load an unfamiliar dataset, understand its schema, create a clean working copy, diagnose incorrect values, filter and join it safely, build useful summaries and features, and export or hand it to an ML pipeline, you already have a substantial portion of the Pandas skills used in everyday ML engineering. There is no objectively measured universal “85%” threshold: proficiency depends on the kind of work and on your ability to solve unfamiliar problems, not the number of functions you can name.

Closing thought

The important transition is from seeing Pandas as a list of functions to recognizing recurring problems. A filter selects observations. A groupby reduces or transforms related observations. A merge connects tables using keys. Cleaning preserves the distinction between known, missing and invalid values. Feature engineering expresses relevant information in a new form, while validation makes sure you have not introduced a silent error.

The same ideas work whether the dataset contains employees, coffee sales, app-store statistics, athlete biographies or customer behavior. Learn the small operations first, combine them into realistic tasks, and keep checking what each row represents at every stage. Then use Pandas as the tool it is: a reliable bridge between imperfect real-world data and useful analysis or machine-learning systems.


Editorial note and source coverage: This draft consolidates the four user-provided video transcripts and earlier Pandas exercises. Transcript 1 (Pandas by Example, freeCodeCamp/DataWars, eight chapters) supplies the word-score and creature-statistics examples, birthday combinations, fuzzy matching, app-store cleaning, and football/basketball analysis. Transcript 2 (approximately one hour) supplies Series, DataFrame creation, CSV/JSON, indexing, aggregation, and basic cleaning. Transcript 3 (approximately 30 minutes) supplies notebook workflows, exploration, filtering, conditional updates, deletion, renaming and export. Transcript 4 (Keith Galli, approximately 94 minutes) supplies sampling, scalar indexing, regex, vectorized features, datetime extraction, joins, missing values, pivots, rolling operations, Arrow and AI-assistance examples. These are reorganized by concept rather than video order. The source projects are adapted to synthetic data because the original datasets were not supplied. Additional companion material includes explicit index alignment, merge validation, nullable types, melt, practical SQL analogies, leakage-safe ML preprocessing and practice questions. Corrections to the transcripts include the meaning of int64, inclusive label slicing versus exclusive positional slicing, environment setup, null semantics, and the distinction between a fuzzy score and a match probability. No external benchmark or dataset result is asserted. Optional dependencies and file-dependent examples are marked.*

← Back to all blogs

ML Engineering · AI Engineering

SQL, Explained from First Principles: From Queries and Database Design to Advanced Analytics, Performance, and Data Engineering

Learn to think in tables, write correct queries, transform messy data, build relational databases, and understand why some SQL queries are faster than others.

SQL is a declarative language: describe the information you want, and the database engine determines how to retrieve it. The real skill is not memorizing keywords. It is knowing what a row represents, how tables relate, how expressions transform data, and how to prove that the resulting query answers the intended question.

This guide uses a consistent fictional retail business. The exercises gradually progress from retrieving a customer to building analytical datasets, diagnosing bad joins, and designing a data pipeline. Every example using the practice dataset is small enough to inspect manually. SQL examples with an Output (SQLite practice data) table have been executed against the supplied setup; other dialect-specific examples have explicitly illustrative expected behavior. Examples that change data use disposable tables, transactions, or a fresh database. Numerical examples are synthetic, not measured production benchmarks.

Dialect convention. Most core queries use portable SQL and are runnable in SQLite 3.46 (or a recent SQLite release). SQL Server (T-SQL), PostgreSQL and MySQL alternatives are labeled. A client such as SQL Server Management Studio (SSMS), MySQL Workbench, pgAdmin, or VS Code with a database extension is a tool for communicating with the database, not the engine itself. Use a local practice environment, not a production database. This guide is about SQL, not the complete administration of any one database system.

Road map

Part What you will learn
I SQL foundations, data types, queries, filters, sorting
II Database engineering, tables, keys, modifications, transactions, ER design
III Aggregation, joins, set operators, subqueries, CTEs
IV Text, numeric, date, NULL, type conversion and cleaning
V Window functions, ranking, time-series analysis and intermediate datasets
VI Procedures, triggers, indexes, plans and partitioning
VII ETL, warehousing and practical projects

The practice database

A customer can place many orders; each order can contain multiple products. Employees belong to departments and may have a manager. We deliberately include a customer with no orders, an order without a customer, missing emails, a product with no sales, tied employee salaries and an empty department to expose important edge cases.

Text
customers (1) ───< orders (N) ───< order_items (N) >─── (1) products
                         PK order_id     PK (order_id, product_id)
departments (1) ───< employees (N)
                     employee.manager_id ──> employee.employee_id

Run the following once in a new SQLite database (for example using the sqlite3 shell or a SQLite client). The PRAGMA command enables foreign-key enforcement in that connection. SQLite accepts the declared types here but has its own dynamic typing/affinity rules; explicit NOT NULL is used on the key columns because an ordinary SQLite INT PRIMARY KEY or composite key can otherwise permit NULL; production MySQL, PostgreSQL and SQL Server enforce types differently. The IDs are assigned explicitly to keep the examples deterministic. Prices represent fictional monetary units; order amount and line totals match in this dataset. In real schemas, taxes, shipping, discounts and rounding may make them differ.

SQL
PRAGMA foreign_keys = ON;
CREATE TABLE departments (department_id INT NOT NULL PRIMARY KEY, department_name VARCHAR(30) NOT NULL UNIQUE);
CREATE TABLE employees (
 employee_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
 department_id INT REFERENCES departments(department_id),
 manager_id INT REFERENCES employees(employee_id),
 salary DECIMAL(10,2) CHECK (salary >= 0), hire_date DATE
);
CREATE TABLE customers (
 customer_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
 country VARCHAR(30), email VARCHAR(100), points INT DEFAULT 0
);
CREATE TABLE products (
 product_id INT NOT NULL PRIMARY KEY, name VARCHAR(50) NOT NULL,
 category VARCHAR(30), price DECIMAL(8,2) CHECK (price >= 0)
);
CREATE TABLE orders (
 order_id INT NOT NULL PRIMARY KEY, customer_id INT REFERENCES customers(customer_id),
 order_date DATE NOT NULL, status VARCHAR(20) NOT NULL,
 amount DECIMAL(10,2) CHECK (amount >= 0)
);
CREATE TABLE order_items (
 order_id INT NOT NULL REFERENCES orders(order_id), product_id INT NOT NULL REFERENCES products(product_id),
 quantity INT NOT NULL CHECK (quantity > 0), unit_price DECIMAL(8,2) NOT NULL,
 PRIMARY KEY (order_id, product_id)
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'HR'),(4,'Finance');
INSERT INTO employees VALUES (1,'Alice',1,NULL,90000,'2022-01-10');
INSERT INTO employees VALUES (2,'Bob',1,1,70000,'2023-04-02'),(3,'Cara',1,1,70000,'2024-03-05'),(4,'Dan',2,NULL,60000,'2022-08-01');
INSERT INTO employees VALUES (5,'Eva',2,4,50000,'2024-01-15'),(6,'Finn',3,NULL,55000,'2023-06-10'),(7,'Gina',NULL,1,NULL,'2025-01-05');
INSERT INTO customers VALUES
 (1,'Ada','USA','ada@example.com',1200), (2,'Ben','UK',NULL,400),
 (3,'Cleo','USA','cleo@example.com',800), (4,'Dina','Germany','',0),
 (5,'Eli',NULL,'eli@example.com',NULL);
INSERT INTO products VALUES (10,'Laptop','Tech',100),(11,'Mouse','Tech',20),(12,'Notebook','Office',10),(13,'Pen','Office',5),(14,'Monitor','Tech',150);
INSERT INTO orders VALUES
 (101,1,'2025-01-10','Completed',120), (102,2,'2025-01-20','Completed',40),
 (103,1,'2025-02-05','Completed',80), (104,3,'2025-02-11','Cancelled',50),
 (105,3,'2025-03-01','Completed',150), (106,2,'2025-03-15','Completed',60),
 (107,NULL,'2025-03-20','Completed',20), (108,1,'2025-04-01','Pending',100);
INSERT INTO order_items VALUES
 (101,10,1,100),(101,11,1,20),(102,11,2,20),(103,11,4,20),
 (104,12,5,10),(105,10,1,100),(105,12,5,10),(106,11,3,20),
 (107,11,1,20),(108,10,1,100);

The baseline tables are shown below. Restore this setup in a fresh database if you change any baseline records.

customers

customer_id name country email points
1 Ada USA ada@example.com 1200
2 Ben UK NULL 400
3 Cleo USA cleo@example.com 800
4 Dina Germany 0
5 Eli NULL eli@example.com NULL

orders

order_id customer_id order_date status amount
101 1 2025-01-10 Completed 120
102 2 2025-01-20 Completed 40
103 1 2025-02-05 Completed 80
104 3 2025-02-11 Cancelled 50
105 3 2025-03-01 Completed 150
106 2 2025-03-15 Completed 60
107 NULL 2025-03-20 Completed 20
108 1 2025-04-01 Pending 100

products

product_id name category price
10 Laptop Tech 100
11 Mouse Tech 20
12 Notebook Office 10
13 Pen Office 5
14 Monitor Tech 150

employees

employee_id name department_id manager_id salary hire_date
1 Alice 1 NULL 90000 2022-01-10
2 Bob 1 1 70000 2023-04-02
3 Cara 1 1 70000 2024-03-05
4 Dan 2 NULL 60000 2022-08-01
5 Eva 2 4 50000 2024-01-15
6 Finn 3 NULL 55000 2023-06-10
7 Gina NULL 1 NULL 2025-01-05

departments

department_id department_name
1 Engineering
2 Sales
3 HR
4 Finance

order_items

order_id product_id quantity unit_price
101 10 1 100
101 11 1 20
102 11 2 20
103 11 4 20
104 12 5 10
105 10 1 100
105 12 5 10
106 11 3 20
107 11 1 20
108 10 1 100

Part I — SQL Foundations

Start by understanding the database, the shape of a table, and the clauses that select the information you need.

1. Introduction to SQL and databases

A database stores related data; a DBMS (database management system) creates, manages, protects and retrieves it. An RDBMS organizes data using relational tables and constraints. SQL is the language used to interact with these systems. A database is not the same as a database server, a DBMS, or a client application.

Text
Application / dashboard / analyst
            ↓ SQL request
     DBMS (parse → plan → execute)
            ↓ ↑
       Stored database
            ↓ results
         Client

Relational systems such as PostgreSQL, MySQL, SQLite and SQL Server share the relational model but implement different SQL dialects. Nonrelational families include document databases, key-value stores, graph databases and wide-column stores. Column-oriented analytical relational databases also exist; column storage is not synonymous with NoSQL. Relational tables resemble spreadsheets, but relationships, constraints, concurrency and query processing distinguish a DBMS from a simple file.

Command family Job Typical statements
DQL Retrieve data SELECT
DDL Define objects CREATE, ALTER, DROP
DML Change records INSERT, UPDATE, DELETE
DCL Control access GRANT, REVOKE (conceptual here)
TCL Control transactions COMMIT, ROLLBACK

CRUD means create, read, update and delete records: INSERT, SELECT, UPDATE, DELETE. It is different from creating or dropping a table.

Setup in other engines. Install the database server and appropriate client, connect to your local instance, create/select a practice database, and run an initialization script. MySQL uses USE database_name; SQL Server supports USE as well; PostgreSQL normally selects the database when connecting. SQL Server can also restore .bak files using its restore workflow. A local SQLite database is a file and does not require a separate server. Use strong credentials and keep them out of source control.

First query

SQL
SELECT 1 AS connected;

Output (SQLite practice data):

connected
1

How it works. The expression is evaluated even without a FROM clause.

Practical use. Check that the query editor is connected and can execute SQL.

Common mistakes. Confusing a client with the server; assuming every SQL dialect has identical syntax; running experimental DDL or DML against production.

Exercise. Retrieve the names of all customers.

Solution

SQL
SELECT name FROM customers ORDER BY customer_id;

Output (SQLite practice data):

name
Ada
Ben
Cleo
Dina
Eli

How it works. SELECT requests a column from the table, not a modification.

2. Database architecture and data types

A row is a record, a column is an attribute, and a cell is a value. A primary key identifies a row. A table has a schema: column names, types, constraints, and relationships. In SQL Server and PostgreSQL, a database can contain multiple named schemas; MySQL commonly treats schema and database as synonyms. A name such as Sales.Orders in SQL Server identifies an object within a schema.

Type family Common types Typical use
Integer INT, BIGINT IDs, counts
Exact numeric DECIMAL(p,s), NUMERIC(p,s) Monetary amounts; p total digits, s fractional digits
Approximate numeric FLOAT, REAL Measurements, scientific computation
Text CHAR(n), VARCHAR(n), TEXT Fixed/variable length text
Boolean BOOLEAN, SQL Server BIT Flags
Date/time DATE, TIME, DATETIME, TIMESTAMP Dates and instants; meanings vary
Binary BLOB, VARBINARY, BYTEA Binary objects

DECIMAL(5,2) means up to five total digits, two fractional digits (e.g. 999.99). Use exact numeric values for money in databases with fixed decimal types. Floating point is approximate; SQLite does not enforce fixed precision merely from DECIMAL(p,s). A date is not a time zone. PostgreSQL has TIMESTAMPTZ; SQL Server timestamp is a rowversion type, not a date/time. Choose text for telephone numbers or codes with leading zeroes, not arithmetic integers.

Physical storage and indexes are later topics; the logical table structure is what a query initially reasons about.

Inspect declared columns

SQL
PRAGMA table_info(customers);

Output (SQLite practice data):

cid name type notnull dflt_value pk
0 customer_id INT 1 NULL 1
1 name VARCHAR(50) 1 NULL 0
2 country VARCHAR(30) 0 NULL 0
3 email VARCHAR(100) 0 NULL 0
4 points INT 0 0 0

How it works. SQLite-specific metadata inspection. MySQL has DESCRIBE customers; SQL Server and PostgreSQL expose information_schema and client object explorers.

Practical use. Check column names and types before constructing a query.

Common mistakes. Using strings for all numeric/date data; confusing precision and scale; assuming SQLite validates VARCHAR length or decimal scale; storing sensitive passwords as plaintext.

Exercise. Inspect the orders schema and identify the key.

Solution

SQL
PRAGMA table_info(orders);

Output (SQLite practice data):

cid name type notnull dflt_value pk
0 order_id INT 1 NULL 1
1 customer_id INT 0 NULL 0
2 order_date DATE 1 NULL 0
3 status VARCHAR(20) 1 NULL 0
4 amount DECIMAL(10,2) 0 NULL 0

How it works. The pk flag identifies order_id. This metadata syntax is SQLite-specific.

3. SELECT and FROM

SELECT defines the columns or expressions in the result; FROM identifies the data source. Aliases (AS) make result columns meaningful. * expands all columns, but explicit projection keeps output stable and avoids unnecessary data transfer. SQL keywords are generally case-insensitive; identifiers and string comparison rules depend on dialect, quoting and collation.

SQL
SELECT column1, expression AS alias
FROM table_name;

Use one clause per line, consistent aliases and semicolons between statements. -- starts a line comment (in MySQL include a following space); /* ... */ marks a block comment. Logical processing starts with FROM, not the first word SELECT.

Select particular columns

SQL
SELECT customer_id, name, points FROM customers ORDER BY customer_id;

Output (SQLite practice data):

customer_id name points
1 Ada 1200
2 Ben 400
3 Cleo 800
4 Dina 0
5 Eli NULL

How it works. Only requested columns appear, in the order specified.

Practical use. Build a lightweight customer export.

Calculated columns

SQL
SELECT name, price, price * 1.10 AS new_price FROM products ORDER BY product_id;

Output (SQLite practice data):

name price new_price
Laptop 100 110.0
Mouse 20 22.0
Notebook 10 11.0
Pen 5 5.5
Monitor 150 165.0

How it works. The expression is evaluated per row without changing stored prices.

Practical use. Preview a proposed price increase.

Common mistakes. Omitting a comma between expressions; trailing comma before FROM; relying on SELECT * in production interfaces; using a SELECT alias in WHERE in most engines.

Exercise. Return each product name and the price after a 20% discount.

Solution

SQL
SELECT name, ROUND(price * 0.8, 2) AS discounted_price FROM products ORDER BY product_id;

Output (SQLite practice data):

name discounted_price
Laptop 80.0
Mouse 16.0
Notebook 8.0
Pen 4.0
Monitor 120.0

How it works. The discount is a derived result, not an UPDATE.

4. Filtering data and operators

WHERE retains rows for which the predicate evaluates TRUE. SQL uses three-valued logic: TRUE, FALSE and UNKNOWN. A comparison to NULL generally evaluates UNKNOWN, so use IS NULL or IS NOT NULL.

Operator Meaning
=, <>, !=, >, >=, <, <= Compare values
AND, OR, NOT Combine or negate predicates
BETWEEN a AND b Inclusive range
IN (...), NOT IN (...) Membership (NULL caveat later)
LIKE / NOT LIKE Pattern matching: % zero or more characters, _ one character
IS NULL, IS NOT NULL Missing value checks

NOT binds more tightly than AND, which binds more tightly than OR in common dialects; use parentheses for clarity. De Morgan's laws give NOT (A OR B) = NOT A AND NOT B. Negation does not turn UNKNOWN into TRUE. String literal values use single quotes; quote identifiers according to the engine rather than treating them as strings.

Compound filters

SQL
SELECT name, country, points
FROM customers
WHERE (country = 'USA' OR country = 'UK') AND points >= 800
ORDER BY customer_id;

Output (SQLite practice data):

name country points
Ada USA 1200
Cleo USA 800

How it works. Parentheses group the countries before applying the points condition.

Practical use. Segment eligible customers.

Range and list membership

SQL
SELECT order_id, amount, status
FROM orders
WHERE amount BETWEEN 40 AND 100 AND status IN ('Completed','Pending')
ORDER BY order_id;

Output (SQLite practice data):

order_id amount status
102 40 Completed
103 80 Completed
106 60 Completed
108 100 Pending

How it works. Both endpoints count. Each row must meet both predicates.

Practical use. Search a price band among selected statuses.

Wildcard and missing values

SQL
SELECT customer_id, name, email FROM customers
WHERE name LIKE 'A%' OR email IS NULL
ORDER BY customer_id;

Output (SQLite practice data):

customer_id name email
1 Ada ada@example.com
2 Ben NULL

How it works. A prefix pattern finds Ada; the missing-email predicate finds Ben.

Practical use. Find contact records requiring attention.

Common mistakes. Writing country = 'USA' OR 'UK' instead of two comparisons or IN; writing = NULL; using BETWEEN on timestamps without considering end-of-day; assuming LIKE is always case-sensitive.

Exercise. Find completed orders of at least 60 but less than 150.

Solution

SQL
SELECT order_id, amount FROM orders WHERE status = 'Completed' AND amount >= 60 AND amount < 150 ORDER BY order_id;

Output (SQLite practice data):

order_id amount
101 120
103 80
106 60

How it works. An explicit half-open range excludes 150.

5. Sorting, DISTINCT and pagination

ORDER BY determines result ordering. Use ASC (default) or DESC, with additional columns for tie-breaking. Without ORDER BY no row order is guaranteed. DISTINCT removes duplicate output rows, not duplicate values of each column independently. Pagination limits the returned rows, not necessarily the work required to find them.

Engine Return first 3 rows Skip 3, return 3
SQLite/PostgreSQL/MySQL LIMIT 3 LIMIT 3 OFFSET 3
MySQL alternate LIMIT 3 LIMIT 3, 3 (offset, count)
SQL Server SELECT TOP (3) ... ORDER BY ... OFFSET 3 ROWS FETCH NEXT 3 ROWS ONLY

SQL Server TOP and the LIMIT variants require deterministic ORDER BY when asking for a particular top N. Positional ORDER BY 2 is possible but brittle when projection changes. NULL ordering differs across engines.

SQL Server top-N syntax

Dialect: SQL Server.

SQL
SELECT TOP (3) name,salary FROM dbo.employees WHERE salary IS NOT NULL ORDER BY salary DESC,employee_id;

Expected behavior (illustrative): Alice 90000, Bob 70000, Cara 70000.

How it works. TOP limits the sorted result to three rows.

Distinct values

SQL
SELECT DISTINCT country FROM customers ORDER BY country;

Output (SQLite practice data):

country
NULL
Germany
UK
USA

How it works. DISTINCT collapses repeated USA and retains one NULL.

Practical use. List the countries present in the dataset.

Top 3 with a stable tie-break

SQL
SELECT name, salary FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC, employee_id LIMIT 3;

Output (SQLite practice data):

name salary
Alice 90000
Bob 70000
Cara 70000

How it works. Salary is the primary sort; employee_id makes the tie reproducible.

Practical use. Retrieve the highest-paid employees.

Page two

SQL
SELECT order_id, order_date FROM orders ORDER BY order_date, order_id LIMIT 3 OFFSET 3;

Output (SQLite practice data):

order_id order_date
104 2025-02-11
105 2025-03-01
106 2025-03-15

How it works. Skip the first three sorted rows, then return three.

Practical use. Provide a small page of order history.

Common mistakes. Relying on physical row order; adding DISTINCT to hide a bad join; using LIMIT without ORDER BY for ranking; using large offsets without considering performance.

Exercise. Find the second and third most expensive products.

Solution

SQL
SELECT name, price FROM products ORDER BY price DESC, product_id LIMIT 2 OFFSET 1;

Output (SQLite practice data):

name price
Laptop 100
Mouse 20

How it works. Skip the first result, then return two.

Part II — Database Engineering

A useful query depends on a well-designed database. Now move from retrieving records to defining and maintaining their structure.

6. Creating and modifying databases and tables

DDL defines database objects. CREATE DATABASE shop; and USE shop; are MySQL/SQL Server examples (PostgreSQL connects to the chosen database; SQLite opens a file). DROP DATABASE removes an entire database and is destructive. MySQL also supports database read-only configuration in versions that implement it: ALTER DATABASE shop READ ONLY = 1; (reset to 0 before changing the practice database). Read-only modes and encryption settings are engine-specific administrative controls.

CREATE TABLE defines columns, types and constraints. ALTER TABLE changes a definition. DROP TABLE removes the table itself, including data. DELETE removes rows; TRUNCATE TABLE clears a table in engines that support it, with different identity, trigger and transaction behavior. SQLite has no TRUNCATE statement.

Operation Example / dialect
Add column ALTER TABLE sandbox ADD COLUMN notes VARCHAR(100); (SQLite, PostgreSQL, MySQL)
Rename column ALTER TABLE sandbox RENAME COLUMN notes TO description; (SQLite, PostgreSQL, modern MySQL)
Rename table ALTER TABLE sandbox RENAME TO sandbox_new; (SQLite/PostgreSQL); MySQL RENAME TABLE sandbox TO sandbox_new
Modify type MySQL MODIFY COLUMN description VARCHAR(200); PostgreSQL ALTER COLUMN description TYPE VARCHAR(200)
Reorder column MySQL MODIFY COLUMN description VARCHAR(200) FIRST or AFTER other_column
Drop column ALTER TABLE sandbox DROP COLUMN description; (subject to dependencies/version)

SQL Server uses different syntax for certain operations, including sp_rename and ALTER COLUMN. DDL can lock objects or implicitly commit in some engines. Use explicit column lists in inserts rather than relying on physical order.

Build and inspect a disposable table

SQL
SELECT id, label, notes FROM sandbox ORDER BY id;

Output (SQLite practice data):

id label notes
1 sample NULL

How it works. The preparation creates the table, inserts one row and adds a nullable column. Existing rows have NULL for notes.

Practical use. Add a new optional attribute without manually recreating the table.

SQL
-- Run in a fresh practice database.
CREATE TABLE sandbox (id INT PRIMARY KEY, label VARCHAR(30));
INSERT INTO sandbox VALUES (1, 'sample');
ALTER TABLE sandbox ADD COLUMN notes VARCHAR(100);
SELECT id, label, notes FROM sandbox;
-- After inspection, clean up only this disposable table:
DROP TABLE sandbox;

Common mistakes. Confusing DROP, DELETE and TRUNCATE; dropping dependent columns; assuming all DDL can be rolled back; applying type conversions without validating existing data.

Exercise. Create a disposable two-column table and add a nullable integer quantity column. Inspect the result.

Run this preparation in a fresh practice connection:

SQL
CREATE TABLE stock_sandbox(id INT PRIMARY KEY, name VARCHAR(30));
ALTER TABLE stock_sandbox ADD COLUMN quantity INT;

Solution

SQL
PRAGMA table_info(stock_sandbox);

Output (SQLite practice data):

cid name type notnull dflt_value pk
0 id INT 0 NULL 1
1 name VARCHAR(30) 0 NULL 0
2 quantity INT 0 NULL 0

How it works. The new field appears in the schema. Execute the two preparation statements before the inspection.

7. Keys, relationships and constraints

A key identifies records or connects tables. A primary key is unique and non-null (one primary key constraint may cover multiple columns). A foreign key references an eligible unique parent key, often a primary key. Natural keys have meaning outside the database; surrogate keys are assigned identifiers. A composite key combines attributes. In order_items, neither order_id nor product_id is individually unique, but the pair is.

Constraint / attribute What it does
PRIMARY KEY Identifies the row
FOREIGN KEY ... REFERENCES Rejects invalid non-null references
NOT NULL Prevents missing values
UNIQUE Prevents duplicate non-null key values; NULL behavior varies
CHECK Rejects rows violating a condition (UNKNOWN can pass)
DEFAULT Supplies a value when omitted
MySQL AUTO_INCREMENT, SQL Server IDENTITY, PostgreSQL GENERATED ... AS IDENTITY Generates identifiers

Define constraints at creation or use supported ALTER TABLE ... ADD CONSTRAINT operations later. SQLite often requires a table rebuild for new constraints. Name constraints to make maintenance and diagnostics easier. A default is not a replacement for an explicitly supplied NULL unless the engine has a special rule. Generated IDs need not be consecutive.

One-to-one relationships require uniqueness of the foreign key; one-to-many is implemented using a foreign key on the many side. Many-to-many uses a junction table. Self-referencing keys represent relationships such as employee → manager.

SQL
CREATE TABLE demo_pay (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE,
  hourly_pay DECIMAL(5,2) NOT NULL,
  CONSTRAINT chk_pay CHECK (hourly_pay >= 10)
);

Expected behavior. A row with hourly pay 15 is accepted. A row with 5 or NULL is rejected. Adding a second non-null email identical to an existing one violates UNIQUE. A nullable unique email may allow multiple NULLs depending on engine. A constraint enforces valid data at write time, instead of relying on every application to validate independently.

SQL
CREATE TABLE demo_parent (id INT PRIMARY KEY);
CREATE TABLE demo_child (
    id INT PRIMARY KEY,
    parent_id INT REFERENCES demo_parent(id) ON DELETE SET NULL
);

ON DELETE SET NULL retains child rows and clears a nullable reference. ON DELETE CASCADE deletes matching child rows. RESTRICT / NO ACTION prevents deletion while dependent references exist, subject to engine timing rules. Cascades should reflect business intent; a foreign key in a composite primary key does not automatically require CASCADE.

Show a many-to-many association

SQL
SELECT oi.order_id, p.name, oi.quantity
FROM order_items oi JOIN products p ON p.product_id = oi.product_id
WHERE oi.order_id = 101 ORDER BY p.product_id;

Output (SQLite practice data):

order_id name quantity
101 Laptop 1
101 Mouse 1

How it works. One order connects to two products through the junction table.

Practical use. Represent purchases without repeating customer or product attributes.

Common mistakes. Using names as identifiers when they are not unique; forgetting foreign-key enforcement; assuming a CHECK automatically rejects NULL; cascading deletions without understanding downstream effects.

Exercise. Predict and inspect the child row after deleting its parent with ON DELETE SET NULL.

Run this preparation in a fresh practice connection:

SQL
CREATE TABLE demo_parent(id INT PRIMARY KEY);
CREATE TABLE demo_child(id INT PRIMARY KEY, parent_id INT REFERENCES demo_parent(id) ON DELETE SET NULL);
INSERT INTO demo_parent VALUES(1);
INSERT INTO demo_child VALUES(10,1);
DELETE FROM demo_parent WHERE id=1;

Solution

SQL
SELECT * FROM demo_child;

Output (SQLite practice data):

id parent_id
10 NULL

How it works. The child remains and its parent_id becomes NULL. The preparation shown conceptually above uses a disposable database.

8. INSERT, UPDATE and DELETE

DML changes stored records. Always specify the column list when inserting partial rows; omitted columns receive defaults or NULL if allowed. Multirow VALUES is more concise than separate INSERT statements. INSERT INTO ... SELECT copies rows from a query. Use UPDATE ... SET for existing rows and DELETE FROM ... WHERE to delete matching rows, not columns.

SQL
INSERT INTO table_name (col1, col2) VALUES (value1, value2);
UPDATE table_name SET col2 = value WHERE condition;
DELETE FROM table_name WHERE condition;

Preview the exact WHERE predicate with SELECT first. A missing predicate updates or deletes every row. UPDATE can use expressions, multiple assignments and subqueries; a DELETE can use a subquery as well. Workbench safe-update mode may restrict operations not using appropriate key predicates or limits, but it is not a guarantee of safety.

SQL
CREATE TABLE demo_products AS SELECT * FROM products;
INSERT INTO demo_products(product_id,name,category,price) VALUES(15,'Cable','Tech',8),(16,'Bag','Office',30);
UPDATE demo_products SET price=price*1.1 WHERE category='Tech';
DELETE FROM demo_products WHERE product_id=16;

Inspect the modified copy

SQL
SELECT product_id,name,price FROM demo_products ORDER BY product_id;

Output (SQLite practice data):

product_id name price
10 Laptop 110.0
11 Mouse 22
12 Notebook 10
13 Pen 5
14 Monitor 165
15 Cable 8.8

How it works. Two records are inserted, the Tech rows increase by 10%, then Bag is deleted. This copy has no inherited constraints.

Practical use. Try changes without modifying the baseline products table.

Parent-child insertion (MySQL example). A generated parent ID must be reused in the same connection when inserting child rows. Use a transaction to commit both operations together. The following assumes a schema in which orders.order_id is AUTO_INCREMENT and the other fields match our practice schema. PostgreSQL can use INSERT ... RETURNING order_id; SQL Server can use OUTPUT INSERTED.order_id or SCOPE_IDENTITY() with appropriate care.

SQL
START TRANSACTION;
INSERT INTO orders (customer_id, order_date, status, amount)
VALUES (1, '2025-05-01', 'Completed', 40);
SET @order_id = LAST_INSERT_ID();
INSERT INTO order_items (order_id, product_id, quantity, unit_price)
VALUES (@order_id, 11, 2, 20);
COMMIT;

Expected: one new order and one child line referencing the generated ID, or rollback on failure. This example requires a MySQL-specific identity schema and is not run in SQLite. In application code, handle errors and roll back explicitly.

Common mistakes. Omitting WHERE; assuming CTAS preserves constraints; relying on consecutive generated IDs; concatenating user input into SQL instead of binding parameters.

Exercise. On a disposable copy, flag completed orders of at least 100 as Reviewed.

Run this preparation in a fresh practice connection:

SQL
CREATE TABLE orders_copy AS SELECT * FROM orders;
UPDATE orders_copy SET status='Reviewed' WHERE status='Completed' AND amount>=100;

Solution

SQL
SELECT order_id,status FROM orders_copy ORDER BY order_id;

Output (SQLite practice data):

order_id status
101 Reviewed
102 Completed
103 Completed
104 Cancelled
105 Reviewed
106 Completed
107 Completed
108 Pending

How it works. Only qualifying orders change; the baseline stays intact.

9. Transactions and safe data manipulation

A transaction groups changes into a unit of work. COMMIT makes changes durable according to the database's guarantees; ROLLBACK undoes uncommitted changes. Autocommit is commonly enabled, so separate statements may each commit automatically. In MySQL SET autocommit = 0 disables it for that session; PostgreSQL, SQLite and SQL Server have their own transaction syntax.

Text
BEGIN → modifications → validation → COMMIT
                        └─ error → ROLLBACK

A useful mental model is that one purchase should not persist its order without its item rows. For transactional storage, the logical unit should succeed together or fail together. A commit is not a savepoint. Committed changes cannot be undone by ordinary ROLLBACK. This chapter covers the practical transaction basics, not a deep treatment of isolation, locking or deadlocks.

SQL
BEGIN TRANSACTION;
DELETE FROM order_items WHERE order_id = 108;
DELETE FROM orders WHERE order_id = 108;
SELECT COUNT(*) AS remaining_orders FROM orders;
ROLLBACK;
SELECT COUNT(*) AS remaining_orders FROM orders;

Output (executed in a fresh SQLite database):

Stage orders count
Before 8
Before rollback 7
After rollback 8

The child is deleted before the parent to satisfy the foreign key. The rollback restores both. In a real transaction, COMMIT would be used after validation. SQL Server BEGIN TRANSACTION and PostgreSQL BEGIN are suitable; MySQL uses START TRANSACTION. Do not rely on rolling back MySQL DDL that causes implicit commits.

Common mistakes. Expecting ROLLBACK to undo a committed statement; leaving transactions open; treating a transaction as a backup; failing to handle errors or foreign keys.

Exercise. Preview deleting all rows from a disposable copy and then restore them with a rollback.

Solution

Dialect: SQLite (run as a script in a fresh connection).

SQL
CREATE TABLE tx_demo AS SELECT * FROM customers;
-- Commit table creation first if your client has an open transaction.
BEGIN TRANSACTION;
DELETE FROM tx_demo;
SELECT COUNT(*) FROM tx_demo;
ROLLBACK;
SELECT COUNT(*) FROM tx_demo;

Expected behavior (illustrative): 0 during the transaction, 5 after rollback. The table creation is outside the transaction.

10. ER diagrams and relational database design

Start with business requirements, not with CREATE TABLE. Identify entities, attributes, keys, relationships, cardinality and participation. An entity represents an object such as customer; an attribute describes it. A relationship connects entities. Cardinality is the number of entities that can participate (one or many); participation indicates whether involvement is mandatory or optional.

ER concept Example Relational mapping
Strong entity Customer Table with a primary key
Composite attribute Full name, address Separate atomic fields where appropriate
Multivalued attribute Customer phone numbers Child table with customer key and phone
Derived attribute Age from birth date Compute when needed
Weak entity Order line dependent on order Owner key plus identifying attribute(s)
Relationship attribute Quantity on order/product Store in junction table
1:1 Employee and assigned locker FK with UNIQUE, or combine if appropriate
1:N Customer and order FK on many side
M:N Order and product Junction table

Separating customer details from orders avoids repeating the same address on every order when the address is a customer attribute. Historical shipping addresses may intentionally be stored on orders if they represent the address at the time of purchase. That is a business requirement, not needless duplication. This introduces normalization intuitively; formal normal forms are beyond this chapter.

Text
Requirements → ER diagram → relational schema → constraints → test data → queries
Customer 0..N Orders; Order 0..N Items; Product 0..N Items
Each Item references exactly one Order and one Product (in a strict design).

In the practice schema, the order customer is optional (anonymous purchase); the item composite primary key identifies one product per order. A separate line ID would be needed if repeated identical products can appear on separate lines. ER diagrams often use rectangles for entities, ovals for attributes and diamonds for relationships, or crow's-foot notation for cardinality.

SQL
CREATE TABLE demo_supplier (supplier_id INT NOT NULL PRIMARY KEY, name VARCHAR(50));
CREATE TABLE demo_supply (
 supplier_id INT NOT NULL REFERENCES demo_supplier(supplier_id),
 product_id INT NOT NULL REFERENCES products(product_id),
 cost DECIMAL(8,2) CHECK (cost >= 0),
 PRIMARY KEY (supplier_id, product_id)
);

Expected: a supplier can supply multiple products and a product can have multiple suppliers. The junction table records a relationship-specific cost. A repeated pair is rejected.

Common mistakes. Storing multiple phone numbers in a comma-separated field; choosing the wrong grain for a fact table; confusing optional participation with cardinality; assuming FK alone enforces a mandatory or one-to-one relationship.

Exercise. Design a student/course enrollment relationship including a grade.

Solution

Dialect: Portable DDL (fresh practice database).

SQL
CREATE TABLE students (student_id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE courses (course_id INT PRIMARY KEY, title VARCHAR(100));
CREATE TABLE enrollments (
 student_id INT NOT NULL REFERENCES students(student_id),
 course_id INT NOT NULL REFERENCES courses(course_id),
 grade DECIMAL(5,2), PRIMARY KEY (student_id, course_id)
);

Expected behavior (illustrative): One record per student/course pair; grade belongs to enrollment, not student or course. If retakes are allowed, include an attempt identifier.

Part III — Querying and Combining Data

Learn to summarize rows, combine related records, compare datasets and break complex questions into smaller queries.

11. Aggregation, GROUP BY and HAVING

Aggregate functions return a summary rather than a value per input row. COUNT(*) counts rows; COUNT(column) counts non-NULL values; COUNT(DISTINCT column) counts distinct non-null values. SUM, AVG, MIN and MAX ignore NULL inputs; with no non-null inputs they normally return NULL. AVG uses the number of non-null values, not the total row count.

GROUP BY defines the output grain. One group per country means one result row per country. WHERE filters input rows; HAVING filters groups after aggregation. Selected expressions that are neither aggregates nor grouped must satisfy the engine's grouping rules; portable queries group every nonaggregated column. Think of aggregation as collapsing rows, not adding a total to every row.

Logical sequence (simplified) Purpose
FROM / JOIN / ON Build input rows
WHERE Filter rows
GROUP BY Form groups
HAVING Filter groups
SELECT (including windows after grouping) Compute output expressions
DISTINCT Remove duplicate output rows
ORDER BY Sort result
LIMIT / TOP / OFFSET-FETCH Limit result

This is logical processing, not the physical execution plan. An optimizer can reorder operations while preserving query semantics.

Overall summary

SQL
SELECT COUNT(*) AS orders, COUNT(customer_id) AS identified_orders, SUM(amount) AS total, AVG(amount) AS mean_amount, MIN(amount) AS minimum, MAX(amount) AS maximum FROM orders;

Output (SQLite practice data):

orders identified_orders total mean_amount minimum maximum
8 7 620 77.5 20 150

How it works. COUNT(customer_id) excludes the anonymous order. Other aggregates summarize the amount column.

Practical use. Profile records before further analysis.

Group and filter

SQL
SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS total
FROM orders
WHERE status = 'Completed'
GROUP BY customer_id
HAVING SUM(amount) >= 100
ORDER BY total DESC;

Output (SQLite practice data):

customer_id orders total
1 2 200
3 1 150
2 2 100

How it works. First discard noncompleted rows; group by customer; then filter the totals.

Practical use. Find valuable customers.

ROLLUP. Reporting queries often need both detail groups and a grand total. MySQL uses GROUP BY department_id WITH ROLLUP; SQL Server/PostgreSQL use GROUP BY ROLLUP(department_id). SQLite can emulate a one-level rollup with UNION ALL. A subtotal NULL is different from a genuine NULL grouping value; use GROUPING() where available or explicit labels.

One-level subtotal and total

SQL
SELECT COALESCE(CAST(department_id AS VARCHAR(10)), 'Unassigned') AS department,
       SUM(salary) AS total_salary
FROM employees GROUP BY department_id
UNION ALL
SELECT 'Grand total', SUM(salary) FROM employees;

Output (SQLite practice data):

department total_salary
Unassigned NULL
1 230000
2 110000
3 55000
Grand total 395000

How it works. The second query aggregates all rows; UNION ALL appends the total. The unassigned employee has an unknown salary.

Practical use. Prepare a report with subtotals.

Common mistakes. Using WHERE SUM(...); averaging group averages without weighting; counting rows after a one-to-many join without checking grain; treating missing salary as zero by default.

Exercise. Find completed revenue by status-independent customer ID, but only customers with at least two completed orders.

Solution

SQL
SELECT customer_id, COUNT(*) AS n, SUM(amount) AS revenue
FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
GROUP BY customer_id HAVING COUNT(*) >= 2 ORDER BY customer_id;

Output (SQLite practice data):

customer_id n revenue
1 2 200
2 2 100

How it works. WHERE removes anonymous/noncompleted rows; HAVING tests the number of remaining orders per customer.

12. All JOIN types and join strategies

A join combines columns from related tables. Think in terms of matching row pairs, not a Venn diagram alone. If a customer has three orders, joining the customer to orders returns three customer/order pairs. If both sides have multiple matching rows, the counts multiply.

Join Behavior
INNER Matching pairs only
LEFT OUTER All left rows; unmatched right columns become NULL
RIGHT OUTER All right rows; unmatched left columns become NULL
FULL OUTER Matching pairs and unmatched rows on both sides
CROSS Cartesian product (all pairs)
SELF A table joined to itself using different aliases
LEFT/RIGHT anti Rows from one side with no match, via outer join + NULL or NOT EXISTS
FULL anti Unmatched rows from both sides, via full join + filters

MySQL does not have native FULL OUTER JOIN; combine a left join with a right-side anti join using UNION ALL. SQLite 3.39+ supports RIGHT and FULL. SQL Server, PostgreSQL and MySQL support CROSS JOIN; the self join is a pattern, not a keyword.

Inner join — orders with customers

SQL
SELECT o.order_id, c.name, o.amount
FROM orders o INNER JOIN customers c ON o.customer_id = c.customer_id
ORDER BY o.order_id;

Output (SQLite practice data):

order_id name amount
101 Ada 120
102 Ben 40
103 Ada 80
104 Cleo 50
105 Cleo 150
106 Ben 60
108 Ada 100

How it works. The anonymous order cannot match a customer and is excluded.

Practical use. Attach customer information to transactions.

Left join — all customers, including those with no orders

SQL
SELECT c.name, o.order_id
FROM customers c LEFT JOIN orders o ON c.customer_id=o.customer_id
ORDER BY c.customer_id, o.order_id;

Output (SQLite practice data):

name order_id
Ada 101
Ada 103
Ada 108
Ben 102
Ben 106
Cleo 104
Cleo 105
Dina NULL
Eli NULL

How it works. Dina and Eli survive the join with NULL order IDs. Ada appears three times.

Practical use. Keep all customers in a retention report.

Right join — preserve all customers

SQL
SELECT c.name,o.order_id FROM orders o RIGHT JOIN customers c ON o.customer_id=c.customer_id ORDER BY c.customer_id,o.order_id;

Output (SQLite practice data):

name order_id
Ada 101
Ada 103
Ada 108
Ben 102
Ben 106
Cleo 104
Cleo 105
Dina NULL
Eli NULL

How it works. Swapping the table order and using RIGHT JOIN gives the same logical matching pairs as the earlier LEFT JOIN.

Practical use. Preserve the reference population.

Full outer join — reconcile both datasets

SQL
SELECT c.customer_id, c.name, o.order_id
FROM customers c FULL OUTER JOIN orders o ON c.customer_id=o.customer_id
ORDER BY c.customer_id, o.order_id;

Output (SQLite practice data):

customer_id name order_id
NULL NULL 107
1 Ada 101
1 Ada 103
1 Ada 108
2 Ben 102
2 Ben 106
3 Cleo 104
3 Cleo 105
4 Dina NULL
5 Eli NULL

How it works. Customers without orders and the anonymous order all appear.

Practical use. Find unmatched source records.

Left anti join — customers without orders

SQL
SELECT c.customer_id, c.name
FROM customers c LEFT JOIN orders o ON o.customer_id=c.customer_id
WHERE o.order_id IS NULL ORDER BY c.customer_id;

Output (SQLite practice data):

customer_id name
4 Dina
5 Eli

How it works. Test a non-nullable key from the right table to distinguish unmatched rows from matched rows with missing attributes.

Practical use. Identify potential re-engagement targets.

Full anti join — unmatched rows on either side

SQL
SELECT c.name,o.order_id FROM customers c FULL OUTER JOIN orders o ON c.customer_id=o.customer_id WHERE c.customer_id IS NULL OR o.order_id IS NULL ORDER BY c.name,o.order_id;

Output (SQLite practice data):

name order_id
NULL 107
Dina NULL
Eli NULL

How it works. Keep only the rows without a partner on either side.

Practical use. Reconcile missing references and unused customer records.

Self outer join — employees and managers

SQL
SELECT e.name AS employee, m.name AS manager
FROM employees e LEFT JOIN employees m ON e.manager_id=m.employee_id
ORDER BY e.employee_id;

Output (SQLite practice data):

employee manager
Alice NULL
Bob Alice
Cara Alice
Dan NULL
Eva Dan
Finn NULL
Gina Alice

How it works. Aliases distinguish the two roles of the same table. Top-level employees remain.

Practical use. Create an organization directory.

Cross join — combinations

SQL
WITH sizes AS (SELECT 'Small' AS size UNION ALL SELECT 'Large'),
colors AS (SELECT 'Red' AS color UNION ALL SELECT 'Blue')
SELECT size,color FROM sizes CROSS JOIN colors ORDER BY size,color;

Output (SQLite practice data):

size color
Large Blue
Large Red
Small Blue
Small Red

How it works. Two sizes times two colors produce four rows.

Practical use. Generate possible product variations or parameter combinations.

Multiple joins and matching composite keys

SQL
SELECT o.order_id, c.name AS customer, p.name AS product, oi.quantity
FROM orders o LEFT JOIN customers c ON o.customer_id=c.customer_id
JOIN order_items oi ON oi.order_id=o.order_id
JOIN products p ON p.product_id=oi.product_id
ORDER BY o.order_id,p.product_id;

Output (SQLite practice data):

order_id customer product quantity
101 Ada Laptop 1
101 Ada Mouse 1
102 Ben Mouse 2
103 Ada Mouse 4
104 Cleo Notebook 5
105 Cleo Laptop 1
105 Cleo Notebook 5
106 Ben Mouse 3
107 NULL Mouse 1
108 Ada Laptop 1

How it works. The grain is now order line, not order. Joining orders to their items repeats order-level amounts.

Practical use. Create a line-level sales report.

For a compound relationship, match every component of the key. For example ON a.order_id=b.order_id AND a.product_id=b.product_id. In SQLite, PostgreSQL and MySQL JOIN ... USING (order_id, product_id) is a shorthand when names match; SQL Server uses ON. USING changes how common columns appear under SELECT *. NATURAL JOIN matches all identically named columns automatically and can silently change behavior if schemas change. Prefer explicit conditions. Implicit joins such as FROM customers c, orders o WHERE ... are legal in many engines but can accidentally become cross joins.

Cross-database joins: MySQL can refer to sql_store.order_items and sql_inventory.products on the same server; SQL Server supports database.schema.table. PostgreSQL requires an appropriate cross-database mechanism rather than simply another database prefix. In SQLite attached database files use schema-qualified names.

Important outer-join trap: placing o.status='Completed' in WHERE after a left join removes unmatched rows. Put the predicate in ON when the goal is to retain every customer while matching only completed orders.

USING with a shared column

SQL
SELECT customer_id,c.name,o.order_id FROM customers c JOIN orders o USING(customer_id) ORDER BY o.order_id;

Output (SQLite practice data):

customer_id name order_id
1 Ada 101
2 Ben 102
1 Ada 103
3 Cleo 104
3 Cleo 105
2 Ben 106
1 Ada 108

How it works. The common key is specified once; the qualified columns distinguish the two tables.

Compound join — match the whole key

SQL
WITH item_notes(order_id,product_id,note) AS (SELECT 101,11,'Gift wrap' UNION ALL SELECT 105,12,'Urgent')
SELECT oi.order_id,oi.product_id,n.note FROM order_items oi JOIN item_notes n ON n.order_id=oi.order_id AND n.product_id=oi.product_id ORDER BY oi.order_id,oi.product_id;

Output (SQLite practice data):

order_id product_id note
101 11 Gift wrap
105 12 Urgent

How it works. Matching just the order ID would incorrectly attach each note to every item in that order.

Practical use. Join line-level attributes without multiplying rows.

Keep all customers while counting completed orders

SQL
SELECT c.name, COUNT(o.order_id) AS completed_orders
FROM customers c LEFT JOIN orders o
  ON o.customer_id=c.customer_id AND o.status='Completed'
GROUP BY c.customer_id,c.name ORDER BY c.customer_id;

Output (SQLite practice data):

name completed_orders
Ada 2
Ben 2
Cleo 1
Dina 0
Eli 0

How it works. COUNT of the right key is zero for no match, unlike COUNT(*).

Practical use. Build customer activity features without losing inactive customers.

Common mistakes. Joining on names instead of stable keys; missing a composite-key condition; COUNT(*) after outer join; filtering the nullable side in WHERE; summing order-level amounts after expanding to line grain.

Exercise. Find products that have never appeared in an order item.

Solution

SQL
SELECT p.product_id,p.name FROM products p
LEFT JOIN order_items oi ON oi.product_id=p.product_id
WHERE oi.order_id IS NULL ORDER BY p.product_id;

Output (SQLite practice data):

product_id name
13 Pen
14 Monitor

How it works. The anti join returns products without any matching item.

13. Set operators

Joins combine columns; set operators combine rows from compatible result sets. Each branch must return the same number of columns, in the same semantic order, with compatible types. The first query generally defines output names. UNION, INTERSECT, and EXCEPT remove duplicate rows by default; UNION ALL preserves multiplicity. An ORDER BY at the end sorts the combined result. SQL Server and PostgreSQL support these four; SQLite does too. Older MySQL versions lack INTERSECT and EXCEPT; check the version.

Operator Result when A = {1,2,2,3}, B = {2,4}
UNION 1, 2, 3, 4
UNION ALL 1, 2, 2, 3, 2, 4
INTERSECT 2
EXCEPT (A minus B) 1, 3

Use UNION ALL for appending monthly extracts when rows should be retained; UNION for genuinely distinct rows. To compare two datasets' distinct contents, check EXCEPT in both directions. This does not verify duplicate multiplicities.

UNION — completed customers versus customers with high points

SQL
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
UNION
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;

Output (SQLite practice data):

customer_id
1
2
3

How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.

Practical use. Compare customer cohorts.

UNION ALL — completed customers versus customers with high points

SQL
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
UNION ALL
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;

Output (SQLite practice data):

customer_id
1
1
1
2
2
3
3

How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.

Practical use. Compare customer cohorts.

INTERSECT — completed customers versus customers with high points

SQL
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
INTERSECT
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;

Output (SQLite practice data):

customer_id
1
3

How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.

Practical use. Compare customer cohorts.

EXCEPT — completed customers versus customers with high points

SQL
SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
EXCEPT
SELECT customer_id FROM customers WHERE points>=800
ORDER BY customer_id;

Output (SQLite practice data):

customer_id
2

How it works. Each branch selects a compatible identifier. The operator determines membership and multiplicity.

Practical use. Compare customer cohorts.

Common mistakes. Using UNION when duplicate events are meaningful; mismatching column order; treating EXCEPT as symmetric; assuming UNION ALL guarantees branch order.

Exercise. Find customers who have never placed an order using EXCEPT.

Solution

SQL
SELECT customer_id FROM customers
EXCEPT
SELECT customer_id FROM orders
ORDER BY customer_id;

Output (SQLite practice data):

customer_id
4
5

How it works. Subtract identifiers present in orders.

14. Subqueries and subquery operators

A subquery is a query embedded in another statement. It may return a single scalar, a list of values, or a table. A scalar subquery must return at most one row and one column in engines that enforce scalar cardinality; SQLite can take the first row, which can conceal mistakes. A derived table in FROM or JOIN needs an alias for portable code.

A noncorrelated subquery can be understood independently of the outer row. A correlated subquery references an outer column; conceptually it is evaluated for that row, although the optimizer may rewrite it. SQL engines may decorrelate, cache or otherwise optimize either form.

Scalar subquery — orders above average

SQL
SELECT order_id,amount FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders)
ORDER BY amount DESC,order_id;

Output (SQLite practice data):

order_id amount
105 150
101 120
108 100
103 80

How it works. The inner aggregate returns one number; the outer WHERE compares each order to it.

Practical use. Identify larger-than-average transactions.

Subquery in SELECT — attach a global average

SQL
SELECT order_id,amount,(SELECT ROUND(AVG(amount),2) FROM orders) AS overall_avg FROM orders WHERE order_id IN (101,102) ORDER BY order_id;

Output (SQLite practice data):

order_id amount overall_avg
101 120 77.5
102 40 77.5

How it works. The independent scalar subquery supplies the same baseline for each selected row.

Derived table in JOIN

SQL
SELECT c.name,COALESCE(t.total,0) AS total FROM customers c LEFT JOIN (SELECT customer_id,SUM(amount) AS total FROM orders WHERE status='Completed' GROUP BY customer_id) t ON c.customer_id=t.customer_id ORDER BY c.customer_id;

Output (SQLite practice data):

name total
Ada 200
Ben 100
Cleo 150
Dina 0
Eli 0

How it works. Aggregate to customer grain before joining, preserving each customer exactly once.

Derived table — filter aggregated totals

SQL
SELECT t.customer_id,t.total FROM (
 SELECT customer_id,SUM(amount) AS total FROM orders GROUP BY customer_id
) AS t WHERE t.total>100 ORDER BY t.customer_id;

Output (SQLite practice data):

customer_id total
1 300
3 200

How it works. The inner table establishes customer grain; the outer query filters that result.

Practical use. Build a reusable intermediate calculation within a statement.

Correlated subquery — customer average

SQL
SELECT o.order_id,o.customer_id,o.amount FROM orders o
WHERE o.amount > (SELECT AVG(i.amount) FROM orders i WHERE i.customer_id=o.customer_id)
ORDER BY o.order_id;

Output (SQLite practice data):

order_id customer_id amount
101 1 120
105 3 150
106 2 60

How it works. The average is for the outer order customer. NULL customer IDs do not match using equality.

Practical use. Compare each transaction with its customer baseline.

IN with a multirow subquery

SQL
SELECT name FROM customers WHERE customer_id IN (SELECT customer_id FROM orders WHERE status='Completed') ORDER BY customer_id;

Output (SQLite practice data):

name
Ada
Ben
Cleo

How it works. The inner query supplies eligible IDs. Repeated IDs do not multiply outer rows.

EXISTS — customers with a completed purchase

SQL
SELECT c.customer_id,c.name FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o
 WHERE o.customer_id=c.customer_id AND o.status='Completed')
ORDER BY c.customer_id;

Output (SQLite practice data):

customer_id name
1 Ada
2 Ben
3 Cleo

How it works. EXISTS tests whether at least one matching row exists; it does not duplicate customers with many orders.

Practical use. Semijoin-style filtering.

NOT EXISTS — safe anti-match

SQL
SELECT c.customer_id,c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id=c.customer_id)
ORDER BY c.customer_id;

Output (SQLite practice data):

customer_id name
4 Dina
5 Eli

How it works. The anonymous order does not invalidate the test. In contrast, NOT IN (SELECT customer_id FROM orders) yields no matches because the subquery includes NULL.

Practical use. Identify inactive customers safely.

Operator Meaning
IN Equal to at least one returned value
NOT IN Not equal to any value, with UNKNOWN risk if NULL is present
> ANY (subquery) Greater than at least one returned value
> ALL (subquery) Greater than every returned value
EXISTS / NOT EXISTS At least one row / no rows

ANY and ALL are supported in SQL Server, PostgreSQL and MySQL but not SQLite's quantified-comparison syntax. Empty sets and NULL values matter: comparison with ALL over an empty result is TRUE; ANY over an empty result is FALSE. A rewrite using MIN/MAX is equivalent only under appropriate nonempty and non-null assumptions.

Quantified comparison — greater than at least one Office price

Dialect: PostgreSQL / MySQL / SQL Server.

SQL
SELECT name,price FROM products WHERE price > ANY (SELECT price FROM products WHERE category='Office') ORDER BY product_id;

Expected behavior (illustrative): Laptop (100), Mouse (20), Notebook (10), Monitor (150).

How it works. The price must exceed at least one of the Office prices (5 and 10).

Quantified comparison — greater than all Office prices

Dialect: PostgreSQL / MySQL / SQL Server.

SQL
SELECT name, price FROM products WHERE price > ALL (SELECT price FROM products WHERE category='Office') ORDER BY product_id;

Expected behavior (illustrative): Laptop (100), Mouse (20), Monitor (150).

How it works. The largest Office price is 10; every returned product exceeds both Office prices.

Subqueries also work in DML. Example: UPDATE orders SET status='Reviewed' WHERE customer_id IN (SELECT customer_id FROM customers WHERE points>=800) AND status='Completed'; Preview and run on a copy; the same predicate can be used for a DELETE when that is the intended action.

Common mistakes. Using = with a multirow subquery; forgetting correlation conditions; NOT IN with NULL; expecting correlated subqueries to always be slower; neglecting to qualify ambiguous columns.

Exercise. Find employees whose salary is above the average of their own department.

Solution

SQL
SELECT e.name,e.salary FROM employees e
WHERE e.salary>(SELECT AVG(i.salary) FROM employees i WHERE i.department_id=e.department_id)
ORDER BY e.employee_id;

Output (SQLite practice data):

name salary
Alice 90000
Dan 60000

How it works. The inner aggregate compares each person with their own department, not the company average.

15. Common table expressions and recursion

A common table expression (CTE) names an intermediate query result for use in one statement. It is often easier to read than several nested subqueries. Define multiple CTEs separated by commas; later CTEs can reference earlier ones. A CTE can declare its output column names. It is not a persistent table, and materialization is an optimizer/dialect decision rather than a guarantee.

SQL
WITH first_step AS (...),
     second_step AS (SELECT ... FROM first_step)
SELECT ... FROM second_step;

The ellipses are syntax placeholders. In SQL Server, terminate the previous statement with a semicolon before WITH. SQL Server does not use the RECURSIVE keyword; PostgreSQL, MySQL and SQLite use WITH RECURSIVE for recursive definitions.

Chained CTEs — sales and segments

SQL
WITH completed AS (
 SELECT customer_id,amount FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
), totals AS (
 SELECT customer_id,SUM(amount) AS revenue FROM completed GROUP BY customer_id
)
SELECT c.name,t.revenue FROM totals t JOIN customers c ON c.customer_id=t.customer_id
WHERE t.revenue>=100 ORDER BY t.revenue DESC;

Output (SQLite practice data):

name revenue
Ada 200
Cleo 150
Ben 100

How it works. Each named stage has one purpose: filter, aggregate, enrich.

Practical use. Build a readable multi-stage business query.

Recursive CTE — generate numbers

SQL
WITH RECURSIVE numbers(n) AS (
 SELECT 1
 UNION ALL
 SELECT n+1 FROM numbers WHERE n<5
)
SELECT n FROM numbers ORDER BY n;

Output (SQLite practice data):

n
1
2
3
4
5

How it works. The anchor emits 1; the recursive member consumes the previous level until the condition stops producing rows.

Practical use. Build small sequence datasets.

Employee hierarchy

SQL
WITH RECURSIVE hierarchy(employee_id,name,level) AS (
 SELECT employee_id,name,0 FROM employees WHERE manager_id IS NULL
 UNION ALL
 SELECT e.employee_id,e.name,h.level+1
 FROM employees e JOIN hierarchy h ON e.manager_id=h.employee_id
 WHERE h.level<10
)
SELECT * FROM hierarchy ORDER BY level,employee_id;

Output (SQLite practice data):

employee_id name level
1 Alice 0
4 Dan 0
6 Finn 0
2 Bob 1
3 Cara 1
5 Eva 1
7 Gina 1

How it works. Anchor selects roots; recursive member finds direct reports of the prior level. Depth guard limits recursion, but a robust general graph traversal also needs cycle detection.

Practical use. Map organizational hierarchy.

Common mistakes. Trying to query a CTE in a later independent statement; assuming a CTE is stored on disk or always faster; using recursion without a termination condition; referencing CTEs out of order.

Exercise. Use two CTEs to count completed orders per customer and retain counts at least 2.

Solution

SQL
WITH completed AS (SELECT customer_id FROM orders WHERE status='Completed' AND customer_id IS NOT NULL),
counts AS (SELECT customer_id,COUNT(*) AS n FROM completed GROUP BY customer_id)
SELECT c.name,counts.n FROM counts JOIN customers c ON c.customer_id=counts.customer_id
WHERE counts.n>=2 ORDER BY c.customer_id;

Output (SQLite practice data):

name n
Ada 2
Ben 2

How it works. The first step filters, the second groups, the final step enriches and filters.

Part IV — Data Transformation

SQL is not only a query language for retrieving data. Row-level functions prepare data for reporting, analysis and feature engineering.

16. String functions and regular expressions

Text functions transform a value without necessarily changing its stored representation. Use them to clean names, standardize codes and extract useful features. Function names and index positions differ between languages and engines; SQL substring positions are generally one-based.

Operation SQLite PostgreSQL / MySQL / SQL Server notes
Length LENGTH(s) PG/MySQL LENGTH; MySQL CHAR_LENGTH counts characters; T-SQL LEN excludes trailing spaces
Upper/lower UPPER, LOWER Common
Strip spaces TRIM, LTRIM, RTRIM Common, optional trim syntax differs
Substring SUBSTR(s,2,3) SUBSTRING(s,2,3) widely available
Prefix/suffix SUBSTR(s,1,n) / SUBSTR(s,-n) LEFT(s,n) / RIGHT(s,n)
Replace REPLACE(s,a,b) Common
Search position INSTR(s,pattern) MySQL LOCATE, T-SQL CHARINDEX, PG POSITION
Concatenate a || b or recent SQLite CONCAT PG ||/CONCAT, MySQL CONCAT, T-SQL CONCAT

CONCAT and concatenation operators differ in how they treat NULL. Check the dialect before assuming an unknown component becomes an empty string.

Clean and split text

SQL
WITH raw(label) AS (SELECT '  Ada-Smith  ')
SELECT TRIM(label) AS clean, UPPER(TRIM(label)) AS uppercase,
 LENGTH(label) AS raw_length, LENGTH(TRIM(label)) AS clean_length,
 REPLACE(TRIM(label),'-',' ') AS standardized,
 SUBSTR(TRIM(label),1,3) AS prefix,
 INSTR(TRIM(label),'-') AS dash_position FROM raw;

Output (SQLite practice data):

clean uppercase raw_length clean_length standardized prefix dash_position
Ada-Smith ADA-SMITH 13 9 Ada Smith Ada 4

How it works. TRIM removes the surrounding spaces; nested functions act on the cleaned value.

Practical use. Standardize names imported from spreadsheets.

Build a customer display label

SQL
SELECT name || ' (' || COALESCE(country,'Unknown') || ')' AS label FROM customers ORDER BY customer_id;

Output (SQLite practice data):

label
Ada (USA)
Ben (UK)
Cleo (USA)
Dina (Germany)
Eli (Unknown)

How it works. The NULL country is explicitly replaced before concatenation.

Practical use. Build readable labels for reports.

Regular expressions. LIKE supports % and _; regular expressions offer anchors, alternatives and character classes.

Pattern Meaning
smith Contains smith
^A Starts with A
son$ Ends with son
smith|jones Either alternative
[ae] One of the listed characters
[a-h] One character in the range
e[ru] er or eu

MySQL uses REGEXP / REGEXP_LIKE; PostgreSQL uses ~ (case sensitive) or ~* (case insensitive). SQLite REGEXP requires a user-supplied implementation. SQL Server's regex capabilities depend on version; simple LIKE patterns remain portable. Regex flavor and collation can change results.

Match either A or B at the beginning

Dialect: MySQL.

SQL
SELECT name FROM customers WHERE name REGEXP '^[AB]' ORDER BY customer_id;

Expected behavior (illustrative): Ada, Ben.

How it works. The anchor starts matching at the first character; the character class allows either letter.

Common mistakes. Confusing LIKE and regex wildcards; trimming after comparison rather than before; using byte length as character count; assuming normalization fixes every spelling difference.

Exercise. Return the first three characters of each product name in lowercase.

Solution

SQL
SELECT name, LOWER(SUBSTR(name,1,3)) AS prefix FROM products ORDER BY product_id;

Output (SQLite practice data):

name prefix
Laptop lap
Mouse mou
Notebook not
Pen pen
Monitor mon

How it works. Extract first, then lowercase. SUBSTR is SQLite syntax.

17. Numeric functions and calculations

Arithmetic is a row-level transformation. Use +, -, *, / and modulo (% or MOD by dialect). Multiplication and division bind before addition and subtraction; parentheses make intent clear. SQL engines differ in integer division and numeric result types. With integer inputs, 5/2 can yield 2 rather than 2.5; cast or use a decimal operand. ROUND controls displayed precision, ABS returns magnitude. Round at the correct stage: rounding each line before summing can produce a different total from rounding the sum.

Calculate quantity × unit price

SQL
SELECT order_id,product_id,quantity,unit_price,
 quantity*unit_price AS line_total FROM order_items
WHERE order_id=101 ORDER BY product_id;

Output (SQLite practice data):

order_id product_id quantity unit_price line_total
101 10 1 100 100
101 11 1 20 20

How it works. Each row produces a calculated line total.

Practical use. Build a revenue feature at line grain.

Division and rounding

SQL
SELECT 5/2 AS integer_division, 5.0/2 AS decimal_division, ROUND(10.0/3,2) AS rounded, ABS(-12) AS magnitude, 17%5 AS remainder;

Output (SQLite practice data):

integer_division decimal_division rounded magnitude remainder
2 2.5 3.33 12 2

How it works. SQLite integer division truncates; one real operand changes the result.

Practical use. Compute ratios and differences carefully.

Percentage of original price

SQL
SELECT name, price, ROUND(price*0.15,2) AS discount, ROUND(price*(1-0.15),2) AS final_price FROM products ORDER BY product_id;

Output (SQLite practice data):

name price discount final_price
Laptop 100 15.0 85.0
Mouse 20 3.0 17.0
Notebook 10 1.5 8.5
Pen 5 0.75 4.25
Monitor 150 22.5 127.5

How it works. The discount is 15% of the price, not a fixed subtraction.

Practical use. Compare pricing scenarios.

Common mistakes. Integer division in ratios; mixing approximate and exact amounts; ignoring division by zero; rounding away important precision too early.

Exercise. Calculate each line amount including a hypothetical 10% surcharge for order 105.

Solution

SQL
SELECT product_id,quantity*unit_price AS base, ROUND(quantity*unit_price*1.1,2) AS with_surcharge FROM order_items WHERE order_id=105 ORDER BY product_id;

Output (SQLite practice data):

product_id base with_surcharge
10 100 110.0
12 50 55.0

How it works. Multiplication occurs at order-item grain.

18. Date and time functions

Dates allow time-based filters, durations and reporting periods. Store date/time values using the appropriate engine types, not arbitrary formatted text. The SQLite practice dates use ISO 8601 YYYY-MM-DD text so date functions and chronological comparison work here. CURRENT_DATE gives today's date and CURRENT_TIMESTAMP a current timestamp; exact time-zone/transaction semantics differ. Use fixed dates in examples for reproducibility.

Task SQLite MySQL PostgreSQL SQL Server
Current date date('now') CURRENT_DATE() CURRENT_DATE CAST(GETDATE() AS date)
Current time time('now') CURRENT_TIME() CURRENT_TIME CAST(GETDATE() AS time)
Timestamp datetime('now') NOW() CURRENT_TIMESTAMP GETDATE()
Extract year strftime('%Y',d) YEAR(d) EXTRACT(YEAR FROM d) YEAR(d) / DATEPART(year,d)
Month start date(d,'start of month') date functions / DATE_FORMAT date_trunc('month',d) DATETRUNC(month,d) (2022+)
Month end date(d,'start of month','+1 month','-1 day') LAST_DAY(d) month start + interval EOMONTH(d)
Add days date(d,'+7 days') DATE_ADD(d,INTERVAL 7 DAY) d + INTERVAL '7 days' DATEADD(day,7,d)
Days between julianday(b)-julianday(a) DATEDIFF(b,a) b-a for dates DATEDIFF(day,a,b)
Format strftime('%Y-%m',d) DATE_FORMAT(d,'%Y-%m') TO_CHAR(d,'YYYY-MM') FORMAT(d,'yyyy-MM')

DATENAME in SQL Server returns a date part's name, such as month. CAST, CONVERT and FORMAT serve different tasks: converting types is different from formatting text for display. ISDATE tests convertibility to supported date/time values under SQL Server rules; do not assume it validates every business date format. MySQL STR_TO_DATE parses a specified pattern. PostgreSQL AT TIME ZONE converts between timestamp interpretations; the direction depends on the input type. Use a named zone where daylight-saving rules matter. Date addition must use calendar functions or intervals, not integer arithmetic on encoded dates.

Date extraction and calendar calculations

SQL
SELECT order_id,order_date,strftime('%Y-%m',order_date) AS month,
 date(order_date,'+7 days') AS due_date,
 date(order_date,'start of month','+1 month','-1 day') AS month_end
FROM orders WHERE order_id IN (101,103,105) ORDER BY order_id;

Output (SQLite practice data):

order_id order_date month due_date month_end
101 2025-01-10 2025-01 2025-01-17 2025-01-31
103 2025-02-05 2025-02 2025-02-12 2025-02-28
105 2025-03-01 2025-03 2025-03-08 2025-03-31

How it works. The functions extract the month and perform calendar-aware arithmetic.

Practical use. Calculate delivery dates or reporting periods.

Half-open date range

SQL
SELECT order_id,order_date,amount FROM orders WHERE order_date >= '2025-02-01' AND order_date < '2025-03-01' ORDER BY order_id;

Output (SQLite practice data):

order_id order_date amount
103 2025-02-05 80
104 2025-02-11 50

How it works. All February dates qualify; the next month is excluded. With timestamps, this also avoids excluding later times on the final day.

Practical use. Filter monthly transactions.

Parse a date string

Dialect: MySQL.

SQL
SELECT STR_TO_DATE('02/11/2025','%m/%d/%Y') AS parsed_date;

Expected behavior (illustrative): 2025-02-11.

How it works. Explicitly specifies the source date format instead of relying on implicit conversion.

Common mistakes. Hardcoding the year when asking for current year; grouping by month number without year; treating DATEDIFF as elapsed seconds in all cases; ignoring time zones and ambiguous formats; wrapping indexed dates in functions unnecessarily.

Exercise. Summarize completed revenue by year-month.

Solution

SQL
SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
FROM orders WHERE status='Completed'
GROUP BY strftime('%Y-%m',order_date) ORDER BY month;

Output (SQLite practice data):

month revenue
2025-01 160
2025-02 80
2025-03 230

How it works. Group on a year-month key, not month alone. SQLite formatting syntax.

19. NULL handling and type conversion

NULL means absent, unknown or inapplicable; it is not 0, an empty string, or spaces. COALESCE(a,b,c) chooses the first non-null expression; SQL Server ISNULL(a,b) replaces NULL but has different type rules; MySQL ISNULL(x) is a predicate, not the same function. NULLIF(a,b) returns NULL when the values compare equal. Combine TRIM and NULLIF to standardize blank strings only when blank truly means missing.

Expression Result
COALESCE(NULL,10,20) 10
NULLIF(10,10) NULL
NULLIF(10,20) 10
COALESCE(NULLIF(TRIM(' '),''),'Unknown') Unknown
amount / NULLIF(quantity,0) NULL when quantity is zero

Do not blindly impute a missing salary as zero: that changes the meaning of an average. If a missing value truly represents no activity, a zero after a left join can be appropriate. When joining on nullable keys, NULL does not equal NULL using ordinary equality; replacing both NULL keys with a sentinel can cause false matches.

CAST(expression AS type) is widely supported. SQL Server CONVERT(type,expression[,style]) handles conversions and formats; its safe conversion alternatives can be useful when checking messy data. PostgreSQL supports expression::type. SQLite's permissive conversion can turn invalid numeric text into 0, unlike stricter engines. Validate input before converting. A query result can also be sorted by a CASE expression to explicitly position NULLs.

Normalize blank and missing emails

SQL
SELECT name,email,COALESCE(NULLIF(TRIM(email),''),'Missing') AS clean_email,
 CASE WHEN NULLIF(TRIM(email),'') IS NULL THEN 1 ELSE 0 END AS missing_flag
FROM customers ORDER BY customer_id;

Output (SQLite practice data):

name email clean_email missing_flag
Ada ada@example.com ada@example.com 0
Ben NULL Missing 1
Cleo cleo@example.com cleo@example.com 0
Dina Missing 1
Eli eli@example.com eli@example.com 0

How it works. Blank and NULL are mapped to a display label, with a separate flag preserving information about missingness.

Practical use. Audit contact-data completeness.

Prevent division by zero

SQL
SELECT 100.0/NULLIF(0,0) AS undefined_ratio,100.0/NULLIF(4,0) AS valid_ratio,CAST('42' AS INTEGER) AS parsed_integer;

Output (SQLite practice data):

undefined_ratio valid_ratio parsed_integer
NULL 25.0 42

How it works. The denominator becomes NULL instead of zero; the ratio remains undefined.

Practical use. Build safe KPI calculations.

Compare missing and filled counts

SQL
SELECT COUNT(*) AS total,COUNT(email) AS non_null,COUNT(NULLIF(TRIM(email),'')) AS usable FROM customers;

Output (SQLite practice data):

total non_null usable
5 4 3

How it works. COUNT(email) includes empty strings; the cleaned expression excludes them.

Practical use. Measure data quality before imputation.

Common mistakes. Comparing NULL with =; replacing unknown values with 0 without business justification; assuming blank and NULL mean the same thing; relying on implicit type conversions; dividing by zero.

Exercise. Return all employee salaries, unknown salaries last and highest known salaries first.

Solution

SQL
SELECT name,salary FROM employees ORDER BY CASE WHEN salary IS NULL THEN 1 ELSE 0 END,salary DESC,employee_id;

Output (SQLite practice data):

name salary
Alice 90000
Bob 70000
Cara 70000
Dan 60000
Finn 55000
Eva 50000
Gina NULL

How it works. Sort by a missingness flag before salary, independent of default NULL ordering.

20. CASE expressions and data cleaning

CASE is SQL's conditional expression. A searched CASE evaluates predicates in order and returns the first matching result; simple CASE compares a single expression to candidate values. If no branch matches and ELSE is absent, the result is NULL. CASE can appear in SELECT, ORDER BY, aggregations and other expression contexts. It returns a value, not a procedural statement.

SQL
CASE WHEN condition_1 THEN result_1
     WHEN condition_2 THEN result_2
     ELSE fallback END

Arrange thresholds carefully, e.g. highest to lowest. For cleaning: stage a copy of raw data, inspect duplicates, standardize text and types, handle missing data using domain rules, remove unusable records if justified, and validate. Never overwrite the only source. Deduplication requires a business key and a deterministic rule, not just SELECT DISTINCT.

Customer segmentation

SQL
SELECT name,points,
 CASE WHEN points IS NULL THEN 'Unknown'
      WHEN points>=1000 THEN 'Gold'
      WHEN points>=500 THEN 'Silver'
      ELSE 'Bronze' END AS segment
FROM customers ORDER BY customer_id;

Output (SQLite practice data):

name points segment
Ada 1200 Gold
Ben 400 Bronze
Cleo 800 Silver
Dina 0 Bronze
Eli NULL Unknown

How it works. NULL is handled explicitly before thresholds.

Practical use. Convert numeric values into business categories.

Simple CASE — map a known category

SQL
SELECT order_id,status,CASE status WHEN 'Completed' THEN 'Recognized' WHEN 'Pending' THEN 'Open' ELSE 'Excluded' END AS report_status FROM orders ORDER BY order_id;

Output (SQLite practice data):

order_id status report_status
101 Completed Recognized
102 Completed Recognized
103 Completed Recognized
104 Cancelled Excluded
105 Completed Recognized
106 Completed Recognized
107 Completed Recognized
108 Pending Open

How it works. Simple CASE compares one expression against each listed value.

Practical use. Map operational status codes to reporting labels.

Simple CASE and conditional aggregation

SQL
SELECT SUM(CASE WHEN status='Completed' THEN amount ELSE 0 END) AS completed,
 SUM(CASE WHEN status='Cancelled' THEN amount ELSE 0 END) AS cancelled,
 SUM(CASE WHEN status='Pending' THEN amount ELSE 0 END) AS pending FROM orders;

Output (SQLite practice data):

completed cancelled pending
470 50 100

How it works. Each order contributes to the corresponding total.

Practical use. Produce multiple KPI columns in one scan.

SQL
CREATE TABLE raw_contacts(row_id INT,customer_id INT,email TEXT,updated_at TEXT);
INSERT INTO raw_contacts VALUES(1,1,' Ada@Example.com ','2025-01-01'),(2,1,'ada@example.com','2025-02-01'),(3,2,'  ','2025-01-05'),(4,3,NULL,'2025-01-07');

Standardize and identify duplicates

SQL
WITH cleaned AS (
 SELECT row_id,customer_id,NULLIF(LOWER(TRIM(email)),'') AS email,updated_at FROM raw_contacts
), ranked AS (
 SELECT *,ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY updated_at DESC,row_id DESC) AS rn FROM cleaned
)
SELECT customer_id,email,updated_at FROM ranked WHERE rn=1 ORDER BY customer_id;

Output (SQLite practice data):

customer_id email updated_at
1 ada@example.com 2025-02-01
2 NULL 2025-01-05
3 NULL 2025-01-07

How it works. The staging query normalizes email and retains the latest row for each customer. Window functions are explained in Part V.

Practical use. Create a reliable clean layer from duplicate imports.

A MySQL cleaning workflow can use CREATE TABLE staging LIKE raw_table; INSERT INTO staging SELECT * FROM raw_table; to preserve more structure than CTAS. Identify duplicate keys with ROW_NUMBER, create a second staging table including row number if needed, delete where rn > 1, then drop the helper column. MySQL cannot directly delete from every CTE result. To fill missing industry labels from known rows for the same company, first check that company-to-industry is unambiguous; use an update join or correlated lookup only when the known label is valid. Convert date strings with STR_TO_DATE before altering the column type. Reject or retain rows with missing metrics according to downstream requirements.

Common mistakes. Wrong CASE order; silently grouping NULL as Bronze; deleting duplicates using an incomplete key; filling every missing numeric field with zero; standardizing categories without checking meaning.

Exercise. Classify order amounts: at least 100 High, at least 50 Medium, otherwise Low.

Solution

SQL
SELECT order_id,amount,CASE WHEN amount>=100 THEN 'High' WHEN amount>=50 THEN 'Medium' ELSE 'Low' END AS band
FROM orders ORDER BY order_id;

Output (SQLite practice data):

order_id amount band
101 120 High
102 40 Low
103 80 Medium
104 50 Medium
105 150 High
106 60 Medium
107 20 Low
108 100 High

How it works. Highest threshold first; ELSE handles all remaining known amounts. If amounts can be NULL, add a distinct Unknown branch.

Part V — Advanced Analytics

Window functions preserve row detail while calculating across related records. Combine them with intermediate query stages to answer questions that ordinary GROUP BY cannot express conveniently.

21. Window functions and frames

GROUP BY reduces rows to groups; window functions normally preserve the rows entering the window stage. A window function calculates a value using a set of related rows. The OVER clause describes that set. It may contain a partition, an ordering and a frame.

SQL
SUM(amount) OVER (
    PARTITION BY customer_id
    ORDER BY order_date, order_id
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
  • PARTITION BY splits the input into independent groups without collapsing them. If absent, the whole result is one partition.
  • Window ORDER BY specifies calculation order, not final display order.
  • ROWS BETWEEN ... AND ... defines physical row offsets relative to the current row. UNBOUNDED PRECEDING starts at the partition's beginning; CURRENT ROW refers to the current row; n PRECEDING and n FOLLOWING set offsets; UNBOUNDED FOLLOWING ends at the partition's final row.
  • RANGE defines a logical range and can include peer rows with the same ordering value. Support for numeric/interval range offsets varies. Many engines default an ordered aggregate window to a peer-inclusive RANGE frame; explicit ROWS is safer for deterministic row-by-row totals.

Window results are not available to WHERE at the same query level; use a CTE or subquery to filter them. Window functions run logically after grouping/HAVING. You cannot generally nest one window function directly inside another at the same query level. Rank and offset functions have different frame rules from aggregate windows.

Compare detail to overall and customer totals

SQL
SELECT order_id,customer_id,amount,
 SUM(amount) OVER() AS all_amount,
 SUM(amount) OVER(PARTITION BY customer_id) AS customer_amount,
 ROUND(AVG(amount) OVER(PARTITION BY customer_id),2) AS customer_avg
FROM orders ORDER BY order_id;

Output (SQLite practice data):

order_id customer_id amount all_amount customer_amount customer_avg
101 1 120 620 300 100.0
102 2 40 620 100 50.0
103 1 80 620 300 100.0
104 3 50 620 200 100.0
105 3 150 620 200 100.0
106 2 60 620 100 50.0
107 NULL 20 620 20 20.0
108 1 100 620 300 100.0

How it works. No rows collapse. Each row includes the overall and per-customer totals. NULL customer IDs form a partition; decide whether that grouping has business meaning.

Practical use. Show transaction context beside every record.

Running total, moving average and extremes

SQL
SELECT order_id,amount,
 SUM(amount) OVER(ORDER BY order_date,order_id ROWS UNBOUNDED PRECEDING) AS running_total,
 ROUND(AVG(amount) OVER(ORDER BY order_date,order_id ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),2) AS moving_avg_3,
 MIN(amount) OVER() AS minimum, MAX(amount) OVER() AS maximum
FROM orders WHERE status='Completed' ORDER BY order_date,order_id;

Output (SQLite practice data):

order_id amount running_total moving_avg_3 minimum maximum
101 120 120 120.0 20 150
102 40 160 80.0 20 150
103 80 240 80.0 20 150
105 150 390 90.0 20 150
106 60 450 96.67 20 150
107 20 470 76.67 20 150

How it works. A running total grows from the first row. The moving frame holds up to three consecutive records, not three calendar months. The first two frames have fewer than three rows.

Practical use. Monitor transaction trends and context.

Visualize a running window over amounts 20, 10, 30, 5, 40:

Current row Running frame Running SUM Trailing 3-row frame Moving SUM
1 20 20 20 20
2 20, 10 30 20, 10 30
3 20, 10, 30 60 20, 10, 30 60
4 20, 10, 30, 5 65 10, 30, 5 45
5 20, 10, 30, 5, 40 105 30, 5, 40 75

To calculate a moving average, divide by the number of non-null values in the frame. A centered frame ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING includes future rows, which would be inappropriate for a historical prediction feature.

Counts and percentage of total

SQL
SELECT order_id,amount,COUNT(*) OVER() AS row_count,
 ROUND(100.0*amount/NULLIF(SUM(amount) OVER(),0),2) AS pct_total
FROM orders WHERE status='Completed' ORDER BY order_id;

Output (SQLite practice data):

order_id amount row_count pct_total
101 120 6 25.53
102 40 6 8.51
103 80 6 17.02
105 150 6 31.91
106 60 6 12.77
107 20 6 4.26

How it works. The denominator is the completed-order total, not the total across excluded statuses. NULLIF prevents division by zero.

Practical use. Measure each transaction contribution.

Common mistakes. Using GROUP BY when detail rows must remain; relying on default frame with ties; confusing window order with output order; using future rows in historical features; treating a row frame as a time interval.

Exercise. Calculate a running total of completed order amounts for each identified customer.

Solution

SQL
SELECT customer_id,order_id,amount,
 SUM(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id ROWS UNBOUNDED PRECEDING) AS running_total
FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
ORDER BY customer_id,order_date,order_id;

Output (SQLite practice data):

customer_id order_id amount running_total
1 101 120 120
1 103 80 200
2 102 40 40
2 106 60 100
3 105 150 150

How it works. Partition restarts the accumulation for every customer.

22. Ranking, segmentation and distributions

Ranking functions assign positions within each ordered partition. Ties determine which function is appropriate. ROW_NUMBER assigns distinct integers; RANK assigns the same rank to peers and skips following ranks; DENSE_RANK has no gaps. NTILE(n) divides ordered rows into up to n buckets, with larger buckets first when the count is not divisible; equal values can be split across buckets. PERCENT_RANK measures relative rank and CUME_DIST the fraction of rows at or before the current peer group.

For n rows, PERCENT_RANK = (RANK - 1)/(n-1) (0 for a single row), and CUME_DIST = number of rows preceding or tied with current row / n. These are relative positions, not the same as assigning a continuous percentile cutoff. The window ordering determines which values count as earlier.

Three ranking functions side by side

SQL
SELECT name,salary,
 ROW_NUMBER() OVER(ORDER BY salary DESC,employee_id) AS row_num,
 RANK() OVER(ORDER BY salary DESC) AS rank_num,
 DENSE_RANK() OVER(ORDER BY salary DESC) AS dense_rank_num
FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC,employee_id;

Output (SQLite practice data):

name salary row_num rank_num dense_rank_num
Alice 90000 1 1 1
Bob 70000 2 2 2
Cara 70000 3 2 2
Dan 60000 4 4 3
Finn 55000 5 5 4
Eva 50000 6 6 5

How it works. Bob and Cara tie in RANK and DENSE_RANK. ROW_NUMBER uses employee_id to break the tie; including that ID in RANK would change the peer groups.

Practical use. Choose exactly N people or top N distinct salary levels.

Quantile buckets and relative distributions

SQL
SELECT name,salary,
 NTILE(3) OVER(ORDER BY salary,employee_id) AS bucket,
 ROUND(PERCENT_RANK() OVER(ORDER BY salary),3) AS percent_rank,
 ROUND(CUME_DIST() OVER(ORDER BY salary),3) AS cume_dist
FROM employees WHERE salary IS NOT NULL ORDER BY salary,employee_id;

Output (SQLite practice data):

name salary bucket percent_rank cume_dist
Eva 50000 1 0.0 0.167
Finn 55000 1 0.2 0.333
Dan 60000 2 0.4 0.5
Bob 70000 2 0.6 0.833
Cara 70000 3 0.6 0.833
Alice 90000 3 1.0 1.0

How it works. Six known salaries produce three buckets of two. Distribution functions retain ties in salary.

Practical use. Divide a population into ordered cohorts.

Top salaries per department

SQL
WITH ranked AS (
 SELECT employee_id,name,department_id,salary,
 DENSE_RANK() OVER(PARTITION BY department_id ORDER BY salary DESC) AS rnk
 FROM employees WHERE salary IS NOT NULL AND department_id IS NOT NULL
)
SELECT department_id,name,salary,rnk FROM ranked WHERE rnk<=2 ORDER BY department_id,rnk,employee_id;

Output (SQLite practice data):

department_id name salary rnk
1 Alice 90000 1
1 Bob 70000 2
1 Cara 70000 2
2 Dan 60000 1
2 Eva 50000 2
3 Finn 55000 1

How it works. Filter in the outer query. DENSE_RANK can return more than two people per department when salaries tie.

Practical use. Find top performers or highest-paid employees by group.

To deduplicate, use ROW_NUMBER partitioned by the intended business key, ordered by a reliable latest timestamp and stable tie-break. Then select rn = 1. A ranking without unique ordering can select different survivors across executions. Use a GROUP BY count check to verify that the resulting business key is unique.

Common mistakes. Using RANK when exactly N rows are required; accidentally breaking ties with a unique ID in RANK; using NTILE as if all equal values stay together; filtering window values in WHERE.

Exercise. Select exactly one highest-paid employee in each nonempty department, breaking salary ties by employee ID.

Solution

SQL
WITH ranked AS (
 SELECT employee_id,name,department_id,salary,
 ROW_NUMBER() OVER(PARTITION BY department_id ORDER BY salary DESC,employee_id) AS rn
 FROM employees WHERE department_id IS NOT NULL AND salary IS NOT NULL
)
SELECT department_id,name,salary FROM ranked WHERE rn=1 ORDER BY department_id;

Output (SQLite practice data):

department_id name salary
1 Alice 90000
2 Dan 60000
3 Finn 55000

How it works. ROW_NUMBER ensures one survivor per partition.

23. LAG, LEAD and time-series analysis

LAG accesses an earlier ordered row; LEAD accesses a later row. FIRST_VALUE and LAST_VALUE access the first and last value in the current frame. Offset functions commonly accept an offset and a default for out-of-range rows. A missing previous row is different from a previous row whose value is NULL.

Time-series analysis often begins by aggregating transactions to a common period. If a month is absent, LAG returns the previous available row, not automatically the previous calendar month. Build a calendar spine and fill absent periods deliberately when the business definition requires it. In forecasting or ML, LEAD and frames containing following rows may leak future data.

Monthly revenue and growth

SQL
WITH monthly AS (
 SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
 FROM orders WHERE status='Completed' GROUP BY strftime('%Y-%m',order_date)
), compared AS (
 SELECT month,revenue,LAG(revenue) OVER(ORDER BY month) AS previous,
 LEAD(revenue) OVER(ORDER BY month) AS next_month
 FROM monthly
)
SELECT month,revenue,previous,next_month,revenue-previous AS change,
 ROUND(100.0*(revenue-previous)/NULLIF(previous,0),2) AS growth_pct
FROM compared ORDER BY month;

Output (SQLite practice data):

month revenue previous next_month change growth_pct
2025-01 160 NULL 80 NULL NULL
2025-02 80 160 230 -80 -50.0
2025-03 230 80 NULL 150 187.5

How it works. The first CTE produces month-level revenue. LAG compares consecutive available months. Growth is undefined for the first row or a zero denominator. LEAD is shown for retrospective analysis only.

Practical use. Compare monthly business performance.

First and last value across each partition

SQL
SELECT order_id,customer_id,amount,
 FIRST_VALUE(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id) AS first_amount,
 LAST_VALUE(amount) OVER(PARTITION BY customer_id ORDER BY order_date,order_id
 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS last_amount
FROM orders WHERE customer_id IS NOT NULL ORDER BY customer_id,order_date,order_id;

Output (SQLite practice data):

order_id customer_id amount first_amount last_amount
101 1 120 120 100
103 1 80 120 100
108 1 100 120 100
102 2 40 40 60
106 2 60 40 60
104 3 50 50 150
105 3 150 50 150

How it works. LAST_VALUE uses the explicit full partition frame. With the default ordered frame, it may return the current row rather than the final partition value.

Practical use. Compare a customer’s first and most recent purchase.

Days since previous completed order

SQL
WITH history AS (
 SELECT customer_id,order_id,order_date,
 LAG(order_date) OVER(PARTITION BY customer_id ORDER BY order_date,order_id) AS prior_date
 FROM orders WHERE status='Completed' AND customer_id IS NOT NULL
)
SELECT customer_id,order_id,prior_date,order_date,
 CAST(julianday(order_date)-julianday(prior_date) AS INTEGER) AS days_since_prior
FROM history ORDER BY customer_id,order_date,order_id;

Output (SQLite practice data):

customer_id order_id prior_date order_date days_since_prior
1 101 NULL 2025-01-10 NULL
1 103 2025-01-10 2025-02-05 26
2 102 NULL 2025-01-20 NULL
2 106 2025-01-20 2025-03-15 54
3 105 NULL 2025-03-01 NULL

How it works. The first purchase has no prior date, and its gap is NULL. The date subtraction uses SQLite julianday.

Practical use. Create a purchase frequency feature.

Common mistakes. Calculating period changes on raw transactions rather than aggregated periods; dividing by zero; treating missing periods as zero without defining the calendar; using LAST_VALUE with an inappropriate frame; leaking future records into predictors.

Exercise. Calculate a trailing two-month average of completed revenue for available months.

Solution

SQL
WITH monthly AS (
 SELECT strftime('%Y-%m',order_date) AS month,SUM(amount) AS revenue
 FROM orders WHERE status='Completed' GROUP BY strftime('%Y-%m',order_date)
)
SELECT month,revenue,ROUND(AVG(revenue) OVER(ORDER BY month ROWS BETWEEN 1 PRECEDING AND CURRENT ROW),2) AS moving_avg
FROM monthly ORDER BY month;

Output (SQLite practice data):

month revenue moving_avg
2025-01 160 160.0
2025-02 80 120.0
2025-03 230 155.0

How it works. The frame contains this and the preceding available monthly row. Add a calendar when months can be absent.

24. Views, temporary tables and intermediate datasets

A named intermediate result helps isolate complexity. Choose its lifetime and storage intentionally.

Technique Lifetime Storage / behavior
Derived table One statement Embedded query; optimizer decides
CTE One statement Named query; optimizer decides
Ordinary view Persistent definition Query abstraction, not a separate saved result
Temporary table Usually session/connection scoped Actual temporary object; can be indexed
CTAS / SELECT INTO Persistent table unless temporary Snapshot of query results at creation

Views can expose only selected columns, provide consistent business definitions, and hide query complexity. Access control still requires appropriate privileges; a view alone is not a complete security boundary. A view can be updated only under engine-specific rules. Materialized views are a separate feature and not treated here. CREATE VIEW, DROP VIEW, and ALTER VIEW or CREATE OR REPLACE VIEW vary by engine. SQLite typically drops and recreates a view to redefine it.

SQLite/PostgreSQL/MySQL support CREATE TABLE copy AS SELECT ...; SQL Server uses SELECT ... INTO copy FROM .... CTAS does not preserve all keys, indexes, defaults or constraints. MySQL CREATE TABLE copy LIKE original creates a structural copy with its own limitations; INSERT INTO copy SELECT ... copies records. Temporary table syntax: SQLite CREATE TEMP TABLE, MySQL/PostgreSQL CREATE TEMPORARY TABLE, SQL Server SELECT ... INTO #temp or CREATE TABLE #temp. Temporary objects may use memory and/or disk; not guaranteed memory-only.

SQL
CREATE VIEW completed_orders AS SELECT order_id,customer_id,order_date,amount FROM orders WHERE status='Completed';

Query a view

SQL
SELECT customer_id,SUM(amount) AS total FROM completed_orders GROUP BY customer_id ORDER BY customer_id;

Output (SQLite practice data):

customer_id total
NULL 20
1 200
2 100
3 150

How it works. The view stores the definition of completed orders and the query aggregates the rows it exposes.

Practical use. Share a standard definition of completed revenue.

SQL Server physical snapshot

Dialect: SQL Server; target table must not exist.

SQL
SELECT order_id,customer_id,amount INTO dbo.completed_snapshot FROM dbo.orders WHERE status='Completed';

Expected behavior (illustrative): Six completed order rows copied into a new table. Source constraints and indexes are not copied automatically.

How it works. SELECT INTO creates a physical table, unlike a view.

SQL
CREATE TEMP TABLE customer_totals AS SELECT customer_id,SUM(amount) AS total FROM orders WHERE status='Completed' AND customer_id IS NOT NULL GROUP BY customer_id;

Use a session-scoped temporary table

SQL
SELECT c.name,t.total FROM customer_totals t JOIN customers c ON c.customer_id=t.customer_id ORDER BY t.total DESC;

Output (SQLite practice data):

name total
Ada 200
Cleo 150
Ben 100

How it works. The temporary table contains a snapshot of the intermediate result. Other independent statements in the same connection can reuse it.

Practical use. Inspect and reuse an intermediate dataset during analysis.

For a permanent archive, explicitly define schema and constraints if they are important. Example: CREATE TABLE archived_orders AS SELECT * FROM orders WHERE order_date < '2025-03-01'; creates a snapshot. Later source updates do not automatically propagate to that table; a normal view would reflect current data when queried.

Common mistakes. Assuming views cache results or always make queries faster; treating a temp table as visible to all sessions; expecting CTAS to preserve indexes; using CTEs as permanent objects; duplicating raw data without a refresh policy.

Exercise. Create a temporary table of completed March orders and sum its revenue.

Run this preparation in a fresh practice connection:

SQL
CREATE TEMP TABLE march_orders AS SELECT * FROM orders WHERE status='Completed' AND order_date>='2025-03-01' AND order_date<'2025-04-01';

Solution

SQL
SELECT COUNT(*) AS orders,SUM(amount) AS revenue FROM march_orders;

Output (SQLite practice data):

orders revenue
3 230

How it works. The temporary table contains March completed orders including anonymous purchases.

Part VI — Advanced Database Operations

Now consider reusable database-side logic and the physical behavior of a query. These chapters use engine-specific syntax where required.

25. Stored procedures and error handling

A stored procedure is a named routine stored by the database and invoked with parameters. It can combine multiple SQL statements, variables, conditions and error handling. This can centralize operations used by multiple callers. It is not the same as a view or a CTE: a procedure can perform writes, return result sets, or orchestrate several steps. Procedural languages and syntax differ substantially; SQLite has no native stored procedures.

SQL Server uses CREATE PROCEDURE, EXEC, DECLARE, SET, IF ... ELSE, and BEGIN ... END. MySQL uses CREATE PROCEDURE, CALL, parameters such as IN, and a client DELIMITER directive when defining a multi-statement body. DELIMITER is a client command, not ordinary SQL. PostgreSQL uses its own procedure/function language and CALL syntax.

The following examples assume the same logical tables have been created in the specified database engine. SQL Server GO separates client batches in SSMS; it is not a T-SQL statement sent directly through a driver.

Reusable customer revenue procedure

Dialect: SQL Server / SSMS.

SQL
CREATE PROCEDURE dbo.CustomerRevenue
    @customer_id INT,
    @status VARCHAR(20) = 'Completed'
AS
BEGIN
    SET NOCOUNT ON;
    SELECT customer_id, SUM(amount) AS revenue
    FROM dbo.orders
    WHERE customer_id = @customer_id AND status = @status
    GROUP BY customer_id;
END;
GO
EXEC dbo.CustomerRevenue @customer_id = 1;

Expected behavior (illustrative): customer_id 1, revenue 200, assuming the practice records have been loaded into dbo.orders.

How it works. Parameters constrain the query, and the default status can be overridden.

Practical use. Expose a stable reporting operation to callers.

Equivalent procedure in MySQL

Dialect: MySQL client supporting DELIMITER.

SQL
DELIMITER //
CREATE PROCEDURE CustomerRevenue(IN p_customer_id INT)
BEGIN
    SELECT customer_id,SUM(amount) AS revenue
    FROM orders WHERE customer_id=p_customer_id AND status='Completed'
    GROUP BY customer_id;
END//
DELIMITER ;
CALL CustomerRevenue(1);

Expected behavior (illustrative): customer_id 1, revenue 200.

How it works. The IN parameter is distinct from the column name. CALL executes the stored body.

Variables and control flow. A SQL Server routine may use DECLARE @total DECIMAL(12,2); SET @total = ...; IF @total > 100 BEGIN ... END ELSE BEGIN ... END. Inside a procedure, validate inputs and return clear failure information. Use TRY/CATCH to handle errors and avoid leaving a transaction open.

Error handling with transaction rollback

Dialect: SQL Server, fresh session without an enclosing transaction.

SQL
BEGIN TRY
    BEGIN TRANSACTION;
    UPDATE dbo.orders SET amount=amount+10 WHERE order_id=101;
    -- Deliberately cause an error for this practice example.
    THROW 50001, 'Practice rollback', 1;
    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    SELECT ERROR_NUMBER() AS error_number, ERROR_MESSAGE() AS error_message,
           ERROR_LINE() AS error_line;
END CATCH;

Expected behavior (illustrative): Error 50001 is returned; order 101 remains 120 after rollback.

How it works. The CATCH block handles the deliberately raised error and rolls back the open transaction. In production choose whether to rethrow errors after logging.

Practical use. Make multi-statement write routines recover cleanly.

Remove a practice procedure when finished with DROP PROCEDURE dbo.CustomerRevenue; (SQL Server) or DROP PROCEDURE IF EXISTS CustomerRevenue; (MySQL). Use a fresh practice schema so the name does not collide with existing routines.

Common mistakes. Mixing dialect syntax; confusing parameter and column names; putting arbitrary dynamic SQL into routines; swallowing errors; leaving transactions open; assuming stored procedures are automatically faster.

Exercise. Write a procedure that lists employees from a requested department.

Solution

Dialect: SQL Server / SSMS.

SQL
CREATE PROCEDURE dbo.EmployeesByDepartment @department_id INT
AS
BEGIN
    SET NOCOUNT ON;
    SELECT employee_id,name,salary FROM dbo.employees
    WHERE department_id=@department_id ORDER BY employee_id;
END;
GO
EXEC dbo.EmployeesByDepartment @department_id=2;

Expected behavior (illustrative): Dan (60000) and Eva (50000).

26. Triggers and scheduled events

A trigger runs automatically in response to a database event. It can enforce a rule, maintain derived data, or record an audit trail. Unlike a procedure, it is not explicitly called by the application. Keep triggers focused: they add hidden work to the original write and can complicate debugging.

Operation OLD values NEW values
INSERT unavailable available
UPDATE available available
DELETE available unavailable

MySQL and SQLite use row-level OLD/NEW in trigger bodies. MySQL supports BEFORE and AFTER triggers. SQL Server DML triggers run per statement and use inserted and deleted pseudo-tables, which can contain many rows. Never assume a statement affects only one row. SQL Server supports AFTER and INSTEAD OF triggers, not MySQL-style BEFORE syntax.

SQL
CREATE TABLE order_audit(order_id INT,old_status TEXT,new_status TEXT);
CREATE TRIGGER audit_order_status AFTER UPDATE OF status ON orders
FOR EACH ROW WHEN OLD.status<>NEW.status
BEGIN
    INSERT INTO order_audit VALUES(NEW.order_id,OLD.status,NEW.status);
END;
UPDATE orders SET status='Completed' WHERE order_id=108;

Inspect the audit trail

SQL
SELECT * FROM order_audit;

Output (SQLite practice data):

order_id old_status new_status
108 Pending Completed

How it works. The update causes an automatic insertion into order_audit. This example runs on a disposable practice database.

Practical use. Record changes for operational diagnostics.

Set-based audit trigger

Dialect: SQL Server / SSMS, disposable practice schema.

SQL
CREATE TABLE dbo.order_audit (
    order_id INT, old_status VARCHAR(20), new_status VARCHAR(20)
);
GO
CREATE TRIGGER dbo.audit_order_status ON dbo.orders
AFTER UPDATE AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO dbo.order_audit(order_id,old_status,new_status)
    SELECT i.order_id,d.status,i.status
    FROM inserted i JOIN deleted d ON i.order_id=d.order_id
    WHERE i.status<>d.status;
END;
GO
UPDATE dbo.orders SET status='Completed' WHERE order_id=108;

Expected behavior (illustrative): One audit record: 108, Pending, Completed. Multiple changed rows would generate multiple audit rows.

How it works. The inserted and deleted sets provide before-and-after values, and the join matches the same key.

A MySQL BEFORE trigger can set a derived annual salary using SET NEW.salary = NEW.hourly_pay * 2080; when the schema contains both fields and that annualization rule is valid. AFTER INSERT/DELETE/UPDATE can adjust a salary-expense summary by +NEW.salary, −OLD.salary, or NEW.salary−OLD.salary. Such derived totals require careful handling of NULL, concurrency and corrections; a query may be simpler than storing a redundant value.

Scheduled events (MySQL). Events run on a time schedule rather than responding to row writes. For example, a periodic cleanup of a disposable staging table can be written as follows. The event scheduler must be enabled and the user must have appropriate privileges; do not activate an event until the predicate and retention policy are reviewed.

SQL
CREATE EVENT cleanup_demo_stage
ON SCHEDULE EVERY 1 DAY
DO DELETE FROM demo_stage
   WHERE created_at < CURRENT_TIMESTAMP - INTERVAL 30 DAY;
-- Assumes demo_stage exists; illustrative MySQL scheduled operation.
-- DROP EVENT cleanup_demo_stage;

Expected: once per scheduled execution, rows older than the chosen retention period are deleted from the demonstration staging table. Use SHOW EVENTS / SHOW TRIGGERS and DROP EVENT / DROP TRIGGER to inspect or remove practice objects in MySQL. An external scheduler is another option in systems without this feature.

Common mistakes. Writing single-row SQL Server triggers; forgetting OLD/NEW availability; automatically deleting production data without a reviewed predicate; assuming an event runs when scheduler is disabled; creating recursive or expensive trigger chains.

Exercise. Create an insert audit trigger that logs IDs of new customers on a disposable SQLite database.

Solution

Dialect: SQLite, fresh practice connection.

SQL
CREATE TABLE customer_audit(customer_id INT);
CREATE TRIGGER audit_customer_insert AFTER INSERT ON customers
BEGIN
 INSERT INTO customer_audit VALUES(NEW.customer_id);
END;
INSERT INTO customers(customer_id,name) VALUES(6,'New customer');
SELECT * FROM customer_audit;

Expected behavior (illustrative): One row with customer_id 6.

27. Indexes and storage architecture

An index is an additional access structure that can speed up particular searches, joins and ordering operations at the cost of storage and write maintenance. A rowstore engine stores rows on pages; a heap has no clustered index organizing its rows. B-tree-like structures navigate from upper levels to leaf pages; a leaf entry may contain the row itself or a locator depending on the index type. An optimizer may choose a scan instead of an index seek when many rows qualify.

Text
             root / search keys
                 /       \
        intermediate     intermediate
            /   \              /   \
         leaf  leaf         leaf  leaf

This diagram represents the access structure, not the exact physical pages. SQL Server distinguishes clustered and nonclustered rowstore indexes; clustered index leaf pages contain the table data. A table can have only one clustered index. Nonclustered indexes store keys and row locators (plus optional included columns). Columnstore groups column values and can use compression and batch-mode processing in analytical workloads. Index categories may overlap: a composite index can also be unique or filtered.

Type Appropriate use
Single-column Frequent selective lookups on one column
Composite Frequent combined predicates or useful ordering
Unique Enforce a unique key and support access
Filtered / partial Subset of rows (SQL Server / PostgreSQL / SQLite syntax differs)
Covering Contains the columns needed by a query, avoiding additional row lookups
Clustered (SQL Server) Organize table rowstore data at index leaves
Nonclustered (SQL Server) Additional access path
Columnstore (SQL Server) Large analytical scans and aggregations

A B-tree on (customer_id, order_date) normally supports efficient lookups by customer_id or customer_id plus order_date. Searching by order_date alone may not benefit from a direct leftmost-prefix lookup. Some engines can use other access strategies, such as skip scans, so treat this as a common design principle rather than a universal prohibition. Column order and predicate selectivity matter. Primary/unique keys often have supporting indexes, but a foreign key may need an explicit index depending on the engine.

SQL
CREATE INDEX idx_orders_customer_date ON orders(customer_id,order_date);
SELECT order_id,amount FROM orders
WHERE customer_id=1 AND order_date>='2025-02-01';

Composite index lookup result

SQL
SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01' ORDER BY order_date,order_id;

Output (SQLite practice data):

order_id amount
103 80
108 100

How it works. The index key matches the equality prefix followed by the date range. It does not change which rows are returned.

Practical use. Accelerate customer order-history access when justified by the workload.

SQL Server index examples (illustrative; use separate practice tables and review existing indexes) Purpose
CREATE NONCLUSTERED INDEX idx_orders_date ON dbo.orders(order_date) INCLUDE(amount); Cover a date/amount query
CREATE NONCLUSTERED INDEX idx_completed ON dbo.orders(customer_id) WHERE status='Completed'; Filtered index for a recurring subset
CREATE CLUSTERED INDEX idx_id ON dbo.heap_orders(order_id); Cluster a heap table (requires no existing clustered index)
CREATE COLUMNSTORE INDEX idx_analytics ON dbo.analytics_orders(order_date, amount); Nonclustered columnstore on an analytical table

Inspect indexes with PRAGMA index_list('orders') (SQLite), SHOW INDEXES FROM orders (MySQL), or SQL Server system catalog views. Drop an index with DROP INDEX idx_orders_customer_date in SQLite/PostgreSQL; MySQL ALTER TABLE orders DROP INDEX idx_orders_customer_date; SQL Server DROP INDEX idx_orders_customer_date ON dbo.orders. Avoid redundant or unused indexes, but measure their actual usage and constraints before removing them.

Common mistakes. Indexing every column; ignoring composite order; assuming a seek always wins; using indexes to solve incorrect query grain; dropping unique/constraint-supporting indexes without understanding dependencies.

Exercise. Create an index on product_id for repeated order-item lookups. Inspect the result for product 11.

Run this preparation in a fresh practice connection:

SQL
CREATE INDEX idx_item_product ON order_items(product_id);

Solution

SQL
SELECT order_id,quantity FROM order_items WHERE product_id=11 ORDER BY order_id;

Output (SQLite practice data):

order_id quantity
101 1
102 2
103 4
106 3
107 1

How it works. The existing composite key starts with order_id; a product-leading index provides another access path. Execute CREATE INDEX idx_item_product ON order_items(product_id) before the SELECT in a practice database.

28. Execution plans, optimization and partitioning

SQL is declarative: the optimizer chooses a physical plan using metadata, available indexes and statistics. Logical clause order is a correctness model; the physical plan may push down predicates, reorder joins, select a hash join or scan a table. Inspect real plans instead of assuming how the query ran.

Text
SQL text → parse / bind → optimize using statistics and access paths
                         ↓
                   execution plan
                         ↓
                   physical operators → result
Operator Meaning
Table scan Read table data without a selective index access path
Index scan Read a range or all of an index structure
Index seek Navigate to a key or key range
Nested loops Repeatedly find matching rows for outer input
Hash join Build a hash table on one input and probe with the other
Merge join Match two suitably ordered inputs
Sort Order rows; can consume memory and spill
Aggregate Compute summaries using suitable physical strategy

Actual SQL Server plans include runtime observations; estimated plans do not execute the query. Inspect estimated vs actual rows, operator costs (estimates, not measured timings), scans/seeks, residual filters, lookups, sorts and spills. SSMS can display both plan types. PostgreSQL EXPLAIN shows the estimated plan; EXPLAIN ANALYZE actually runs the query. MySQL EXPLAIN / EXPLAIN ANALYZE have engine-specific output. SQLite uses EXPLAIN QUERY PLAN. Be careful with actual plans for DML because the statement executes.

Plan before an index

SQL
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01';

Output (SQLite practice data):

id parent notused detail
2 0 0 SCAN orders

How it works. SQLite chooses a scan on the baseline with no customer/date index. Plan details and choices are version/data-dependent.

Plan after an index

SQL
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders WHERE customer_id=1 AND order_date>='2025-02-01';

Output (SQLite practice data):

id parent notused detail
3 0 0 SEARCH orders USING INDEX idx_orders_customer_date (customer_id=? AND order_date>?)

How it works. SQLite can now search using the composite index. This is a plan demonstration, not a benchmark; the toy dataset is too small to establish a speedup.

Practical use. Verify that a proposed access path is considered.

Performance workflow. Establish the correct result and a baseline; identify a slow query from measurements; inspect plans and statistics; form a hypothesis; change one factor; retest correctness and performance; monitor regression. Useful SQL Server diagnostics include SET STATISTICS IO ON; SET STATISTICS TIME ON; and the execution plan. Turn diagnostics off after use. Plan caching can reuse earlier compiled plans, but parameter distributions and changing data can affect plan suitability.

Practical guidelines:

  • Select required columns and filter unnecessary rows; avoid applying functions to indexed filter columns when an equivalent range is possible. E.g. order_date >= '2025-02-01' AND order_date < '2025-03-01' rather than extracting the month of every row.
  • Use correct data types and matching join-key types to avoid implicit conversions.
  • Aggregate to the appropriate grain before joining when it avoids unnecessary row expansion. Do not preaggregate if it changes the business result.
  • Prefer UNION ALL when deduplication is not needed, and EXISTS for membership when returning all matching pairs is unnecessary.
  • Avoid unnecessary sorting, DISTINCT, and repeated computations; investigate correlated subqueries, but don't assume their optimizer implementation.
  • Maintain statistics and monitor usage; evaluate fragmentation and page density against the actual workload. SQL Server ALTER INDEX ... REORGANIZE and ... REBUILD and UPDATE STATISTICS are maintenance commands, not a universal fixed weekly rule. Rebuilds consume resources; use evidence before scheduling.
  • SQL Server query hints (e.g. OPTION (HASH JOIN)) can override optimizer choices; use sparingly after measurement, not as a default.

OLTP vs OLAP. Transactional workloads favor reliable small reads/writes and targeted indexes. Analytical workloads often scan and aggregate large datasets and can benefit from column-oriented storage or partitioning. The same design is not optimal for every workload.

Partitioning. Divide a large table into logical segments by a partition key, often a date. Partition pruning/elimination means the engine can skip irrelevant partitions if the predicate and partition layout permit it. Partitioning also assists lifecycle management; it does not guarantee faster queries, nor automatically distribute data across servers. Parallelism and file placement depend on platform and configuration.

Text
orders by date
├─ before 2025
├─ 2025
└─ 2026 onward
Query 2025 range → potentially access only the 2025 partition

SQL Server uses a partition function to define ranges and a partition scheme to map ranges onto filegroups. A partition key is included in the table/index layout as appropriate. Use a disposable database for the following illustrative DDL; ALL TO PRIMARY keeps the example simple, not a recommendation for physical distribution.

SQL
CREATE PARTITION FUNCTION pf_order_date (DATE)
AS RANGE RIGHT FOR VALUES ('2025-01-01','2026-01-01');
CREATE PARTITION SCHEME ps_order_date
AS PARTITION pf_order_date ALL TO ([PRIMARY]);
CREATE TABLE dbo.partitioned_orders (
    order_id INT NOT NULL,
    order_date DATE NOT NULL,
    amount DECIMAL(10,2)
) ON ps_order_date(order_date);
-- Load data, then inspect a plan for the range predicate:
SELECT order_id,amount FROM dbo.partitioned_orders
WHERE order_date>='2025-01-01' AND order_date<'2026-01-01';

Expected behavior: rows with dates in 2025 belong to the middle partition. If rows are loaded and the engine can eliminate partitions, the query need not scan other date ranges. The empty table as created returns no rows; no performance claim is made. PostgreSQL declarative partitioning and MySQL partition syntax are different.

Common mistakes. Optimizing before validating output; interpreting estimated costs as measured latency; testing on unrepresentative data; overindexing; wrapping filter keys in expressions unnecessarily; assuming partitioning or hints always improve performance.

Exercise. Rewrite a query using strftime on the order_date column to use a sargable February date range, then inspect the plan with an index.

Run this preparation in a fresh practice connection:

SQL
CREATE INDEX idx_order_date ON orders(order_date);

Solution

SQL
EXPLAIN QUERY PLAN SELECT order_id,amount FROM orders
WHERE order_date>='2025-02-01' AND order_date<'2025-03-01';

Output (SQLite practice data):

id parent notused detail
3 0 0 SEARCH orders USING INDEX idx_order_date (order_date>? AND order_date<?)

How it works. The range can use the date index. Execute CREATE INDEX idx_order_date ON orders(order_date) in your practice database before inspecting. Confirm equivalent result rows with and without the index.

Part VII — Real-World Applications

Bring the concepts together in data engineering and analysis workflows. The following small projects are intentionally synthetic and can be reproduced without downloading a large dataset.

29. ETL, data engineering and warehousing

Operational databases typically support applications and transactions (OLTP). A data warehouse integrates data from source systems for analytical queries (OLAP). A business may have separate CRM, ERP, sales and other systems; a warehouse can provide a consistent analytical view of the business. A data mart serves a subject area such as sales. Integration requires agreed identifiers, data quality rules, definitions and ownership.

Concept Meaning
ETL Extract, transform, then load prepared data into a target
ELT Extract, load raw data, then transform in the target environment
Full load Replace or ingest a complete source snapshot
Incremental load Process new or changed records since a known boundary
Batch Process a defined collection of records at intervals
Streaming Process continuously arriving events with appropriate latency guarantees
Fact table Stores measurable events at a defined grain
Dimension table Stores descriptive context, such as product or customer
Slowly changing dimension Manages changes to descriptive attributes; overwrite or preserve history according to business needs

A fact's grain answers “what does one row represent?” In a sales model, one row may represent an order line. Dimensions provide context for filtering and grouping that fact. A star schema places a fact at the center of related dimensions. A fact table can contain multiple measures and foreign keys; it need not be a single preaggregated KPI. A snowflake schema separates some dimension attributes into additional related tables.

Text
              dim_customer
                   |
 dim_product — fact_sales — dim_date
                   |
              dim_channel

The schema is conceptual; a small project need not build every dimension. Operational and dimensional models make different tradeoffs: an analytical model may intentionally denormalize descriptions for easier reporting, while operational schemas often reduce duplication to protect updates.

Data architectures include data warehouses (structured analytical data), data lakes (large collections of data in varied formats), lakehouses (lake storage with warehouse-like table and management capabilities), and data mesh (domain-oriented ownership and data products, not simply a storage engine). Warehouse design approaches include Inmon (enterprise warehouse before marts), Kimball (dimensional marts with conformed dimensions), Data Vault (historical integration with raw/business layers), and medallion (progressive refinement of data quality). These are broad descriptions; implementation details vary.

From raw to business-ready: medallion architecture

Text
CRM / ERP / CSV extracts
           ↓ ingest
Bronze — raw records, source metadata, traceability
           ↓ validate, standardize, deduplicate
Silver — cleaned, typed, integrated records
           ↓ apply business logic and dimensional modeling
Gold — business-ready facts, dimensions, KPIs, ML-ready datasets
           ↓
Reports, analytics, models and downstream applications

Bronze preserves the original information; Silver handles cleaning and integration; Gold applies agreed business definitions. Define naming conventions and data grain, document transformations, test each layer, and version-control SQL scripts. A practical miniature demonstration follows. It is a teaching design, not a production-ready warehouse: the raw extract is synthetic, refresh is a full rebuild, and there is no scheduler, incremental merge or production monitoring.

Runnable miniature (SQLite). Here amount_text is deliberately restricted to known decimal strings or blank; general dirty numeric input must be validated before CAST. A duplicate is defined as a repeated source order ID, and the later raw ID wins. This assumption is valid only for this toy extract.

SQL
CREATE TABLE bronze_sales (raw_id INT PRIMARY KEY, source_order_id INT, customer_id INT, amount_text TEXT, status_text TEXT);
INSERT INTO bronze_sales VALUES
 (1,201,1,' 25.00 ',' completed '),
 (2,202,2,'40.00','COMPLETED'),
 (3,202,2,'40.00','COMPLETED'),
 (4,203,3,'15.00','cancelled'),
 (5,204,1,'','completed');
CREATE TABLE silver_sales AS
WITH standardized AS (
 SELECT raw_id,source_order_id,customer_id,
        NULLIF(TRIM(amount_text),'') AS amount_text,
        LOWER(TRIM(status_text)) AS status
 FROM bronze_sales
), dedup AS (
 SELECT *,ROW_NUMBER() OVER(PARTITION BY source_order_id ORDER BY raw_id DESC) AS rn
 FROM standardized
)
SELECT source_order_id,customer_id,CAST(amount_text AS DECIMAL(10,2)) AS amount,status
FROM dedup WHERE rn=1 AND amount_text IS NOT NULL;
CREATE VIEW gold_customer_sales AS
SELECT c.customer_id,c.name,COUNT(s.source_order_id) AS completed_orders,
 COALESCE(SUM(s.amount),0) AS revenue
FROM customers c LEFT JOIN silver_sales s ON c.customer_id=s.customer_id AND s.status='completed'
GROUP BY c.customer_id,c.name;

Inspect the Silver layer

SQL
SELECT * FROM silver_sales ORDER BY source_order_id;

Output (SQLite practice data):

source_order_id customer_id amount status
201 1 25 completed
202 2 40 completed
203 3 15 cancelled

How it works. Five raw records become three clean order records: one duplicate and one blank amount are excluded. The raw records remain available.

Practical use. Check transformation decisions independently of reporting.

Inspect the Gold layer

SQL
SELECT * FROM gold_customer_sales ORDER BY customer_id;

Output (SQLite practice data):

customer_id name completed_orders revenue
1 Ada 1 25
2 Ben 1 40
3 Cleo 0 0
4 Dina 0 0
5 Eli 0 0

How it works. Gold counts completed orders only and retains every customer. Cancelled orders are excluded; zero revenue is appropriate here for no qualifying sale.

Practical use. Provide a customer-level dataset for reporting.

Validate the layers

SQL
SELECT (SELECT COUNT(*) FROM bronze_sales) AS raw_rows,
 (SELECT COUNT(*) FROM silver_sales) AS clean_rows,
 (SELECT COUNT(DISTINCT source_order_id) FROM silver_sales) AS unique_orders,
 (SELECT SUM(amount) FROM silver_sales WHERE status='completed') AS silver_completed,
 (SELECT SUM(revenue) FROM gold_customer_sales) AS gold_revenue;

Output (SQLite practice data):

raw_rows clean_rows unique_orders silver_completed gold_revenue
5 3 3 65 65

How it works. The clean key should be unique, and completed revenue should reconcile between layers. This works because every valid completed source customer is present in the customer dimension.

For incremental loads, define a watermark or change-tracking mechanism; handle late arrivals and corrections; avoid reprocessing duplicates; and decide how deletes are represented. Re-running a load should not silently double-count facts. The illustrative pipeline uses CREATE TABLE and is intentionally executed once in a fresh database. Production refresh procedures must define repeatable load semantics. Slowly changing dimensions can overwrite current attributes (Type 1) or retain versioned historical rows (Type 2); for a historical join, choose the appropriate effective version. Those are design choices, not implemented here.

Import/export and orchestration. SQLite supports CSV import in its shell, MySQL and Workbench offer import tools, SQL Server has bulk load/restore workflows, and PostgreSQL supports COPY/client \copy. In psql, \copy table_name FROM 'local.csv' WITH (FORMAT csv, HEADER true); uses a local client file, whereas server-side COPY requires server-accessible files and permissions. Load into staging with the right column order, delimiter and encoding; inspect row counts and parse failures before promoting records. Avoid mixing a client command with an ordinary SQL driver API.

Common mistakes. Treating all source records as clean; overwriting Bronze; using incompatible facts/grains in one table; double-counting incremental loads; discarding records without an audit rule; expecting architectural labels to replace data validation.

Exercise. Check for duplicate source order keys in the Silver layer.

Solution

SQL
SELECT source_order_id,COUNT(*) AS n FROM silver_sales GROUP BY source_order_id HAVING COUNT(*)>1;

Output (SQLite practice data):

(0 rows; columns: source_order_id, n)

How it works. An empty result is the desired validation outcome. Run the warehouse setup above in a fresh SQLite connection.

30. Practical SQL projects and interview preparation

The point of a project is to answer a well-defined question from raw tables, not to demonstrate as many SQL functions as possible. For each analysis, identify the grain, define the metric, explore the inputs, construct the query incrementally, inspect the output and validate the result. The projects below combine the preceding concepts. All datasets are fictional; no result should be interpreted as a real market statistic.

Project A — Job-market and skill analytics

Business question. Which jobs pay most, which skills are common, and which skills balance demand and compensation? Use a fact table of job postings, company and skill dimensions, and a many-to-many junction linking jobs to skills. The salary is yearly; the data is synthetic. Skills are counted once per job.

SQL
CREATE TABLE company_dim (company_id INT NOT NULL PRIMARY KEY, name TEXT);
CREATE TABLE job_postings_fact (job_id INT NOT NULL PRIMARY KEY,company_id INT REFERENCES company_dim(company_id),job_title TEXT,salary_year_avg DECIMAL(12,2),job_location TEXT,posted_date TEXT);
CREATE TABLE skills_dim (skill_id INT NOT NULL PRIMARY KEY,skill TEXT);
CREATE TABLE skills_job_dim (job_id INT NOT NULL REFERENCES job_postings_fact(job_id),skill_id INT NOT NULL REFERENCES skills_dim(skill_id),PRIMARY KEY(job_id,skill_id));
INSERT INTO company_dim VALUES (1,'Northstar'),(2,'Atlas'),(3,'Orion');
INSERT INTO job_postings_fact VALUES
 (1,1,'Data Analyst',80000,'Remote','2025-01-01'),
 (2,2,'Data Analyst',100000,'Remote','2025-01-02'),
 (3,1,'Data Analyst',60000,'Onsite','2025-01-03'),
 (4,3,'Data Analyst',120000,'Remote','2025-02-01'),
 (5,2,'Data Analyst',NULL,'Remote','2025-02-02'),
 (6,3,'ML Engineer',140000,'Remote','2025-02-03');
INSERT INTO skills_dim VALUES (1,'SQL'),(2,'Python'),(3,'Excel'),(4,'Tableau'),(5,'Spark');
INSERT INTO skills_job_dim VALUES (1,1),(1,3),(2,1),(2,2),(3,1),(3,4),(4,1),(4,2),(4,5),(5,1),(5,4),(6,2),(6,5);

Analysis scope. Restrict to remote Data Analyst postings. Demand counts every eligible posting with the skill; salary averages count only postings with known salaries. A job with multiple skills contributes to each skill's average, not multiple times to the overall job average.

A1. Highest-paying eligible jobs

SQL
SELECT j.job_id,c.name AS company,j.salary_year_avg
FROM job_postings_fact j JOIN company_dim c ON j.company_id=c.company_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL
ORDER BY j.salary_year_avg DESC,j.job_id LIMIT 3;

Output (SQLite practice data):

job_id company salary_year_avg
4 Orion 120000
2 Atlas 100000
1 Northstar 80000

How it works. Filter role and remote location before sorting known salaries.

Practical use. Find top-paying opportunities.

A2. Skills associated with the highest-paying jobs

SQL
WITH top_jobs AS (
 SELECT job_id,salary_year_avg FROM job_postings_fact
 WHERE job_title='Data Analyst' AND job_location='Remote' AND salary_year_avg IS NOT NULL
 ORDER BY salary_year_avg DESC,job_id LIMIT 2
)
SELECT t.job_id,t.salary_year_avg,s.skill FROM top_jobs t
JOIN skills_job_dim sj ON sj.job_id=t.job_id JOIN skills_dim s ON s.skill_id=sj.skill_id
ORDER BY t.salary_year_avg DESC,s.skill;

Output (SQLite practice data):

job_id salary_year_avg skill
4 120000 Python
4 120000 SQL
4 120000 Spark
2 100000 Python
2 100000 SQL

How it works. Select top jobs at job grain first, then expand to skills. Applying LIMIT after the join would select skill rows instead of jobs.

A3. Most in-demand skills

SQL
SELECT s.skill,COUNT(DISTINCT j.job_id) AS demand
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
JOIN skills_dim s ON s.skill_id=sj.skill_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote'
GROUP BY s.skill_id,s.skill ORDER BY demand DESC,s.skill;

Output (SQLite practice data):

skill demand
SQL 4
Python 2
Excel 1
Spark 1
Tableau 1

How it works. Count distinct job IDs per skill, including jobs with missing salary. The junction key prevents repeated job/skill pairs.

A4. Highest average salary by skill

SQL
SELECT s.skill,COUNT(j.salary_year_avg) AS known_salaries,ROUND(AVG(j.salary_year_avg),2) AS avg_salary
FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
JOIN skills_dim s ON s.skill_id=sj.skill_id
WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL
GROUP BY s.skill_id,s.skill ORDER BY avg_salary DESC,s.skill;

Output (SQLite practice data):

skill known_salaries avg_salary
Spark 1 120000.0
Python 2 110000.0
SQL 3 100000.0
Excel 1 80000.0

How it works. The average excludes unknown salaries. Report the sample count so one high-paying posting does not appear more reliable than it is.

A5. Balance demand and salary

SQL
WITH demand AS (
 SELECT sj.skill_id,COUNT(DISTINCT j.job_id) AS demand
 FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
 WHERE j.job_title='Data Analyst' AND j.job_location='Remote' GROUP BY sj.skill_id
), salaries AS (
 SELECT sj.skill_id,AVG(j.salary_year_avg) AS avg_salary,COUNT(j.salary_year_avg) AS n_salary
 FROM job_postings_fact j JOIN skills_job_dim sj ON j.job_id=sj.job_id
 WHERE j.job_title='Data Analyst' AND j.job_location='Remote' AND j.salary_year_avg IS NOT NULL GROUP BY sj.skill_id
)
SELECT s.skill,d.demand,ROUND(a.avg_salary,2) AS avg_salary,a.n_salary
FROM demand d JOIN salaries a ON d.skill_id=a.skill_id JOIN skills_dim s ON s.skill_id=d.skill_id
WHERE d.demand>=2 AND a.n_salary>=2 ORDER BY avg_salary DESC,d.demand DESC,s.skill;

Output (SQLite practice data):

skill demand avg_salary n_salary
Python 2 110000.0 2
SQL 4 100000.0 3

How it works. Demand and known-salary counts have different denominators. The thresholds are illustrative, not an industry recommendation.

Validate: Check for duplicate job IDs, duplicate junction keys, role/location filter consistency and missing salaries. Use larger samples before interpreting salary rankings. A salary associated with a skill does not establish that the skill caused the salary.

Project B — Cleaning and exploratory analysis of company layoffs

Business question. How many reported layoffs occurred by month, industry and company? Data may contain duplicates, blanks, inconsistent names, missing metrics and date text. Do not overwrite raw records or add percentages across companies. The following synthetic data uses ISO dates to keep SQLite examples runnable; if an input uses MM/DD/YYYY, parse it explicitly with the engine’s date conversion functions first.

SQL
CREATE TABLE layoffs_raw(row_id INT PRIMARY KEY,company TEXT,location TEXT,industry TEXT,total_laid_off INT,percentage_laid_off REAL,event_date TEXT,stage TEXT,country TEXT,funds_raised INT);
INSERT INTO layoffs_raw VALUES
 (1,' Atlas ','Berlin','CryptoCurrency',100,0.1,'2025-01-10','Series B','Germany',80),
 (2,'Atlas','Berlin','Crypto',100,0.1,'2025-01-10','Series B','Germany',80),
 (3,'Beacon','New York','',40,0.2,'2025-01-20','Series A','United States.',20),
 (4,'Beacon','New York','Retail',60,0.3,'2025-02-01','Series A','United States',20),
 (5,'Cedar','London','Tech',150,1.0,'2025-02-10','Post IPO','UK',200),
 (6,'Cedar','London','Tech',20,NULL,'2025-03-01','Post IPO','UK',200),
 (7,'Delta','Paris','Retail',NULL,NULL,'2025-03-05','Series C','France',50),
 (8,'Elm','Paris','Retail',50,0.1,'2025-03-09','Series C','France',40);
CREATE TABLE layoffs_clean AS
WITH normalized AS (
 SELECT row_id,TRIM(company) AS company,TRIM(location) AS location,
 CASE WHEN LOWER(TRIM(industry)) LIKE 'crypto%' THEN 'Crypto' ELSE NULLIF(TRIM(industry),'') END AS industry,
 total_laid_off,percentage_laid_off,event_date,stage,RTRIM(TRIM(country),'.') AS country,funds_raised
 FROM layoffs_raw
), ranked AS (
 SELECT *,ROW_NUMBER() OVER(PARTITION BY company,location,industry,total_laid_off,percentage_laid_off,event_date,stage,country,funds_raised ORDER BY row_id) AS rn
 FROM normalized
), dedup AS (SELECT * FROM ranked WHERE rn=1),
 known_industry AS (
 SELECT company,location,MAX(industry) AS industry FROM dedup WHERE industry IS NOT NULL
 GROUP BY company,location HAVING COUNT(DISTINCT industry)=1
)
SELECT d.row_id,d.company,d.location,COALESCE(d.industry,k.industry) AS industry,
 d.total_laid_off,d.percentage_laid_off,d.event_date,d.stage,d.country,d.funds_raised
FROM dedup d LEFT JOIN known_industry k ON d.company=k.company AND d.location=k.location
WHERE d.total_laid_off IS NOT NULL OR d.percentage_laid_off IS NOT NULL;

B1. Inspect cleaned records

SQL
SELECT company,industry,total_laid_off,percentage_laid_off,event_date,country FROM layoffs_clean ORDER BY event_date,company;

Output (SQLite practice data):

company industry total_laid_off percentage_laid_off event_date country
Atlas Crypto 100 0.1 2025-01-10 Germany
Beacon Retail 40 0.2 2025-01-20 United States
Beacon Retail 60 0.3 2025-02-01 United States
Cedar Tech 150 1.0 2025-02-10 UK
Cedar Tech 20 NULL 2025-03-01 UK
Elm Retail 50 0.1 2025-03-09 France

How it works. Standardize before deduplication, rank on all relevant source fields, fill an industry only when company/location has one known industry, and retain rows with at least one metric. The known-industry rule is a business assumption for the synthetic data.

B2. Validate cleaning

SQL
SELECT (SELECT COUNT(*) FROM layoffs_raw) AS raw_rows,
 (SELECT COUNT(*) FROM layoffs_clean) AS clean_rows,
 (SELECT COUNT(*) FROM layoffs_clean WHERE industry IS NULL) AS missing_industry,
 (SELECT SUM(total_laid_off) FROM layoffs_clean) AS reported_total;

Output (SQLite practice data):

raw_rows clean_rows missing_industry reported_total
8 6 0 420

How it works. Eight raw rows become six analytical rows: one duplicate and one unusable record are removed. The total is of known reported counts, not an estimate of all layoffs.

B3. Compare industry and country totals

SQL
SELECT industry,country,SUM(total_laid_off) AS reported_layoffs
FROM layoffs_clean GROUP BY industry,country ORDER BY reported_layoffs DESC,industry,country;

Output (SQLite practice data):

industry country reported_layoffs
Tech UK 170
Crypto Germany 100
Retail United States 100
Retail France 50

How it works. Group by both dimensions. Counts can be summed for distinct events, but percentages require compatible denominators.

B4. Monthly trend and rolling total

SQL
WITH monthly AS (
 SELECT SUBSTR(event_date,1,7) AS month,SUM(total_laid_off) AS monthly_total
 FROM layoffs_clean GROUP BY SUBSTR(event_date,1,7)
)
SELECT month,monthly_total,SUM(monthly_total) OVER(ORDER BY month ROWS UNBOUNDED PRECEDING) AS cumulative
FROM monthly ORDER BY month;

Output (SQLite practice data):

month monthly_total cumulative
2025-01 140 140
2025-02 210 350
2025-03 70 420

How it works. Aggregate event records to month grain, then accumulate monthly totals.

B5. Highest-layoff companies per year

SQL
WITH yearly AS (
 SELECT SUBSTR(event_date,1,4) AS year,company,SUM(total_laid_off) AS total
 FROM layoffs_clean GROUP BY SUBSTR(event_date,1,4),company
), ranked AS (
 SELECT *,DENSE_RANK() OVER(PARTITION BY year ORDER BY total DESC) AS company_rank FROM yearly
)
SELECT year,company,total,company_rank FROM ranked WHERE company_rank<=2 ORDER BY year,company_rank,company;

Output (SQLite practice data):

year company total company_rank
2025 Cedar 170 1
2025 Atlas 100 2
2025 Beacon 100 2

How it works. Aggregate before ranking. Ties can yield more than two companies. In a full EDA, also inspect date range, extremes, 100% layoffs and totals by funding stage and year.

Validate: Confirm that standardized labels reflect the same real category, not merely similar spelling; dates parse correctly; no duplicates remain at the chosen grain; missing total counts are not silently treated as 0. A 100% layoff is a company-level proportion and cannot be added to another company’s percentage. Without employee denominators, a population-wide layoff rate cannot be calculated reliably.

Project C — Build an analytical customer dataset

Business question. At the end of February 2025, create one row per customer with historical completed order count, revenue, average order value, most recent purchase, and a customer segment. This resembles a feature table for analytics or machine learning. The cutoff is exclusive and all features use only earlier observations.

C1. Customer-level snapshot

SQL
WITH historical AS (
 SELECT customer_id,order_date,amount FROM orders
 WHERE status='Completed' AND order_date<'2025-03-01' AND customer_id IS NOT NULL
), aggregated AS (
 SELECT customer_id,COUNT(*) AS purchase_count,SUM(amount) AS revenue,
 AVG(amount) AS avg_order_value,MAX(order_date) AS last_purchase
 FROM historical GROUP BY customer_id
)
SELECT c.customer_id,c.name,COALESCE(a.purchase_count,0) AS purchases,
 COALESCE(a.revenue,0) AS revenue,ROUND(a.avg_order_value,2) AS avg_order_value,
 a.last_purchase,
 CASE WHEN a.customer_id IS NULL THEN 'Inactive' WHEN a.revenue>=100 THEN 'High' ELSE 'Standard' END AS segment
FROM customers c LEFT JOIN aggregated a ON c.customer_id=a.customer_id ORDER BY c.customer_id;

Output (SQLite practice data):

customer_id name purchases revenue avg_order_value last_purchase segment
1 Ada 2 200 100.0 2025-02-05 High
2 Ben 1 40 40.0 2025-01-20 Standard
3 Cleo 0 0 NULL NULL Inactive
4 Dina 0 0 NULL NULL Inactive
5 Eli 0 0 NULL NULL Inactive

How it works. The CTE establishes an as-of cutoff and aggregates before joining, avoiding order-line expansion. No purchases legitimately means count/revenue zero; average and recency remain unknown for those customers.

Practical use. Build a reporting snapshot or an as-of-date ML feature table.

For a real model, dimension attributes such as points must also be available as of the cutoff; avoid using a current customer attribute if it changed after the observation date. Targets must use a distinct future horizon, and feature selection/preprocessing must respect the evaluation split. This is a small applied caveat, not a separate ML course.

Using AI assistance without surrendering correctness

An AI assistant can explain unfamiliar syntax, propose queries, generate synthetic test data, suggest troubleshooting steps, and review a plan. Give it the dialect/version, schema, grain, sample rows, required output, NULL/tie rules and constraints. Ask it to explain the query and identify edge cases. Do not provide real credentials, confidential customer records or other unnecessary sensitive data. Never run generated destructive statements without reviewing the affected rows and transaction behavior. Validate actual outputs and plans independently.

Example prompt: “Use SQL Server syntax. Given orders(order_id, customer_id, amount, status, order_date), return one row per customer with the top two distinct completed order amounts in 2025. Explain how ties and NULL values are handled. Show a CTE, expected output for a small synthetic dataset, and common mistakes. Do not write or delete data.”

The exact requirement “one row per customer with top two distinct amounts” needs either separate output columns or a nested/aggregated representation, not simply two ranked rows. A good assistant should identify that ambiguity rather than invent a result shape.

Common mistakes. Ignoring metric definitions, choosing the wrong grain, silently excluding NULLs, reporting unrepresentative sample findings as real results, letting a join duplicate facts, leaking future data into features, or accepting AI-generated SQL without verification.

Exercise. Interview challenge: return all customers, their number of completed orders, and completed revenue, then rank them by revenue (ties share a dense rank).

Solution

SQL
WITH summary AS (
 SELECT c.customer_id,c.name,COUNT(o.order_id) AS completed_orders,
 COALESCE(SUM(o.amount),0) AS revenue
 FROM customers c LEFT JOIN orders o ON o.customer_id=c.customer_id AND o.status='Completed'
 GROUP BY c.customer_id,c.name
)
SELECT name,completed_orders,revenue,DENSE_RANK() OVER(ORDER BY revenue DESC) AS revenue_rank
FROM summary ORDER BY revenue_rank,customer_id;

Output (SQLite practice data):

name completed_orders revenue revenue_rank
Ada 2 200 1
Cleo 1 150 2
Ben 2 100 3
Dina 0 0 4
Eli 0 0 4

How it works. The outer join keeps inactive customers, GROUP BY establishes the grain, and the window ranks summaries. The final tie-break orders equal ranks deterministically without changing their ranks.

Closing thought: learn to diagnose the query

A professional SQL workflow is less about memorizing the entire language than combining the right tools with a defensible understanding of the data. When a result looks wrong, first ask what a row means and whether a join has changed the grain. When a query is slow, measure and inspect its plan before adding indexes. When changing data, preview the affected rows and use appropriate transactions. When preparing analytical or ML data, define missingness and time cutoffs explicitly.

Requirement Think first about
Retrieve rows/columns SELECT, WHERE, ORDER BY
Summarize records GROUP BY, aggregate functions, HAVING
Combine related tables JOIN, keys, cardinality, grain
Compare datasets UNION, INTERSECT, EXCEPT, anti joins
Break down complexity Subqueries, CTEs, views, temporary tables
Calculate across rows Window partitions, ordering, frames
Improve data quality Staging, text/date/NULL transforms, deterministic deduplication
Persist reliable changes Constraints, transactions, procedures
Improve performance Correct query, measured plan, targeted indexes, partitioning if justified
Build a data product Defined grain, transformations, validation and reproducibility

Start with the baseline tables. Change one query at a time, predict its result before running it, and compare the actual output with the expected output. Once the mechanics become intuitive, practice combining several concepts to solve a real business question. That is how syntax becomes working SQL knowledge.

Scope boundary. This guide concentrates on everyday SQL through advanced analytical and database operations. It introduces transactions, security, dimensional modeling and architecture but does not attempt to be a full database administration manual; advanced isolation/locking, replication, recovery, formal normalization, vendor-specific security and specialized features are deliberately outside its detailed scope. The warehouse pipeline is an explicitly small teaching implementation rather than a complete enterprise warehouse.

← Back to all blogs

Odd

The 97th Percentile Project

How good do you actually need to be to be exceptional?

We often underestimate what it takes to be exceptional while simultaneously overestimating how much we need to accomplish to get there. When we think about financial success, we imagine millionaires and billionaires. When we think about physical fitness, we picture professional athletes. When we think about intelligence, we imagine mathematicians, scientists and people capable of solving extraordinarily complex problems. But what if these are the wrong benchmarks? What if becoming significantly better than most people requires considerably less than we imagine?

This question led me to an idea I call The 97th Percentile Project. The concept is relatively simple: pick almost any measurable area of human achievement and investigate what is actually required to reach the 97th percentile — the top 3%. The objective is not necessarily to become the best in the world. It is to understand how far one needs to go to become exceptional, and whether that distance is shorter than we originally assumed.

The Problem with Extreme Benchmarks

We tend to compare ourselves with people at the extreme end of a distribution. Someone interested in chess might compare themselves with a grandmaster. Someone learning programming might compare themselves with an engineer at Google. Someone interested in running might look at marathon champions. These comparisons can make meaningful achievements seem insignificant.

However, there is an enormous difference between being better than 97% of people and being better than 99.999% of people. Both represent exceptional performance, but the latter may require decades of dedication, extraordinary circumstances, natural ability and considerable sacrifice. The former might be considerably more accessible.

Rather than asking, How can I become the best?, perhaps a more interesting question is: What exactly would it take to become better than 97% of people?

Income: An Interesting Starting Point

Consider income. Do you really need to become a millionaire to be considered financially successful on a global scale? One of the initial benchmarks I wrote down for this project was an annual income of $40,000. Rather than simply looking at the number, I wanted to investigate where it might place someone within the global income distribution.

An annual income of $40,000 translates into approximately:

  • $3,333 per month;
  • $769 per week;
  • $19.23 per hour, assuming a standard 40-hour working week.

Suddenly, what might initially appear to be an ambitious annual income becomes a more understandable hourly target. Whether this income actually places someone in the global top 3% requires reliable data and careful consideration of purchasing power, taxation and household size.

But the larger point remains: our perception of success can change dramatically once we understand the distribution against which we are measuring ourselves. Instead of chasing an abstract idea of wealth, we can identify a specific, measurable financial objective and understand its relative significance.

Beyond Money

What makes this idea particularly interesting is that income is only one possible application. Consider self-defense. You do not necessarily need to become a professional boxer, wrestler or judoka to develop useful defensive capabilities. Learning how to recognize danger, maintain distance, escape threatening situations, remain composed under pressure and develop basic defensive techniques could significantly improve your ability to protect yourself. The question is how much training would be required to place you among the most capable individuals in the general population.

The same concept can be applied to swimming, running, chess, cooking, programming, mathematics, financial literacy or even solving a Rubik's Cube. How fast would you need to run five kilometers? How many languages would you need to speak? How quickly would you need to solve a Rubik's Cube? How much financial knowledge would you need to possess? How proficient would you need to become in programming?

Each question represents a separate investigation into what exceptional competence actually looks like. Some answers might be surprisingly accessible. Others might reveal that reaching the top 3% is much more difficult than anticipated. Both outcomes are valuable.

The Rubik's Cube: When Achievement Opens New Doors

The Rubik's Cube provides a particularly interesting example of this phenomenon. Initially, solving a scrambled cube might appear almost impossible. You might spend several days trying to understand how the pieces move, memorizing algorithms and figuring out why solving one side does not necessarily solve the entire puzzle. Eventually, you solve it.

Your first independent solution might take seven minutes. With practice, seven minutes becomes four, four becomes two, and eventually, you might find yourself consistently solving the cube in under a minute. Each milestone changes your perception of what is possible.

However, continuing to reduce your solving time becomes progressively more demanding. Getting below 30 seconds, then 20 seconds, and eventually 10 seconds may require increasingly sophisticated algorithms, efficient finger movements, pattern recognition, look-ahead techniques and thousands of repetitions. At the extreme end of competitive speedcubing, Chinese competitors such as Yiheng Wang and Xuanyi Geng, who took the first two places in the 3×3 event at the 2025 World Championship, can solve the cube in a matter of seconds.

But is reaching their level necessary? Perhaps solving a Rubik's Cube consistently in under a minute is already a sufficiently meaningful personal achievement. Its exact percentile within the general population may be difficult to establish, but it represents a clearly measurable level of competence.

And this is where something particularly interesting happens. Once you become comfortable with the conventional 3×3 cube, you discover an entirely different world of possibilities that you might not have even considered when you started:

  • Solving a cube blindfolded using memorization techniques.
  • Solving several cubes blindfolded in a single attempt.
  • Solving with one hand.
  • Exploring larger cubes such as the 4×4, 5×5 and 7×7.
  • Learning different puzzles such as the Megaminx, Pyraminx and Square-1.
  • Solving a cube using the fewest possible moves rather than the shortest possible time.

Hungarian speedcuber Marcell Endrey, for example, became the 3×3 blindfolded world champion in 2013, demonstrating that speed is only one dimension of cubing expertise. What initially appeared to be a simple objective — solving a colorful mechanical puzzle — eventually reveals an entire discipline involving mathematics, memory, dexterity, optimization and pattern recognition.

Reaching a reasonable level of competence gives you the opportunity to decide which of these directions is worth exploring. You could not have made that decision intelligently before you started.

Sometimes, the greatest benefit of achieving a goal is discovering the opportunities that were previously invisible to you.

The Economics of Learning

Perhaps the most interesting aspect of the project is the relationship between effort and achievement. Learning is rarely linear. The first few months of studying a subject can produce enormous improvements, while subsequent improvements may become increasingly difficult.

Imagine spending 100 hours learning a new skill. You might progress from knowing virtually nothing to being reasonably competent. Another 100 hours might substantially improve your performance. However, moving from advanced competence to professional mastery could require thousands of additional hours.

This is the concept of diminishing returns. The closer you get to the extreme end of performance, the more expensive each additional improvement may become in terms of time, energy and resources.

This raises an interesting question about how we allocate our limited time. Would it be more valuable to spend thousands of hours becoming extraordinarily good at one particular activity, or to distribute some of those hours across several different disciplines?

There is no universally correct answer. A professional surgeon, scientist or athlete may have excellent reasons to pursue extreme specialization. But outside one's primary profession, developing broad competence across multiple areas could be a remarkably valuable investment. The objective is not to avoid hard work. It is to understand where hard work produces the greatest returns.

Language Learning: The Distance Between Fluency and Mastery

Language learning illustrates the same principle. When you begin learning a foreign language, your initial ambitions are relatively straightforward: introduce yourself, understand simple conversations, ask questions and express basic ideas.

Eventually, you become capable of reading books, watching movies, writing professional emails and participating in complex discussions. You might even reach a level of proficiency approaching C2, the highest level of the Common European Framework of Reference for Languages. At this stage, the language is no longer simply a subject you study. It becomes a tool you can use to study other subjects, communicate with people, pursue professional opportunities and explore different cultures.

But there is still another level. Understanding regional accents, recognizing subtle cultural references, interpreting sarcasm, using idiomatic expressions naturally, appreciating sophisticated humor and understanding the emotional implications of particular words may require years of additional exposure. Even native speakers do not necessarily possess all these capabilities. The distinction between being highly proficient in a language and mastering every dimension of it is enormous.

Moving from a hypothetical 97th percentile to the 99th might involve considerably more effort than reaching the 97th in the first place. Language proficiency levels are not themselves population percentiles, but the principle of increasingly demanding improvements remains relevant. This does not mean that further improvement is unnecessary. It simply means that we should distinguish between the proficiency required to accomplish our objectives and the proficiency required to achieve extraordinary mastery.

If you can confidently communicate, negotiate, write, study and work in another language, you have already unlocked much of its practical value. Everything beyond that can become a deliberate choice rather than an endless obligation.

Machine Learning: Chasing the Final Percentage Points

Interestingly, this phenomenon is not limited to human learning. It can also be observed in machine learning. Imagine training a classification model that initially achieves 91% accuracy. Through better data preprocessing, hyperparameter tuning, improved feature engineering and fine-tuning, you might eventually achieve 95%, followed by 97%.

However, improving that model from 97% to 99% could become an entirely different problem. You might need considerably more training data, better annotations, architectural modifications, more computational resources or a deeper understanding of the remaining failure cases. Some errors might even result from ambiguous inputs, inconsistent labels or limitations inherent in the dataset itself.

Although the numerical difference appears small, the effort required to eliminate the remaining errors may be substantial. Going from 97% to 99% accuracy means eliminating two-thirds of the errors the model still makes. Unless, of course, you happen to be Walter White and have a particular fascination with achieving 99.1% purity.

The important question is whether that additional improvement is actually necessary. For certain applications, such as medical diagnosis or safety-critical systems, even a small improvement could have enormous consequences. For others, a reliable and computationally efficient model with 97% accuracy might be more valuable than an expensive and complicated model achieving 99%.

Accuracy percentages are not percentiles, of course, but the analogy illustrates a similar relationship between performance, effort and diminishing returns. Optimization should serve a purpose rather than become a pursuit of numerical perfection for its own sake. The same principle applies to how we optimize ourselves.

Defining the Population

There is, however, an important statistical consideration. Being in the 97th percentile of the general population is not the same as being in the 97th percentile of people who actively participate in a particular activity.

For example, a competent chess player might outperform most people in the general population while remaining relatively average among competitive chess players. Similarly, someone who exercises regularly might outperform much of the general population without being particularly exceptional among experienced athletes. Neither comparison is inherently wrong, but they answer different questions.

This is why every investigation within the Percentile Project must clearly define its reference population, measurement criteria and data sources. Not everything can be measured accurately, either. In areas where reliable statistics are unavailable, it is important to distinguish between an estimate and an established fact. Otherwise, the project would simply replace one arbitrary definition of success with another.

Escaping the Perfectionism Trap

Perhaps the most important purpose of this project is to escape the trap of perfectionism. One of the greatest obstacles to learning something new is believing that we must eventually master it. Before writing our first line of code, we worry about becoming excellent programmers. Before learning our first foreign words, we imagine speaking like native speakers. Before solving our first Rubik's Cube, we watch people solve it in three seconds. We allow the difficulty of the final destination to discourage us from taking the first step.

But mastery does not have to be the initial objective. We can instead establish a challenging but achievable target, work toward it, and reassess our ambitions once we arrive. The 97th percentile is not necessarily a destination at which we must stop. Nor is it a magical number that guarantees meaningful competence in every discipline. It is a way of establishing a reasonable direction.

Once we reach our initial objective, we may discover that we genuinely enjoy the subject and want to pursue it further. Alternatively, we may recognize that we have already acquired everything we originally wanted from it. Both are perfectly reasonable outcomes.

There is also an opportunity cost associated with perfectionism. Every additional hour spent mastering the final details of one subject is an hour that cannot be invested in another. Sometimes, the effort required to move from the 97th to the 99th percentile in one discipline could instead be invested in developing substantial competence in an entirely different one. The intention is not to discourage ambition but to prevent extreme ambitions from becoming barriers to progress.

You do not need to commit to mastery before giving yourself permission to begin.

Turning the Idea into a Project

For every discipline, I would like to investigate five fundamental questions:

  1. What does average performance look like?
  2. What is required to reach the 90th, 95th, 97th and 99th percentiles?
  3. What specific knowledge and skills are necessary?
  4. How much time, effort and money would reaching these levels require?
  5. At what point do diminishing returns become significant?

The resulting information could become a collection of practical roadmaps for acquiring different skills and achieving measurable objectives. Rather than relying on motivational advice or vague ambitions, each roadmap would begin with evidence and end with something actionable.

Over time, this could develop into a personal encyclopedia of human competence — an investigation into what people can achieve and what it actually costs to get there.

A Different Way of Thinking About Success

Ultimately, the Percentile Project is not about competing with everyone else or establishing superiority over other people. It is about understanding what is achievable. It is about replacing intimidating, poorly defined ambitions with concrete objectives. It is about recognizing that one does not necessarily need to dedicate an entire lifetime to a subject to develop a meaningful level of competence in it.

Perhaps we could become financially knowledgeable, physically capable, technically proficient, articulate, well-read and competent in several practical disciplines without becoming world-class specialists in any of them. Of course, reaching the 97th percentile in everything is neither realistic nor necessary. Some disciplines will deserve more attention than others, and some will simply not be worth pursuing. But understanding the requirements allows us to make that decision deliberately.

The world contains an enormous number of skills, disciplines and opportunities. We have a limited amount of time to explore them. Perhaps the most interesting question is not how good we could possibly become at one thing, but how many meaningful things we could become exceptionally good at within a single lifetime.

That is the idea behind the 97th Percentile Project.