# 8.7.枚举类型

8.7.1. 枚举类型的声明

8.7.2. 订购

8.7.3. 类型安全

8.7.4. 实施细节

枚举(enum)类型是包含一组静态有序值的数据类型。它们相当于枚举多种编程语言支持的类型。枚举类型的一个示例可能是一周中的几天,或者一段数据的一组状态值。

# 8.7.1.枚举类型的声明

枚举类型是使用创建类型命令,例如:

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

一旦创建,枚举类型可以在表和函数定义中使用,就像任何其他类型一样:

CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy');
CREATE TABLE person (
    name text,
    current_mood mood
);
INSERT INTO person VALUES ('Moe', 'happy');
SELECT * FROM person WHERE current_mood = 'happy';
 name | current_mood
### 8.7.2. Ordering

 The ordering of the values in an enum type is the order in which the values were listed when the type was created. All standard comparison operators and related aggregate functions are supported for enums. For example:

插入个人价值观(“拉里”、“悲伤”);在个人值中插入('Curly','ok');选择*来自当前情绪>悲伤的人;姓名|当前情绪

# 8.7.3.类型安全

每个枚举数据类型都是独立的,不能与其他枚举类型进行比较。看这个例子:

CREATE TYPE happiness AS ENUM ('happy', 'very happy', 'ecstatic');
CREATE TABLE holidays (
    num_weeks integer,
    happiness happiness
);
INSERT INTO holidays(num_weeks,happiness) VALUES (4, 'happy');
INSERT INTO holidays(num_weeks,happiness) VALUES (6, 'very happy');
INSERT INTO holidays(num_weeks,happiness) VALUES (8, 'ecstatic');
INSERT INTO holidays(num_weeks,happiness) VALUES (2, 'sad');
ERROR:  invalid input value for enum happiness: "sad"
SELECT person.name, holidays.num_weeks FROM person, holidays
  WHERE person.current_mood = holidays.happiness;
ERROR:  operator does not exist: mood = happiness

如果确实需要这样做,可以编写自定义运算符或向查询中添加显式强制转换:

SELECT person.name, holidays.num_weeks FROM person, holidays
  WHERE person.current_mood::text = holidays.happiness::text;
 name | num_weeks
### 8.7.4. Implementation Details

 Enum labels are case sensitive, so `'happy'` is not the same as `'HAPPY'`. White space in the labels is significant too.

 Although enum types are primarily intended for static sets of values, there is support for adding new values to an existing enum type, and for renaming values (see [ALTER TYPE](sql-altertype.html)). Existing values cannot be removed from an enum type, nor can the sort ordering of such values be changed, short of dropping and re-creating the enum type.

 An enum value occupies four bytes on disk. The length of an enum value's textual label is limited by the `NAMEDATALEN` setting compiled into PostgreSQL; in standard builds this means at most 63 bytes.

 The translations from internal enum values to textual labels are kept in the system catalog [`pg_enum`](catalog-pg-enum.html). Querying this catalog directly can be useful.