How to return only values from SELECT and WHERE IN query?

54 views Asked by At

I have the following table - orders:

id value price amount
2 'orange' $12 7
8 'yellow' $14 29
5 'green' $17 9

I have to perform SELECT query with WHERE IN clause

SELECT value FROM order WHERE id IN (2, 5);

or using Knex.js

knex('orders)
      .select('value')
      .whereIn('id', [2, 5])

it returns me an array of objects:

[{value: 'orange'}, {value: 'green'}] 

how is it possible to return only array of values using PostgreSQL syntax?

['orange', 'green']
2

There are 2 answers

1
Rene Bustamante On

Using SQL:

SELECT DISTINCT array_agg(value) AS values
FROM orders
WHERE id IN (2, 5);

Using Knex.js

const values = await knex.raw(`
    SELECT DISTINCT array_agg(value) AS values
    FROM orders
    WHERE id IN (2, 5)
`);
0
Vivick On

Using pluck:

knex('orders')
      .select('value')
      .whereIn('id', [2, 5])
      .pluck('value')