In my PostgreSQL 12.8 database, I have a relatively simple table the_table
with a column value
with type varchar
:
CREATE TABLE public.the_table (
id uuid DEFAULT gen_random_uuid() NOT NULL,
label character varying,
value character varying,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL,
);
I would like to query for all rows with a value that is formatted as an email address.
The query looks like this: SELECT * FROM the_table WHERE value ~ '^[a-zA-Z0-9.$%&*+/=?^_{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]+$'
.
As there are a several million rows in that table, I try to speed up this query by adding a matching expression index with CREATE INDEX index_the_table_on_email_values ON the_table ((value ~ '^[a-zA-Z0-9.$%&*+/=?^_{|}~-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9]+$'));
Unfortunately, the query planner does not utilize the index and performs a full scan on the table instead, which is very slow.
Can anybody help me fixing the index or tell me what other options I have?
I already considered a generated boolean column is_email
instead. I could add an index to that generated column and query it directly. But this seems like a weird workaround for the original problem, which should be solvable with a matching index, correct?
CREATE TABLE
script.