0

I want to add a where condition if the item exist in array, how to make this conditional statement?

SELECT 
        *
FROM
        table
WHERE
        id = 'XX'
AND
        tag in {'one', 'two', 'three'};
1
  • 1
    tag in ('one', 'two', 'three'); Commented Oct 20, 2021 at 7:17

2 Answers 2

4

You're almost there! Just replace { with (.

Let's test by creating table first:

create table test(
    id varchar(2),
    tag varchar(10)
);

Insert some values:

insert into test(id, tag) values ('XX', 'one'), ('YY', 'two'), ('XX', 'three'), ('XX', 'four');

Execute your query:

SELECT 
        *
FROM
        test
WHERE
        id = 'XX'
AND
        tag in ('one', 'two', 'three');

You should see the result as below:

id|tag  |
--+-----+
XX|one  |
XX|three|
Sign up to request clarification or add additional context in comments.

Comments

0

There are various ways, depending on what exactly you want to do and what type is the column you want to query: string, integer, enum, json...

Basically I have only used in (...) notation, but I found way with using any as well.

If your column (myColumn) is an array, you can use this

SELECT * FROM myTable
WHERE 'myStringValue/enum' = ANY (myColumn)

But if your column (myColumn) is not an array (scalar), you can use this

SELECT * FROM myTable
WHERE myColumn IN (...values)

Some reference to read on your own: https://www.postgresql.org/docs/14/arrays.html#ARRAYS-SEARCHING and https://www.postgresql.org/docs/14/functions-comparisons.html

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.