skip to Main Content

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

Answers


  1. 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)
    `);
    
    Login or Signup to reply.
  2. Using pluck:

    knex('orders')
          .select('value')
          .whereIn('id', [2, 5])
          .pluck('value')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search