Advanced indexes

Draft

After the first index, the next lesson is shape. Useful indexes depend on how selective the filter is and how the query is written.

Low selectivity

An index on status exists, but paid matches most rows, so a scan can still be cheaper.

SELECT COUNT(*) AS paid_orders
FROM orders
WHERE status = 'paid';
Loading plan...

Composite index

This query matches the status, created_at index shape: filter first, then order.

SELECT order_number, status, created_at
FROM orders
WHERE status = 'pending'
ORDER BY created_at DESC
LIMIT 5;
Loading plan...

Partial index

A partial index stores only failed orders, which keeps a rare lookup small.

SELECT order_number, status, total_cents
FROM orders
WHERE status = 'failed'
  AND order_number = 'ORD-9000';
Loading plan...

Try Yourself

Loaded Database:advanced-indexes.database-init

The database for this lesson is already loaded. Write any query you want and run it directly in your browser.

Exercises

0 OF 2 DONE
1.Select the 3 newest paid orders using status, ORDER BY created_at DESC, and LIMIT.
2.Select failed order ORD-12000 using both status and order_number.

What We Learned