If genre types are in any way dynamic, i.e. you create new ones and rename old ones from time to time, or if you want to save additional information with every genre type, @mu's advice and @Marcello's implementation would be worth considering - except you should just use type text
instead of varchar(20)
and consider ON UPDATE CASCADE
for the fk constraint.
Other than that, here is the recipe you asked for:
DO
$$
BEGIN
EXECUTE (
SELECT format('CREATE TYPE genre_type AS ENUM (%s)'
,string_agg(DISTINCT quote_literal(genre), ', '))
FROM movies);
END
$$
You need dynamic SQL for that. The simple way is a DO
command (PostgreSQL 9.0+).
Make sure your strings are properly escaped with quote_literal()
.
I aggregate the string with string_agg()
(PostgreSQL 9.0+).
enum
for this? Wouldn't a simple FK to agenres
table work just as well? – mu is too short 8 hours ago