How to Use ENUM_FIRST() Function in PostgreSQL

PostgreSQL supports a custom data type known as “ENUM” that is used to define a fixed set of values for the table's column. Enums provide a secure and reliable way of controlling what data can be inserted into a table's column. PostgreSQL offers various built-in functions that help us manipulate the Enums data efficiently.

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

How to Use ENUM_FIRST() Function in PostgreSQL?

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

ENUM_FIRST(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_FIRST on the example_enum to get the first enum value of “example_enum”:

SELECT ENUM_FIRST(null::example_enum);

The output shows that the ENUM_FIRST() successfully retrieves the first 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_FIRST() function. As a result, the stated function will retrieve the following output:

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

The output shows that the ENUM_FIRST() function retrieves the first enumeration value:

img

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

Conclusion

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