Added a composite index covering every column in your query, yet the database still runs a sort? Classic mistake. A B-tree stores keys like a dictionary: sorted first by column one, then column two within it, and only then by column three.
Suppose you want shipped orders for customer CUST123 sorted by date from Orders:
-- Query with two equality filters and a sort
SELECT OrderID, CustomerID, OrderDate, TotalAmount
FROM Orders
WHERE CustomerID = 'CUST123'
AND Status = 'Shipped'
ORDER BY OrderDate;
-- Put equality filters first, sort column last
CREATE INDEX idx_orders_customer_status_date
ON Orders (CustomerID, Status, OrderDate);
As PostgreSQL's documentation explains, a B-tree narrows searches using leading equality (=) columns. First CustomerID slices the table down to one customer, then Status isolates shipped orders. Inside that narrow slice, rows are already ordered by OrderDate, eliminating the extra Sort step.
Put OrderDate first instead, and that customer's orders scatter across the entire date tree, forcing a broad scan. Better yet, (CustomerID, Status, OrderDate) follows the leftmost-prefix rule, speeding up queries filtering by CustomerID alone or (CustomerID, Status) too. Check your actual plan with EXPLAIN ANALYZE.
