What Does ENUM_LAST() Function Do in PostgreSQL?

PostgreSQL offers various built-in functions to manipulate the Enums data efficiently, such as ENUM_FIRST(), ENUM_LAST(), and ENUM_RANGE(). All these functions serve a specific purpose. For instance, the ENUM_FIRST() function retrieves the first value of the enum, the ENUM_LAST() function retrieves the last value of the enum, and ENUM_RANGE() retrieves the enumeration values within the specified range.

This post will illustrate the working of the ENUM_LAST() function using practical examples.

What Does ENUM_LAST() Function Do in PostgreSQL?

The ENUM_LAST() is a built-in function in Postgres that retrieves the last value of the enum specified by the parameter. Use the below-provided syntax to apply the ENUM_LAST() function on the enum type:

ENUM_LAST(enum_value ENUM);

Here, enum_val is a mandatory parameter that represents an enumeration value.

Example: Using ENUM_FIRST() in Postgres

First, let’s create an enum type named “example_enum” using the below-provided statement:

CREATE TYPE example_enum AS ENUM (
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
);

In the above code snippet, we utilized the CREATE TYPE to create an enum type that contains month names of the year:

img

Now, we will invoke the ENUM_LAST on the example_enum to get the last enum value of “example_enum”:

SELECT ENUM_LAST(null::example_enum);

The output shows that the ENUM_LAST() successfully retrieves the last enum value of the example_enum:

img

In the following code snippet, we will pass all enumeration values ​​of type example_enum to the ENUM_LAST() function. As a result, the stated function will retrieve the following output:

SELECT ENUM_LAST('Jan'::example_enum),
ENUM_LAST('Feb'::example_enum),
ENUM_LAST('Mar'::example_enum),
ENUM_LAST('Apr'::example_enum),
ENUM_LAST('May'::example_enum),
ENUM_LAST('Jun'::example_enum),
ENUM_LAST('Jul'::example_enum),
ENUM_LAST('Aug'::example_enum),
ENUM_LAST('Sep'::example_enum),
ENUM_LAST('Oct'::example_enum),
ENUM_LAST('Nov'::example_enum),
ENUM_LAST('Dec'::example_enum);

The output shows that the ENUM_LAST() function retrieves the last enumeration value:

img

This is how the ENUM_LAST() function works in Postgres.

Conclusion

The ENUM_LAST() is a built-in function in Postgres that retrieves the last value of the enum specified by the parameter. It accepts a mandatory parameter “enum_val” that represents an enumeration value and retrieves the last value of the selected enum. This blog post demonstrated the use of the ENUM_LAST() function in PostgreSQL using practical examples.