How can I write select firstName || ' ' || lastName as name
in knexjs. Using raw this way .columns(knex.raw("fname || ' ' || lname as name"))
works, but is there any other way?
1 Answer
You could also just combine it in the code itself, why combine it in the query, when the same work can be done inline with the results of your query. It would be easier to read at that point, and you can do other stuff to the string before handing it out.
PS: You did ask "is there any other way?"
-
5I wanted to accomplish it in the SQL layer itself, instead of running more loops on the result.– surajckMar 25, 2015 at 6:43
-
1Then you're doing it correctly, since you're doing it at the SQL layer, that's exactly how I would have to do it in raw SQL on the command line. But sadly the raw query will be specific to a single database, your method to CONCAT a string together is based on sqlite, which may not be valid in other DB servers. github.com/tgriesser/knex/issues/465 This is a concern to some folks, but as you will see in other threads on around knex, that's not what it was for. You're supposed to do queries, and manipulate the results in the higher language. Mar 27, 2015 at 3:20
-
what about if you want to sort on the concatenation of several columns... Mar 29, 2017 at 21:25
-
The only difference between the columns would be the concat'ed content, and if you just "order by column1, column2, ...". It also comes down to usage. this response is more off topic though, the question is how to combine multiple columns, not how to order by multiple columns. also you can order in the higher language, unless you're doing pagination. Apr 28, 2017 at 21:30