Replacing substrings in PostgreSQL text fields

Posted Aug 10, 2009 9:40:11 PM

In my previous post I made a small typo. I used the word 'direction' instead of 'directory'. Since I'd already tweeted a link to the post, deleting the entry and recreating it wasn't an option. So I did some quick digging into the PostgreSQL reference and found this handy function:

replace(string text, from text, to text)

This replaces all occurrences in string of substring from with substring to.

I used this to fix the typo in my blog post, by executing:

UPDATE entry 
SET content = replace(content, 'direction', 'directory)
WHERE ID=1401;

In the event that the word 'direction' had occurred multiple times in the post, I could have used a larger substring, such as the whole sentence, to identify the specific occurrence I wanted.

Popular Tags

Recent Stories

${recent.title}

About

My name is Tim Fanelli, I am a software engineer in Northern NY. I spend most of my time working, and when I can, I try to post interesting things here.

Cigar Dossiers