5

I am using PostgreSQL 11.8

CREATE INDEX ix_products_product_sku_with_json_columns
ON products USING btree((product_sku))
INCLUDE ((data->>'variantCode'));

ERROR: expressions are not supported in included columns
SQL state: 0A000

Documentation says:

Expressions are not supported as included columns since they cannot be used in index-only scans.

I suppose data->>'variantCode' is an expression and that's the end of the story?
I can see two workarounds, none of which looks appealing to me:

  • create a dedicated VariantCode regular SQL column in the table
  • put data->>'variantCode' as part of the index keys

How bad is the second option?
Ultimately the goal would be to do an Index-Only Scan in the following query:

SELECT data->>'variantCode', ARRAY_AGG(product_sku)
FROM products
GROUP BY data->>'variantCode'
0

1 Answer 1

7

You cannot have data->>'variantCode' as INCLUDE column, but also adding it as index key won't help you to get an index-only scan. PostgreSQL doesn't consider index keys that are not columns for an index-only scan. There is no fundamental problem that prevents that, it is just not implemented.

You'd have to add the whole data to the index, but that is not possible, since there is no B-tree operator class for jsonb.

So the only remaining option to get an index-only scan would be a generated column:

ALTER TABLE products ADD data_varcode text
   GENERATED ALWAYS AS (data->>'variantCode') STORED;

Then you can use that column in your query and index.

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

1 Comment

Indeed, I couldn't achieve Index-Only Scans using that json column in the index keys, only Bitmap Heap Scan. Unfortunately I am running PostgreSQL 11.8 which doesn't include Generated Columns, but I can still create a regular column. Thanks

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.