List enum types and their values
Postgres enum types carry their allowed values in the catalog, and MySQL enums carry them inline on each column. This recipe lists every enum with its values.
The task
The application and the schema disagree about which status values are legal, so list what each enum actually permits before adding the next one.
The snippet
Written for PostgreSQL. Versions for MySQL are under Variations.
SELECT t.typname AS enum_name,
string_agg(e.enumlabel, ', ' ORDER BY e.enumsortorder) AS allowed_values
FROM pg_type t
JOIN pg_enum e ON e.enumtypid = t.oid
JOIN pg_namespace n ON n.oid = t.typnamespace
WHERE n.nspname = 'public'
GROUP BY t.typname
ORDER BY t.typname;
So funktioniert es
pg_enum stores one row per allowed value of each enum type. enumsortorder is the position in the type, which is also its sort order: ORDER BY status sorts by that position, not alphabetically, and ALTER TYPE ... ADD VALUE ... BEFORE can slot a new value into the middle. To find the columns that use an enum, match its name against udt_name in information_schema.columns, as the second variant does.
Variations
MySQL
MySQLSELECT table_name, column_name, column_type
FROM information_schema.columns
WHERE table_schema = 'mydb' AND data_type = 'enum'
ORDER BY table_name, column_name;
-- column_type holds the full enum('a','b','c') list
PostgreSQL: where an enum is used
PostgreSQLSELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public'
AND udt_name = 'order_status'
ORDER BY table_name;
PostgreSQL: domains and their rules
PostgreSQLSELECT t.typname AS domain_name,
format_type(t.typbasetype, t.typtypmod) AS base_type,
t.typnotnull AS not_null,
pg_get_constraintdef(c.oid) AS rule
FROM pg_type t
JOIN pg_namespace n ON n.oid = t.typnamespace
LEFT JOIN pg_constraint c ON c.contypid = t.oid
WHERE t.typtype = 'd' AND n.nspname = 'public'
ORDER BY t.typname;
Questions that come up
Can I remove a value from an enum?
Not in place on PostgreSQL: there is no ALTER TYPE ... DROP VALUE, so you create a new type without the value, move the columns to it with ALTER COLUMN ... TYPE ... USING, and drop the old type. MySQL takes a MODIFY COLUMN with the shorter list, which rebuilds the table and fails in strict mode if any row still holds the removed value. For value sets that change often, a lookup table with a foreign key is easier to maintain.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.