#When I have a index with multiple columns, how can I specify ordering for all of them

1 messages · Page 1 of 1 (latest)

limpid cliff
#

Say I have a index ("by_highest_score", ["highestScore"]) and I want to first order by highest score, highest first, and then by _createionTime, lowest first? So first desc den asc

thick plankBOT
#

Hi @limpid cliff. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can’t specify different sort directions per indexed field in a single Convex query today.

What you can control:

  • The index defines the sort columns and their priority.
  • .order("asc" | "desc") flips the direction for the entire index key. [Ordering; Sorting with indexes]

So with:

players: defineTable({
  username: v.string(),
  highestScore: v.number(),
}).index("by_highest_score", ["highestScore"]);

a query like:

const top = await ctx.db
  .query("players")
  .withIndex("by_highest_score")
  .order("desc")
  .take(10);

is ordered by:

  1. highestScore descending
  2. _creationTime descending (because _creationTime is always the last index column and shares the same direction) [Sorting with indexes]

There’s no documented way to get highestScore DESC, _creationTime ASC directly from the database. To achieve that exact ordering you’d need to:

  1. Use the index to get a reasonably small result set (e.g. order("desc").take(n)), then
  2. Re‑sort that array in JavaScript by _creationTime ascending as a tiebreaker.

The knowledge sources don’t mention any feature for per-column sort directions or custom index directions, so if you need that pattern at scale, it isn’t supported directly.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: