I know that I can create an index that uses concatenation as follows:
CREATE INDEX idx_table1_field1_field2 ON table1((field1 || field2));
But this is not quite what I need. I will try to explain exactly what kind of index I need.
Let's assume there is a table (let's call it table1) that contains two fields (field1 and field2) of the character data type, each with a length of 15.
+----------------+----------------+
| field1 | field2 |
| character (15) | character (15) |
+----------------+----------------+
| James | Black |
+----------------+----------------+
| Michael | White |
+----------------+----------------+
| David | Silver |
+----------------+----------------+
Now if I execute the following SQL query:
SELECT field1 || field2, CONCAT(field1, field2) FROM table1
I get the following result:
+------------------+---------------------------------+
| ?column? | concat |
| text | text |
+------------------+---------------------------------+
| JamesBlack | James Black |
+------------------+---------------------------------+
| MichaelWhite | Michael White |
+------------------+---------------------------------+
| DavidSilver | David Silver |
+------------------+---------------------------------+
If I use two vertical bars (||), the server does not check that the name James has 5 characters and does not add 10 spaces to the field length (15).
If I use the CONCAT function, I see that the field length is not ignored and the server added 10 spaces to the name James.
I desire to create an index that will take the field length into account (how CONCAT does this).
To create the desired index, I tried to execute the following SQL query:
CREATE INDEX idx_table1_field1_field2 ON table1(CONCAT(field1, field2));
But I got the following error: ERROR: functions in index expression must be marked IMMUTABLE
Is there another way to create the such index?
character(n)in the first place? 15 is the field length if you choose character. If that's not what you want, usevarcharlike everyone else.characteris a red flag. You almost always wanttext. See postgresql.org/docs/current/datatype-character.htmlconcat. Or don't usechar. If you really need the padding, pad it yourself. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.