← Back to PostgreSQL Course | Chapter 9: Indexes & Performance | Lesson 6 of 7

Query optimization

Optimising means measuring, indexing sensibly, fetching only what you need and letting the planner have good statistics.

In this page:

  1. Query optimization

Query optimization

Start with EXPLAIN ANALYZE on the slowest queries. Select only needed columns, filter early, avoid functions on indexed columns in WHERE, replace OFFSET paging with keyset paging, batch writes, and keep statistics fresh with ANALYZE.

Consider covering indexes (INCLUDE) and partial indexes. Measure again after each change.

Note: A function on a column, like lower(col), prevents a plain index on col from being used.

Example: Query optimization

bash
-- Slow: function on the column defeats the plain index
shop=# SELECT id FROM users WHERE lower(email) = '[email protected]';
-- Fast: an expression index matches the query
shop=# CREATE INDEX idx_users_lower_email ON users (lower(email));
-- Fast: keyset pagination instead of a huge OFFSET
shop=# SELECT id, title FROM posts WHERE id > 12000 ORDER BY id LIMIT 20;
-- Covering index so PostgreSQL can answer from the index alone
shop=# CREATE INDEX idx_orders_cust ON orders (customer_id) INCLUDE (total);

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Optimising without measuring
  2. Using SELECT *
  3. Wrapping indexed columns in functions
Chapter Summary
  • Measure with EXPLAIN ANALYZE
  • Select only needed columns
  • Avoid functions on indexed columns
  • Refresh statistics with ANALYZE
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.