apps/docs/content/guides/database/postgres/enums.mdx
Enums in Postgres are a custom data type. They allow you to define a set of values (or labels) that a column can hold. They are useful when you have a fixed set of possible values for a column.
You can define a Postgres Enum using the create type statement. Here's an example:
create type mood as enum (
'happy',
'sad',
'excited',
'calm'
);
In this example, we've created an Enum called "mood" with four possible values.
There is a lot of overlap between Enums and foreign keys. Both can be used to define a set of values for a column. However, there are some advantages to using Enums:
There are also some disadvantages to using Enums:
In general you should only use Enums when the list of values is small, fixed, and unlikely to change often. Things like "a list of continents" or "a list of departments" are good candidates for Enums.
To use the Enum in a table, you can define a column with the Enum type. For example:
create table person (
id serial primary key,
name text,
current_mood mood
);
Here, the current_mood column can only have values from the "mood" Enum.
You can insert data into a table with Enum columns by specifying one of the Enum values:
insert into person
(name, current_mood)
values
('Alice', 'happy');
When querying data, you can filter and compare Enum values as usual:
select *
from person
where current_mood = 'sad';
You can manage your Enums using the alter type statement. Here are some examples:
You can update the value of an Enum column:
update person
set current_mood = 'excited'
where name = 'Alice';
To add new values to an existing Postgres Enum, you can use the ALTER TYPE statement. Here's how you can do it:
Let's say you have an existing Enum called mood, and you want to add a new value, content:
alter type mood add value 'content';
Even though it is possible, it is unsafe to remove enum values once they have been created. It's better to leave the enum value in place.
<Admonition type="caution">Read the Postgres mailing list for more information:
There is no ALTER TYPE DELETE VALUE in Postgres. Even if you delete every occurrence of an Enum value within a table (and vacuumed away those rows), the target value could still exist in upper index pages. If you delete the pg_enum entry you'll break the index.
Check your existing Enum values by querying the enum_range function:
select enum_range(null::mood);