PostgreSQL ENUM: Creating and using custom enumerated types

Enumerated types, or ENUMs, in PostgreSQL provide a powerful way to incorporate controlled list values into database schemas, where a column is restricted to one of a set value of strings. By understanding how to effectively utilize ENUM types, you can ensure data integrity and facilitate clearer, more maintainable code. This article will guide you through creating and using custom ENUM types in PostgreSQL, demonstrating their versatility and reliability in database design.

Understanding ENUM Types in PostgreSQL

ENUM types are a datatype that comprises a static, ordered set of values. They are particularly useful when you know all possible values a column can contain at the database design time. Common practical examples of ENUM types include statuses, states, categories, and any other scenario where the value is restricted to a limited set of options.

Benefits of Using ENUM Types

Using ENUM types in PostgreSQL comes with distinct advantages such as:

  • Data Integrity: Since the value of ENUM types is restricted to the ones specified during its creation, this ensures that only valid data is stored in the database.
  • Readability: Using ENUM types makes your data models more understandable, as the ENUM values are self-explanatory (e.g., ‘red’, ‘green’, ‘blue’ for colors).
  • Performance: ENUMs are often more efficient than other types like text, especially for sorting, because they are internally stored as integers.

Limitations

Despite their benefits, ENUMs have some limitations:

  • Once created, altering an ENUM type can be cumbersome because you need to use special functions to add or rename values.
  • ENUM types are not standardized across different SQL databases, which may be a consideration if you plan to port your database.

Creating ENUM Types

Creating an ENUM type in PostgreSQL is straightforward. First, you must define the ENUM type, and then you can use it like any other datatype in your tables.

Example of Enum Type Creation


CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');

This SQL command creates a new ENUM type named mood with three possible values. You can check if the type exists and view its values using the following command:


\dT+ mood

Output:


                            List of data types
 schema | name |        internal_name        | size | elements  
--------+------+-----------------------------+------+----------
 public | mood | mood                        | 4    | sad
                                                  | ok
                                                  | happy

Using ENUM Types in Tables

Once you have created an ENUM type, you can use it in one or more table columns.

Example of Table with ENUM Column


CREATE TABLE person (
    name VARCHAR(100),
    current_mood mood
);

You can then insert data into this table, ensuring to use only the values defined in the ENUM type.


INSERT INTO person (name, current_mood) VALUES ('Sarah', 'happy');
INSERT INTO person (name, current_mood) VALUES ('John', 'sad');

Attempting to insert an undefined value into the ENUM column will result in an error, which speaks to the data integrity benefits discussed earlier.

Modifying ENUM Types

Modifying existing ENUM types involves using specific PostgreSQL functions since direct modification syntax is not supported.

Adding New Values

To add a new value to an existing ENUM type, you can use the ALTER TYPE command as shown below:


ALTER TYPE mood ADD VALUE 'excited' AFTER 'happy';

Output:


QUERY OK, 0 rows affected

Renaming Values

To rename a value, you need to use a series of SQL operations involving adding a new value, updating the column, and then removing the old value. This can be cumbersome and should be approached with care.

Best Practices and Conclusion

When using ENUM types, it’s important to carefully plan your values and remember that while ENUMs provide great benefits regarding readability and data integrity, they can restrict flexibility in cases where the values might change over time. Always ensure to use descriptive, clear, and meaningful values that will stand the test of time in your use case.

In conclusion, ENUM types in PostgreSQL offer a robust way to manage predefined lists in database columns, enhancing both the integrity and clarity of the database schema. By understanding how to effectively create and manipulate these types, developers can ensure cleaner and more secure databases.

About Editorial Team

Our Editorial Team is made up of tech enthusiasts who are highly skilled in Apache Spark, PySpark, and Machine Learning. They are also proficient in Python, Pandas, R, Hive, PostgreSQL, Snowflake, and Databricks. They aren't just experts; they are passionate teachers. They are dedicated to making complex data concepts easy to understand through engaging and simple tutorials with examples.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top