#When I have a index with multiple columns, how can I specify ordering for all of them
1 messages · Page 1 of 1 (latest)
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:
highestScoredescending_creationTimedescending (because_creationTimeis 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:
- Use the index to get a reasonably small result set (e.g.
order("desc").take(n)), then - Re‑sort that array in JavaScript by
_creationTimeascending as a tiebreaker.