Course contentsShow
← Databases & SQL
Lesson 898 of 1,9538. PostgreSQL InternalsFree lesson

Operator Classes and Families

You will associate custom functions with index types to enable efficient searching on non-standard data.

In this lesson, you will learn how to teach PostgreSQL how to index your custom data types by defining operator classes and families.

Bridging the Gap Between Types and Indexes

When you create a custom data type (like a complex geometric shape or a specialized encrypted string), PostgreSQL doesn't automatically know how to order or compare it for an index. An INDEX is essentially a map, but if the database doesn't know how to navigate the terrain of your data, it defaults to a slow sequential scan.

This is where Operator Classes (opclass) and Operator Families (opfamily) come into play. They act as the "instruction manual" for an index method (like B-Tree or GIN) on how to interact with your specific data type.

The Mechanics of an Opclass

An operator class defines which operators an index can use for a specific data type. For example, if you have a currency type, you need to tell the B-Tree index which functions represent "less than," "greater than," and "equal to."

CREATE OPERATOR CLASS currency_ops
DEFAULT FOR TYPE currency USING btree AS
    OPERATOR 1 < ,
    OPERATOR 2 <= ,
    OPERATOR 3 = ,
    OPERATOR 4 >= ,
    OPERATOR 5 > ,
    FUNCTION 1 currency_cmp(currency, currency);

Organizing with Operator Families

While an operator class is tied to a specific data type, an Operator Family allows you to group multiple, related operator classes together. This is crucial for cross-type operations. For instance, if you want to be able to compare your currency type with a standard numeric type using an index, you would add both types to the same operator family. This allows the index to perform "cross-type" lookups, drastically reducing query times by avoiding unnecessary type casting.

By mapping your custom functions (like currency_cmp) to these standardized slots (like FUNCTION 1 for comparisons), you provide the query planner with a clear map of how to traverse your data. Once defined, you can simply run CREATE INDEX my_idx ON my_table USING btree (my_col currency_ops);, and the database will handle the rest with native-level efficiency.

Key Takeaway: Operator classes define how a specific type behaves in an index, while operator families allow those rules to extend across different types for high-performance indexing.