Lesson 4 of 7
Query Optimisation - EXPLAIN, Indexes & Pagination
A slow query can make a fast application unusable. EXPLAIN shows how MySQL executes a query - revealing missing indexes, full table scans, and inefficient joins. Proper pagination with LIMIT/OFFSET vs cursor-based, and selecting only needed columns are among the most impactful optimisations.
EXPLAIN, Indexes & Efficient Pagination
-- ── EXPLAIN - understand query execution ───────────────────────
EXPLAIN SELECT p.*, u.name AS author_name
FROM posts p
JOIN users u ON u.id = p.author_id
WHERE p.status = 'published'
ORDER BY p.published_at DESC
LIMIT 10;
-- Key columns to understand:
-- type: ALL = full scan (BAD), ref/eq_ref = index lookup (GOOD)
-- key: which index MySQL uses (NULL = no index!)
-- rows: estimated rows scanned
-- Extra: "Using filesort" = no index for ORDER BY (slow on large tables)
-- ── Creating indexes ───────────────────────────────────────────
-- On WHERE condition columns
CREATE INDEX idx_posts_status ON posts (status);
-- Composite index - covers WHERE + ORDER BY
CREATE INDEX idx_posts_status_published ON posts (status, published_at DESC);
-- Covering index - includes all SELECT columns (avoids table lookup)
CREATE INDEX idx_posts_listing ON posts (status, published_at, id, title, slug);
-- ── The N+1 problem ───────────────────────────────────────────
-- ❌ N+1: 1 query for posts + 1 query PER post for author
SELECT * FROM posts WHERE status = 'published';
-- Then for EACH post:
SELECT * FROM users WHERE id = ?; -- executed N times!
-- ✅ JOIN - 1 query total
SELECT p.id, p.title, p.slug, p.published_at,
u.id AS author_id, u.name AS author_name
FROM posts p
INNER JOIN users u ON u.id = p.author_id
WHERE p.status = 'published'
ORDER BY p.published_at DESC;
<?php
// ── Efficient pagination in PHP ────────────────────────────────
class PostRepository {
public function paginate(int $page, int $perPage = 10): array {
$offset = ($page - 1) * $perPage;
// Get total for page count
$total = (int) $this->pdo->query(
"SELECT COUNT(*) FROM posts WHERE status = 'published'"
)->fetchColumn();
// Fetch page items - only the columns we need
$stmt = $this->pdo->prepare(
"SELECT id, title, slug, published_at, author_id
FROM posts
WHERE status = 'published'
ORDER BY published_at DESC
LIMIT :limit OFFSET :offset"
);
$stmt->bindValue(":limit", $perPage, PDO::PARAM_INT);
$stmt->bindValue(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
return [
"items" => $items,
"total" => $total,
"page" => $page,
"per_page" => $perPage,
"last_page" => (int) ceil($total / $perPage),
"has_more" => $offset + $perPage < $total,
];
}
// ── Cursor pagination - better for large datasets ──────────
// Instead of OFFSET 100000 (must scan 100K rows), use WHERE id > last_seen_id
public function cursorPaginate(int $afterId = 0, int $limit = 10): array {
$stmt = $this->pdo->prepare(
"SELECT id, title, slug, published_at
FROM posts
WHERE status = 'published' AND id > :after_id
ORDER BY id ASC
LIMIT :limit"
);
$stmt->bindValue(":after_id", $afterId, PDO::PARAM_INT);
$stmt->bindValue(":limit", $limit, PDO::PARAM_INT);
$stmt->execute();
$items = $stmt->fetchAll();
return [
"items" => $items,
"next_cursor" => !empty($items) ? end($items)["id"] : null,
];
}
}Quick Quiz
Tip
Tip
Practice Query Optimisation EXPLAIN Indexes Pagination in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Query Optimisation - EXPLAIN, Indexes & Pagination
Practice Task
Note
Practice Task - (1) Write a working example of Query Optimisation EXPLAIN Indexes Pagination from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Query Optimisation EXPLAIN Indexes Pagination is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?