0

I'm very new to writing queries in general for PostgreSQL, much less Knex, so I appreciate any help somebody can provide.

PostgreSQL v10.12
Knex v0.20.13
Node v12.16.0

Say I have a DB with entries such as:

id   |  int1  |  int2
_____________________
1        5        10
2        6        15

And my knex query looks something like this:

db // This is my knex connection
  .from('items AS item')
  .select(
    'item.id',
    'item.int1',
    'item.int2'
   )

How would I go about adding a column to my results that would SUM int1 and int2?

id   |  int1  |  int2  |  sum
_______________________________
1        5        10       15
2        6        15       21

1 Answer 1

2

First of all, in order to not skip a step.

The query that we want to build with Knex is:

Select id, int1, int2, (int1 + int2) as sum from items;

This query will fetch all the regular columns of items and add a new column with the name sum.

In order to build this query using Knex:

db.select('id', 'int1', 'int2', db.raw('(int1 + int2) as sum')).from('items');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.