Skip to content

Instantly share code, notes, and snippets.

@searls
Created August 20, 2014 20:01
Show Gist options
  • Save searls/cb5935f3a3c5e28c3814 to your computer and use it in GitHub Desktop.
Save searls/cb5935f3a3c5e28c3814 to your computer and use it in GitHub Desktop.
regex find-and-replace in Postgresql queries

Regex replacements in postgres

I had to make a simple change to all the strings in a table, and I was dreading having to load them into memory, iterate over them, searching for the string, and updating replacements. So instead, I learned that postgresql can actually do regex replacements in an update statement.

For example, if I have a links table with a url column with a bunch of URLs erroneously ending in "?":

Link.where("long_url like '%?'").count #=> 487185

Then I can strip the trailing ? from those records with this query:

ActiveRecord::Base.connection.execute(
  "update links set long_url = regexp_replace(long_url,'\\?$','') where long_url ~ '\\?$'"
)

The command completed in about 20 seconds. To verify:

Link.where("long_url like '%?'").count #=> 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment