Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multicolumn index with expression (PostgreSQL and Rails)

I need to create multicolumn index for 3 columns (VARCHAR, INT and INT), lets call them varchar_col, int1_col and int2_col. For VARCHAR column I need to apply lower(varchar_col) expression.

When I create one-column index with expression

add_index :table, 'lower(varchar_col)', name: 'index_name'

it works, but when I try to create multicolumn with

add_index :table, ['lower(varchar_col)', :int1_col, :int2_col], name: 'index_name'

I receive

PG::UndefinedColumn: ERROR: column "lower(varchar_col)" does not exist

Is it possible to create such an index with Rails add_index function or I need to execute SQL query in migration file? Does PostgreSQL support multicolumn index with expression? And if it supports, what I have to write in migration file to make it works?

Thank you for any help!

P.S. I'm using Rails 5.

like image 859
Peter Tretyakov Avatar asked Sep 12 '25 23:09

Peter Tretyakov


1 Answers

You may send the columns with the expressions as a string:

add_index :table, 'lower(varchar_col), int1_col, int2_col', name: 'index_name'
like image 177
Ilya Lavrov Avatar answered Sep 14 '25 13:09

Ilya Lavrov