DB order by clause issue

qry := `
SELECT id, uuid, name
FROM users
ORDER BY ?
LIMIT ?
OFFSET ?
`

limit := getLimit() // 10 (int)
offset := getOffset() // 0 (int)
order := getOrder() // id DESC (string)

rows, err := db.QueryContext(ctx, qry, order, limit, offset)

When I run code above, ORDER BY clause won’t affect the result because id DESC is being wrapped within single quotes as shown below in the DB logs. Is there a solution to this (excluding fmt.Sprintf)? Single quote is the issue here.

SELECT id, uuid, name
FROM users
ORDER BY 'id DESC'
LIMIT 10
OFFSET 0

Try splitting it into two parameters e.g. in your SQL: ... ORDER BY ? ? and then split the result of getOrder into two parameters: order and direction.

It gives SQL error. By the way, I think there is no solution to it unless I use what I didn’t want to use at the beginning which is fmt.Sprintf.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.