Home > Mobile >  SELECT WHERE column values are in array
SELECT WHERE column values are in array

Time:12-16

Suppose I have a table called 'myTable':

columnA|    columnB|    columnC
   1   |     Yellow|     Apple
   3   |     Red   |     Grape
   8   |     Blue  |     Banana
   6   |     Green |     Orange

The above table is a simplification of an actual table for demo purposes. Imagine actual table is 100K rows. Now, I want to select only the rows where columnB is in a list/array: ex - ['Red', 'Blue', 'Green']. I am not sure the right syntax to use here.

 SELECT * FROM myTable WHERE columnB IN Array['Red', 'Blue', 'Green']

Whats the proper syntax to achieve this?

CodePudding user response:

Here is the example, I believe its for MS SQL

SELECT p.FirstName, p.LastName, e.JobTitle  
FROM Person.Person AS p  
    JOIN HumanResources.Employee AS e  
    ON p.BusinessEntityID = e.BusinessEntityID  
WHERE e.JobTitle IN ('Design Engineer', 'Tool Designer', 'Marketing Assistant');  

CodePudding user response:

In Postgres, you can use an array, too, with = ANY ():

SELECT * FROM myTable WHERE columnB = ANY (ARRAY['Red', 'Blue', 'Green']);

Or with a literal array constant as input:

SELECT * FROM myTable WHERE columnB = ANY ('{Red, Blue, Green}'::text[]);

It's equivalent to:

SELECT * FROM myTable WHERE columnB IN ('Red', 'Blue', 'Green');

Related:

  • Related