Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use concat function in Postgres (9.3) index

I'm creating an index over several text columns (in Postgres 9.3) and I would like to use concat, e.g:

CREATE INDEX 
ON my_table
USING gin (to_tsvector('english', concat(title, ' ', description)))

However, when I try to do this I get the following error:

ERROR: functions in index expression must be marked IMMUTABLE

Vanilla concatenation with the || operator works fine. However, I'd prefer to use concat since description might be NULL, and the || operator seems to turn any concatenation with NULL into NULL.

If I understand this correctly this means that concat is not marked as immutable, which I don't understand.

Of course, I can just coalesce all the nullable columns, but it feels inelegant. More than anything, I'm curious as to why I can't use concat in my index?

like image 265
Christoffer Avatar asked Oct 24 '25 09:10

Christoffer


1 Answers

The reason CONCAT is not IMMUTABLE was explained by Tom Lane in this post:

concat() invokes datatype output functions, which are not necessarily immutable. An easy example is that timestamptz_out's results depend on the TimeZone setting.

I.e. that's due to the fact that it will accept non-text input, which may change based on session settings when converted to text.

You'll probably have to roll your own function for this.

like image 118
jcaron Avatar answered Oct 26 '25 01:10

jcaron



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!