SQL Query Formatting & Index Optimization: A Practical Guide for Database Engineers
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:
- Capitalize Core Keywords: Keep standard ANSI SQL clauses (
SELECT,FROM,WHERE,GROUP BY,ORDER BY,HAVING) in uppercase, while keeping table and column names in lowercase snake_case. - One Column Per Line: In
SELECTprojections, place each attribute on its own line with leading commas. This minimizes git merge conflict diffs when columns are added or removed. - Explicit Join Conditions: Always use explicit
INNER JOIN ... ONsyntax. Never use comma joins (FROM users, orders WHERE ...) which obscure cross-join hazards. - Prefer Common Table Expressions (CTEs) over Deep Subqueries: Decompose multi-step queries into readable
WITHblocks.
-- 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:
- Seq Scan vs. Index Scan: A sequential scan means the database examined every single page on disk. For large tables (>100k rows), this indicates a missing or unusable index.
- Rows Removed by Filter: If the database read 90,000 rows only to discard 89,570, your index did not narrow down the dataset early enough.
- Buffers (Shared Read): "Read" indicates blocks fetched from physical disk (slow), whereas "Hit" indicates memory cache access.
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:
WHERE user_id = 42β Uses IndexWHERE user_id = 42 AND status = 'paid'β Uses IndexWHERE status = 'paid'β CANNOT Use Index (violates leftmost prefix)
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.