Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of defining an operator class when defining index in postgres?

Tags:

postgresql

For example

CREATE INDEX my_index_name
    ON public.my_table USING btree
    (my_column  int8_ops)
    TABLESPACE pg_default;

vs

CREATE INDEX my_index_name
    ON public.my_table USING btree
    (my_column)
    TABLESPACE pg_default;

What is the difference?

like image 744
Jal Avatar asked Jan 21 '18 22:01

Jal


People also ask

What is operator class in index PostgreSQL?

The operator class identifies the operators to be used by the index for that column. For example, a B-tree index on the type int4 would use the int4_ops class; this operator class includes comparison functions for values of type int4 .

What is operator in PostgreSQL?

An operator is a reserved word or a character used primarily in a PostgreSQL statement's WHERE clause to perform operation(s), such as comparisons and arithmetic operations. Operators are used to specify conditions in a PostgreSQL statement and to serve as conjunctions for multiple conditions in a statement.

What is Varchar_pattern_ops?

The varchar_pattern_ops improves the performance of like queries by 4 times i.e 4x. For example, lets have this like query on name column (that has sequential index.) Select * from users where name like 'John%' We might have added a regular Rails index in migration for this name column as.


1 Answers

As much as I dislike quoting verbatim, I think what is written in the manual describes it most correctly and succintly, and I doubt I could do better:

The operator class identifies the operators to be used by the index for that column. For example, a B-tree index on the type int4 would use the int4_ops class; this operator class includes comparison functions for values of type int4. In practice the default operator class for the column's data type is usually sufficient. The main reason for having operator classes is that for some data types, there could be more than one meaningful index behavior. For example, we might want to sort a complex-number data type either by absolute value or by real part. We could do this by defining two operator classes for the data type and then selecting the proper class when making an index. The operator class determines the basic sort ordering (which can then be modified by adding sort options COLLATE, ASC/DESC and/or NULLS FIRST/NULLS LAST).


As for your example, if my_column is defined as type int8, then specifying the operator class as int8_ops is moot, as that would be the default operator for that type.

like image 66
e_i_pi Avatar answered Sep 28 '22 07:09

e_i_pi