Skip to content

Add support for composite indexes and ORDER BY in index queries for boolean values #222

@abose

Description

@abose

Our current _buildCreateIndexQuery / createIndexForJsonField only generate single-column indexes and don’t support ORDER BY.
We need to extend them to accept extra columns (with optional ASC/DESC) and build composite indexes.
Additionally, we should restrict ORDER BY usage to indexed columns only, to avoid inefficient queries.

This is especially important for boolean values stored in JSON, where selectivity is low (e.g. only ~5% are true). Without a composite index, queries must scan large portions of the table.

Example use case: targeting Pro customers whose subscriptions are ending soon.
is_pro_user lives in JSON, and queries like this aren’t efficient today:

SELECT id, name
FROM customers
WHERE json_is_pro_user = 1
ORDER BY subscription_end_date
LIMIT 100;

With a composite index on (is_pro_user, subscription_end_date) MySQL can directly fetch only the Pro users, ordered by their subscription end date:

CREATE INDEX idx_is_pro_user_enddate
  ON customers (`json_is_pro_user` ASC, `subscription_end_date` ASC);

Efficient query:

SELECT id, name
FROM customers
WHERE json_is_pro_user = 1
  AND subscription_end_date > NOW()
ORDER BY subscription_end_date
LIMIT 100;

This avoids scanning the 95% of non-Pro rows and ensures ORDER BY subscription_end_date is satisfied by the index.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions