Skip to content

Instantly share code, notes, and snippets.

@jczaplew
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jczaplew/50fd66b158c4de479e7e to your computer and use it in GitHub Desktop.
Save jczaplew/50fd66b158c4de479e7e to your computer and use it in GitHub Desktop.
Postgres string matching in WHERE between two fields
CREATE TABLE pattern_test (field1 text, field2 text);
INSERT INTO pattern_test VALUES ('abc', '123 abc 546'), ('def', '123def546'), ('xyz', 'xyz something'), ('abo', 'something about something');
-- We want to find all records where field2 contains field1 as a distinct string (i.e. get records 0 and 2)
-- ~* is similar to ILIKE, but accepts a regular expression
-- '\y' will make sure that field1 is always a distinct object in field2
SELECT * FROM pattern_test WHERE field2 ~* concat('\y',field1,'\y');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment