Home / Guides / SQL Formatting & Index Performance Guide

SQL Query Formatting & Index Optimization: A Practical Guide for Database Engineers

✍️ By Zain Masri πŸ“… 2026-10-28 ⏱️ 8 min read Database Engineering

In high-throughput database systems, poorly structured queries do more than create readability headaches during code reviewsβ€”they frequently obscure catastrophic performance bottlenecks. A missing composite index or an accidental function wrapper around a WHERE clause can cause a query to pivot from an index scan (O(log n)) into a multi-million-row sequential table scan (O(n)).

In this guide, we explore industry-standard SQL formatting conventions that improve maintainability and dive into real-world query optimization strategies for PostgreSQL and MySQL.

1. Clean SQL Formatting Conventions

Clean formatting is not just aesthetic; it makes execution logic and join hierarchies immediately obvious during debugging:

-- Readable, maintainable enterprise SQL structure
WITH monthly_cohort AS (
  SELECT
    user_id,
    DATE_TRUNC('month', created_at) AS signup_month
  FROM users
  WHERE status = 'active'
)
SELECT
  c.signup_month,
  COUNT(DISTINCT c.user_id) AS total_users,
  COALESCE(SUM(p.amount_usd), 0.00) AS total_revenue
FROM monthly_cohort c
LEFT JOIN payments p 
  ON p.user_id = c.user_id 
  AND p.status = 'succeeded'
GROUP BY c.signup_month
ORDER BY c.signup_month DESC;

2. Demystifying EXPLAIN (ANALYZE, BUFFERS)

Before optimizing any query, run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL to observe the real execution path rather than guessing:

Seq Scan on orders (cost=0.00..1845.20 rows=452 width=32) (actual time=0.045..12.340 rows=430 loops=1)
  Filter: (created_at >= '2026-01-01'::date)
  Rows Removed by Filter: 89570
  Buffers: shared hit=842 read=124
Planning Time: 0.182 ms
Execution Time: 12.450 ms

Key metrics to audit:

3. The Leftmost Prefix Rule for Composite Indexes

When indexing multiple columns (e.g. CREATE INDEX idx_orders_user_status ON orders(user_id, status, created_at);), column order is critical. A composite B-tree index is sorted lexicographically like a phone book:

Rule of thumb: Place equality filter columns first, followed by range filter columns (e.g. timestamps or amounts).

4. The SARGable Query Principle (Search Argument Able)

Wrapping indexed columns inside functions prevents the query planner from using standard B-Tree indexes:

-- BAD: Non-SARGable (Forces full table scan because function must run on every row)
SELECT * FROM users WHERE LOWER(email) = 'alex@example.com';

-- GOOD: Use functional index OR normalize at write time
CREATE INDEX idx_users_lower_email ON users(LOWER(email));

-- BAD: Math on indexed timestamp column
SELECT * FROM subscriptions WHERE created_at + INTERVAL '30 days' < NOW();

-- GOOD: Isolate the column on one side of operator
SELECT * FROM subscriptions WHERE created_at < NOW() - INTERVAL '30 days';

✨ Format & Beautify Complex SQL Queries Locally

Clean up messy SQL queries, format subqueries, and align keywords with our Client-Side SQL Formatter & Query Beautifier. Fast, private, and 100% in-browser.

Open Free SQL Formatter β†’

More Engineering Guides & Tutorials

Data Engineering β€’ 7 min read
How to Flatten and Parse Deeply Nested JSON in Python, jq, and Node.js
A complete engineering guide to un-nesting arbitrary JSON hierarchies into tabular CSV formats with dot notation, recursive algorithms, and streaming parsers.
Security & Auth β€’ 8 min read
Demystifying JSON Web Tokens: Structure, Signature Verification & Security Pitfalls
A practical guide to JSON Web Tokens (JWT): header anatomy, HMAC vs RSA signatures, token tampering prevention, and client-side cryptographic inspection.
Code & Performance β€’ 7 min read
High-Performance Regular Expressions: Preventing ReDoS & Catastrophic Backtracking
Learn how NFA regex engines execute, why nested quantifiers trigger catastrophic backtracking (ReDoS), and how to write linear-time regular expressions.
⚑ Pro Blueprints ($19) Instant PayPal β†’