Lab 05: Advanced Indexing
Step 1 — Setup: Products Table with 10,000 Rows
-- PostgreSQL
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
category VARCHAR(50),
price NUMERIC(10,2),
stock INT,
tags TEXT[],
metadata JSONB,
is_active BOOLEAN DEFAULT true
);
INSERT INTO products (name, category, price, stock, tags, metadata, is_active)
SELECT
'Product ' || i,
CASE (i % 5)
WHEN 0 THEN 'Electronics' WHEN 1 THEN 'Clothing'
WHEN 2 THEN 'Books' WHEN 3 THEN 'Food'
ELSE 'Sports' END,
(RANDOM() * 500 + 1)::NUMERIC(10,2),
(RANDOM() * 1000)::INT,
ARRAY['tag' || (i%10), 'cat' || (i%5)],
jsonb_build_object('brand', 'Brand'||(i%20), 'rating', (RANDOM()*5)::NUMERIC(3,1)),
(i % 10 != 0)
FROM generate_series(1, 10000) i;
ANALYZE products;Step 2 — Composite Indexes: Column Order Matters
Step 3 — Partial Indexes (PostgreSQL)
Step 4 — Covering Indexes (Index-Only Scans)
Step 5 — GIN Index: Arrays and JSONB
Step 6 — GiST Index and Full-Text GIN
Step 7 — MySQL Prefix Indexes and Index Bloat
Step 8 — Capstone: Index Strategy for an E-commerce Query
Summary
Index Type
Operator
Best For
Last updated
