SQL Query Optimization: B-Tree Indexing, Execution Plans, and Clean Formatting Standards
A practical, engineering-focused guide to writing high-performance SQL queries. Understand database storage engines, index selectivity, execution plan analysis, and readability standards that help engineering teams scale their relational databases.
Key Takeaways
- Relational databases use cost-based query optimizers to parse, plan, and execute SQL statements.
- B-Tree indexes speed up lookups from O(N) linear time to O(log N) logarithmic time, but add write and storage overhead.
- Avoid non-sargable WHERE clauses (such as applying functions or wildcards to indexed columns) which force full table scans.
- Consistent SQL formatting with uppercase keywords and structured indentations drastically reduces cognitive load during code reviews.
1. How Database Query Optimizers Execute SQL
Unlike imperative programming languages (Python, JavaScript, Go) where you dictate step-by-step how to compute an answer, SQL is a declarative language. You specify what data you want, and the database’s Cost-Based Optimizer (CBO) decides how to retrieve it.
When you send a query, the engine parses the SQL syntax, converts it into a relational algebra tree, evaluates dozens of possible execution strategies (Index Scan, Bitmap Index Scan, Hash Join, Nested Loop), calculates an estimated cost based on table statistics, and selects the cheapest plan.
2. The Mechanics of B-Tree Indexes & Index Selectivity
A table without an index is stored as an unordered heap of data pages. To find a single record matching WHERE email = 'user@example.com', the engine must perform a Sequential Scan (Full Table Scan), reading every single disk block from start to finish.
A B-Tree (Balanced Tree) index maintains a sorted, self-balancing tree structure where each leaf node points directly to the physical tuple ID (TID) on disk. Searching a table with 10 million rows via a B-Tree requires only 3 to 4 disk page reads, executing in sub-millisecond time.
-- BAD: Non-Sargable query (forces full table scan on 5M rows)
SELECT id, email, created_at
FROM users
WHERE DATE(created_at) = '2026-10-31';
-- GOOD: Sargable range query (utilizes B-Tree index on created_at)
SELECT id, email, created_at
FROM users
WHERE created_at >= '2026-10-31 00:00:00'
AND created_at < '2026-11-01 00:00:00';
3. Reading Execution Plans: EXPLAIN ANALYZE
Never guess why a query is slow—ask the database directly using EXPLAIN ANALYZE (or EXPLAIN in MySQL).
Key warning signs in execution plans include:
• Seq Scan / Table Scan on tables with more than 10,000 rows.
• High filter percentages (e.g., "Rows Removed by Filter: 998,400"). This indicates the engine read a massive dataset only to throw 99% of it away.
• Nested Loops with massive outer row counts where a Hash Join would have been substantially faster.
4. Clean SQL Formatting Standards for Teams
Messy, unindented SQL with lowercase keywords is a major source of syntax bugs and missed indexing opportunities in production codebases.
Adopting strict formatting conventions—capitalizing SQL keywords (SELECT, FROM, WHERE, JOIN), placing each column and join condition on a new line, and aligning clauses—enhances readability and makes code reviews painless.