Example 1
Index only active orders and query them by customer
The index idx_active_orders_customer stores only the three rows where status = 'active' (rows 1, 2, 5), skipping the two closed orders. On a production table with millions of rows and a small fraction active, this index would be dramatically smaller than a full index on customer_id. The query planner recognises that the query predicate status = 'active' AND customer_id = 1 implies the index condition status = 'active' and uses the partial index automatically — no query changes are needed. To enforce that each customer has at most one active order, use CREATE UNIQUE INDEX ... WHERE status = 'active'; the uniqueness constraint applies only to active rows and does not prevent the same customer from having multiple closed orders.
CREATE TABLE orders (id INT, customer_id INT, status VARCHAR(20));
INSERT INTO
orders
VALUES
(1, 1, 'active'),
(2, 2, 'active'),
(3, 1, 'closed'),
(4, 2, 'closed'),
(5, 1, 'active');CREATE INDEX idx_active_orders_customer ON orders (customer_id)
WHERE
status = 'active';
SELECT
id,
customer_id
FROM
orders
WHERE
status = 'active'
AND customer_id = 1
ORDER BY
id;| id | customer_id |
|---|---|
| 1 | 1 |
| 5 | 1 |
MySQL and MariaDB do not support partial indexes; the example does not run on those engines.