Nicholas Hazel
Nicholas Hazel

Reputation: 3750

Adding a custom column to a knex query with PostgreSQL

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

Upvotes: 0

Views: 1349

Answers (1)

felixmosh
felixmosh

Reputation: 35493

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');

Upvotes: 2

Related Questions