SQL

Lesson 06

Index-friendly predicates

Keep indexed columns searchable by avoiding unnecessary functions on the column side.

Good Code

monthly-reviews.sql
SELECT id, title, submitted_at
FROM code_reviews
WHERE submitted_at >= TIMESTAMPTZ '2026-01-01'
  AND submitted_at < TIMESTAMPTZ '2026-02-01'
ORDER BY submitted_at DESC;

Bad Code

monthly-reviews.sql
SELECT id, title, submitted_at
FROM code_reviews
WHERE TO_CHAR(submitted_at, 'YYYY-MM') = '2026-01'
ORDER BY submitted_at DESC;

Review Notes

What to review

Good Code

The good version expresses the month as a half-open range, which keeps an index on submitted_at useful.

Bad Code

The bad version wraps the column in a formatting function for every row. It is readable, but it usually blocks normal index usage.

Takeaways

  • A correct query can still be review-worthy if it prevents useful index access.