Re: How to search ignoring spaces and minus signs

From: Grzegorz Jaśkiewicz <gryzman(at)gmail(dot)com>
To: Andrus <kobruleht2(at)hot(dot)ee>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to search ignoring spaces and minus signs
Date: 2010-10-14 01:35:15
Message-ID: AANLkTikttcomFaN2en=BgQr310oXn=TuTUAeHM0PDkNL@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

select regexp_replace(myval, E'(\\D)', '', 'g') from foo;

for added speed, you might consider this:
CREATE INDEX ON foo((regexp_replace(myval, E'(\\D)', '', 'g'))::bigint);

which is also going to protect you against inserts where value doesn't
contain any digits.

and added benefit of index:
gj=# select * from foo where (regexp_replace(myval::text,
'(\D)'::text, ''::text, 'g'::text)::bigint) = 5656;
id | myval
----+-------
61 | 56-56
(1 row)

Time: 1.356 ms
gj=# explain select * from foo where (regexp_replace(myval::text,
'(\D)'::text, ''::text, 'g'::text)::bigint) = 5656;
QUERY PLAN
---------------------------------------------------------------------------------------------------
Index Scan using foo_regexp_replace_idx on foo (cost=0.01..8.38
rows=1 width=17)
Index Cond: ((regexp_replace((myval)::text, '(\D)'::text, ''::text,
'g'::text))::bigint = 5656)
(2 rows)

gj=# \d+ foo
Table "public.foo"
Column | Type | Modifiers
| Storage | Description
--------+-----------------------+--------------------------------------------------+----------+-------------
id | integer | not null default
nextval('foo_id_seq'::regclass) | plain |
myval | character varying(20) | not null
| extended |
Indexes:
"foo_pkey" PRIMARY KEY, btree (id)
"foo_regexp_replace_idx" btree ((regexp_replace(myval::text,
'(\D)'::text, ''::text, 'g'::text)::bigint))
Has OIDs: no

or even create a view that would allow you to make it nice and easy:
gj=# CREATE VIEW foo_view AS select id, (regexp_replace(myval::text,
'(\D)'::text, ''::text, 'g'::text)::bigint) AS int_val FROM foo;
CREATE VIEW

gj=# select * from foo_view where int_val = 1212;
id | int_val
----+---------
17 | 1212
(1 row)

Time: 0.709 ms
gj=# explain select * from foo_view where int_val = 1212;
QUERY PLAN
---------------------------------------------------------------------------------------------------
Index Scan using foo_regexp_replace_idx on foo (cost=0.01..8.39
rows=1 width=17)
Index Cond: ((regexp_replace((myval)::text, '(\D)'::text, ''::text,
'g'::text))::bigint = 1212)
(2 rows)

HTH

--
GJ

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Gauthier, Dave 2010-10-14 02:28:39 Re: Adding a New Column Specifically In a Table
Previous Message Christian Ramseyer 2010-10-14 01:24:12 Re: How to search ignoring spaces and minus signs