Loading skill
Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Use indexes instead of filter() for efficient database queries
| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-09 | ✗→✓ | ▲ Improved | -23% | 0% |
| case-01 | ✓→✓ | = Same ✓ | -11% | 0% |
| case-02 | ✓→✓ | = Same ✓ | 22% | 0% |
| case-03 | ✓→✓ | = Same ✓ | -12% | 0% |
| case-04 | ✓→✓ | = Same ✓ | -29% | 0% |
Avoid using .filter() on database queries. Instead, use indexed queries with .withIndex() or filter in TypeScript after collecting results.
Using .filter() on queries performs a full table scan, which becomes slow as your data grows. Indexes provide fast lookups.
Bad:
typescriptconst user = await ctx.db .query("users") .filter(q => q.eq(q.field("email"), email)) .first();
Good:
typescript// In schema.ts export default defineSchema({ users: defineTable({ email: v.string(), name: v.string(), }).index("by_email", ["email"]), }); // In your function const user = await ctx.db .query("users") .withIndex("by_email", q => q.eq("email", email)) .first();
If you must filter by a field that doesn't warrant an index:
typescriptconst allUsers = await ctx.db.query("users").collect(); const filtered = allUsers.filter(user => user.age > 18);
Other measured skills in the registry, with their headline benchmark lift.