© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•3y ago•
8 replies
Valerio

orderBy with variable column

Hey all!
I'd like to explore the possibility to order a query by one of it's columns, but the column itself is inferred from a variable.
What i've tried:
// "categories" has 2 column, id and name

const sortField = 'name';

await db.query.categories.findMany({ orderBy: asc(sql`${sortField}`) });
// "categories" has 2 column, id and name

const sortField = 'name';

await db.query.categories.findMany({ orderBy: asc(sql`${sortField}`) });


but no sort is applied.

Even using

const sortField = 'name' as keyof typeof categories;
const sortField = 'name' as keyof typeof categories;

does not change the final result.
Any idea?

Thanks in advance!
Solution
const sortField = 'name';

await db.query.categories.findMany({ orderBy: asc(sql.identifier(sortField)) });
const sortField = 'name';

await db.query.categories.findMany({ orderBy: asc(sql.identifier(sortField)) });
Jump to solution
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

orderBy related table column
Drizzle TeamDTDrizzle Team / help
3y ago
Dynamic orderBy
Drizzle TeamDTDrizzle Team / help
3y ago
OrderBy with dynamic queries dont work
Drizzle TeamDTDrizzle Team / help
3y ago
case insensitive orderBy
Drizzle TeamDTDrizzle Team / help
2y ago