3

I'd like to create GIN index on a scalar text column using an ARRAY[] expression like so:

CREATE TABLE mytab (
 scalar_column TEXT
)

CREATE INDEX idx_gin ON mytab USING GIN(ARRAY[scalar_column]);

Postgres reports an error on ARRAY keyword.

I'll use this index later in a query like so:

SELECT * FROM mytab WHERE ARRAY[scalar_column] <@ ARRAY['some', 'other', 'values'];

How do I create such an index?

5
  • 2
    Are you just trying to check if the value of scalar_column matches one of a list of values? If so, you can just use a regular btree index and filter WHERE scalar_column IN ('some', 'other', 'values') Commented Apr 10, 2021 at 2:40
  • Which index should I use in this case? Commented Apr 10, 2021 at 6:57
  • As a workaround I've done this CREATE INDEX idx_gin ON mytab USING GIN(string_to_array(scalar_column, '')); I wonder if there is a proper way to create such an index. Commented Apr 10, 2021 at 7:47
  • The index and your query don't make any sense to begin with. Why do you think you need an index on an array expression? Commented Apr 10, 2021 at 9:58
  • 1
    I think that <@ operator with GIN index is faster than = ANY operator with no index. How would you speed up queries which check value against a given array? Commented Apr 10, 2021 at 18:12

1 Answer 1

3

You forgot to add an extra pair of parentheses that is necessary for syntactical reasons:

CREATE INDEX idx_gin ON mytab USING gin ((ARRAY[scalar_column]));

The index does not make a lot of sense. If you need to search for membership in a given array, use a regular B-tree index with = ANY.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Would you please be so kind to elaborate on usefulness of this index. I'd like to speed up queries which check if scalar value is in a given array.
I have elaborated.

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.