2

I have the following enum and table:

CREATE TYPE public.event_type as ENUM (
  'eat_apple',
  'eat_banana',
  'brush_teeth'
);

CREATE TABLE public.events (
  id integer not null,
  type public.event_type,
  created_at timestamp without time zone
);

I have a lot of queries that I'm writing against this table that are only concerned with a subset of the event types (eat_apple and eat_banana).

I could write each of these queries with a WHERE type IN ('eat_banana', 'eat_apple') clause, however there's a high likelihood that in future, I'll need to add an eat_pear event type.

What are the available abstractions in Postgres for storing a subset of these enum values for reuse throughout queries, in a way where the subset can be extended in future, such that existing queries take this into account?

2 Answers 2

6

I would ditch the enum completely and make event_type a proper table that contains a flag if it's a "default" type.

create table event_type
(
  id integer primary key,
  name text not null unique,
  is_default_type boolean not null default true
);

create table events 
(
  id integer not null,
  type integer not null references event_type,
  created_at timestamp without time zone
);

To find those with the default subset you can do:

select e.*
from events e
  join event_type et on et.id = e.type and et.is_default_type;

To maintain the default subset, you just change the flag. For convenience you can create a view from the above query, so you never need to worry about the join.

If you create the view using an IN operator instead of the join it's also automatically updateable.

Sign up to request clarification or add additional context in comments.

2 Comments

You could use the enum as the primary key on the small table, that's what I do, it's fairly painless.
Do you think this is preferable to a function that returned the subset of type values? It feels more visible/discoverable, but maybe less ergonomic. Alternatively, maybe just a view would suffice without the event_type table abstraction!
2

You would use an array of type event_type[] and modify the query to the (equivalent)

WHERE type = ANY (array_value)

If you want to use a string constant, you could write

WHERE type = ANY ('{eat_banana,eat_apple}'::event_type[])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.