0

I have a simple SQL query such as

SELECT * from tableName
WHERE (field = 'value1') OR (field = 'value2') OR (field = 'value3') ...

I am lazy enough to write hardcode write the SQL query like above. I want to extract value1, value2 , ... in an array ( or any collections)

How to write the query above so that it can loop the list of values ?

# declare array

# loop for each element in the array
SELECT * from tableName WHERE (field = element) 

# or even better
# build the WHERE clause with a loop
whereClause = (field = 'value1') OR (field = 'value2') OR (field = 'value3') ...

SELECT * from tableName WHERE whereClause
2
  • 2
    where field = any(array)? Commented Nov 15, 2021 at 14:12
  • @a_horse_with_no_name You are a genius Commented Nov 15, 2021 at 14:40

1 Answer 1

1

As a_horse_with_no_name has mentioned you can

  1. Check if the field is in an array
SELECT *
FROM   tableName 
WHERE  field = ANY(ARRAY['value1', 'value2'])

and you can use a language of your choice to fill these values dynamically

  1. or if those values are already in a table you can
SELECT * 
FROM   tableName
WHERE  field IN (SELECT field FROM otherTableName) 
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.