SQL•Indexing
SQL Indexes: B-Tree Indexing and Query Performance
Indexes create balanced B-Tree search structures on columns, eliminating slow full-table scans.
Syntax
CREATE INDEX idx_user_email ON users(email);
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| CREATE INDEX | Statement | Builds B-tree index on specified table columns. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT,
created_at TEXT
);
-- Create B-Tree index on email column for fast lookups
CREATE INDEX idx_users_email ON users(email);
INSERT INTO users VALUES
(1, '[email protected]', '2026-01-01'),
(2, '[email protected]', '2026-01-02');
-- Fast index lookup
SELECT * FROM users WHERE email = '[email protected]';Expected Output:
id email created_at -- ---------------- ---------- 1 [email protected] 2026-01-01
How It Works: Step-by-Step
- Lines 8: CREATE INDEX builds B-tree index on email.
- Line 16: WHERE email = ... utilizes the index for instant O(log N) lookup.
Key Concepts
- Indexes speed up SELECT queries with WHERE, JOIN, and ORDER BY clauses.
- Indexes add slight overhead to INSERT, UPDATE, and DELETE operations.
Common Mistake: Applying functions to indexed columns in WHERE clauses
WHERE LOWER(email) = "x" prevents the database from using an index on email. Use expression indexes.
❌ Incorrect
WHERE LOWER(email) = '[email protected]' // Invalidates simple index!
✅ Correct
WHERE email = '[email protected]'
Related SQL Tutorials & Compiler
SQL Multirow Aggregate Metrics Calculation: COUNT, SUM, AVG, and GROUP BY
Calculate multirow aggregate metrics using COUNT, SUM, AVG, MIN, MAX, and partitioned GROUP BY filters with HAVING.
SQL DDL: CREATE TABLE, Constraints (PRIMARY KEY, NOT NULL)
Design schemas using CREATE TABLE with PRIMARY KEY, FOREIGN KEY, NOT NULL, and UNIQUE.
SQL Window Functions: ROW_NUMBER, RANK, and OVER (PARTITION BY)
Compute running totals and row rankings across subsets using the OVER() clause.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.