A composite index with the equality columns first and the sort column last.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | -- ====================================================================== -- Q: Which index would you add? -- -- A composite index with the equality columns first and the sort column last. -- Verify with EXPLAIN (ANALYZE, BUFFERS). For large datasets use keyset -- pagination (WHERE created_at < @lastSeen) instead of OFFSET. -- ====================================================================== -- Query to optimize SELECT id, order_number, total_net FROM orders WHERE customer_id = @c AND status = 'Open' ORDER BY created_at DESC LIMIT 20; -- Composite covering index: equality columns first, sort column last CREATE INDEX CONCURRENTLY ix_orders_customer_status_created ON orders (customer_id, status, created_at DESC) INCLUDE (order_number, total_net); -- covering index |