SQL:SQL Indexes: B-Tree Indexing and Query Performance
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:

ParameterTypeDescription
CREATE INDEXStatementBuilds B-tree index on specified table columns.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler