Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql, javax.persistence.criteria: check a database table column with comma separated string values against a list of strings

I have a database table column with comma separated string values like this:

id mycolumn
-- --------
1  A
2  A, B
3  A, B, C

I can't change this, because it's an old customizer database.

I want to check mycolumn against a list of strings:

first query against the list ['A'] should be return the record 1

second query against the list ['A','B'] should be return records 1,2

third query against the list ['A','B','C'] should be return records 1,2,3

I need a sql (postgres) statement and further a java implementation with javax.persistence.criteria.CriteriaBuilder and javax.persistence.criteria.Predicate.

Thank you very much for your hints, Ann

edit: Here my solution for the javax.persitence part:

public static void arrayContains(final CriteriaBuilder cb, final List<Predicate> where,
            final Expression<String> expression, final String values) {
        Expression<String> expressionValues = cb.function("string_to_array", String.class, cb.literal(values), cb.literal(", "));
        Expression<String> expressionDb = cb.function("string_to_array", String.class, expression, cb.literal(", "));
        where.add(cb.isTrue(cb.function("arraycontains", Boolean.class, expressionValues, expressionDb)));
    }
like image 231
Ann-Christin Lindras Avatar asked Feb 03 '26 22:02

Ann-Christin Lindras


1 Answers

In PostgreSQL use string_to_array(mycolumn,',') in the WHERE clause with the containment operator <@, e.g.

SELECT * FROM t
WHERE string_to_array(mycolumn,',') <@ ARRAY['A','B','C']

Keep in mind that you have to create an index that correspond to this condition, in case you're dealing with a large table, e.g. a GIN index.

CREATE INDEX idx_t_mycolumn_gin ON t USING gin (string_to_array(mycolumn,','));

Demo: db<>fiddle

like image 186
Jim Jones Avatar answered Feb 06 '26 12:02

Jim Jones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!