27

If I want to retrieve all entries such that the column foo value contains a string 'bar', is there a simple way to do this in SQL, or Postgresql?

Something like ' WHERE foo = "bar"' but instead of = it would be something like ' WHERE foo CONTAINS "bar"'.

Postgres Version 9.3

2
  • 3
    where foo like %bar%`' Commented May 21, 2015 at 15:21
  • alternatively: where strpos(foo, 'bar')? Commented May 21, 2015 at 15:22

2 Answers 2

43

Use the SQL LIKE statement. With that, you use a % as a wildcard. So, your WHERE statement could be something like:

WHERE foo LIKE '%bar%'
Sign up to request clarification or add additional context in comments.

Comments

22

One of:

  1. WHERE foo LIKE '%bar%'

  2. WHERE foo ILIKE '%bar%' --case insensitive

  3. WHERE foo ~* 'bar' --regex

  4. WHERE foo ~* '\ybar\y' --matches bar but not foobar (\y is word boundary)

  5. WHERE foo::tsvector @@ 'bar'::tsquery --matches bar but not foobar

You can index foo to make LIKE, ILIKE, and regexp searches faster: http://www.postgresql.org/docs/9.3/static/pgtrgm.html#AEN154464 Or use a GIN or GIST index on a full-text column

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.