Skip to content

how to use dynamic sorting and order? #655

Closed Answered by porsager
kiranimeid asked this question in Q&A
Discussion options

You must be logged in to vote

No, the issue is that your orderby column is sent as a parameter. Here is your sample query which should work (notice orderby is inside sql()):

const orderby = 'some_column'
const order = 'desc'

await sql`
  select 
    * 
  from ticket 
  where account = ${ acc.id }  
  order by ${ sql(orderby) } ${ order === 'desc' ? sql`desc` : sql`asc` }
`

Of course you could make the order by clause more dynamic, but that's almost always up to the specific userland implementation requirements. Imagine something like this:

const id = 1
const order = {
  username: 'asc'
  created_at: 'desc'
}

await sql`
  select 
    * 
  from ticket 
  where account = ${ id }  
  order by ${
    Object.entries(order).

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kiranimeid
Comment options

@porsager
Comment options

Answer selected by porsager
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants