Index Types Deep Dive: Functions
Module: Query Optimization & Performance
**PostgreSQL - All Index Types:**
```sql
-- 1. B-tree (default)
CREATE INDEX idx_btree ON orders(order_date);
-- Same as:
CREATE INDEX idx_btree ON orders USING btree(order_date);
-- Multi-column B-tree
CREATE INDEX idx_customer_date ON orders(customer_id, order_date);
-- Use for: WHERE customer_id = ? AND order_date > ?
-- 2. Hash index
CREATE INDEX idx_hash ON users USING hash(email);
-- Only for: WHERE email = 'exact@match.com'
-- NOT for: WHERE email LIKE '%match%'
-- 3. GIN index for full-text
CREATE INDEX idx_gin_fts ON articles
USING gin(to_tsvector('english', content));
-- Query with:
SELECT * FROM articles
WHERE to_tsvector('english', content) @@ to_tsquery('postgresql & performance');
-- GIN for JSONB
CREATE INDEX idx_gin_json ON products USING gin(metadata);
-- Query with:
SELECT * FROM products WHERE metadata @> '{"brand": "Apple"}';
SELECT * FROM products WHERE metadata ? 'warranty';
SELECT * FROM products WHERE metadata ?& ARRAY['color', 'size'];
-- GIN for arrays
CREATE INDEX idx_gin_array ON posts USING gin(tags);
-- Query with:
SELECT * FROM posts WHERE tags @> ARRAY['postgresql'];
SELECT * FROM posts WHERE tags && ARRAY['sql', 'database'];
-- 4. GiST index for geometry
CREATE INDEX idx_gist_geo ON locations USING gist(coordinates);
-- Query with:
SELECT * FROM locations
WHERE ST_DWithin(coordinates, ST_MakePoint(-122.4, 37.8), 5000);
-- GiST for range types
CREATE INDEX idx_gist_range ON bookings USING gist(booking_period);
-- Query with:
SELECT * FROM bookings
WHERE booking_period && '[2024-01-01, 2024-01-31)'::daterange;