Sub topic 2
Extracting Parts, Finding Text, and Cleaning Strings in PostgreSQL
This chapter assumes you can write SELECT, WHERE and GROUP BY queries, know the basic PostgreSQL types, and can run queries in psql or another client.
PostgreSQL counts string positions from 1, not 0. The first character is position 1.
Extracting parts with substring, left and right
substring(text FROM start FOR length) returns part of a string. left(text, n) returns the first n characters, and right(text, n) returns the last n.
SELECT substring('PostgreSQL' FROM 1 FOR 8) AS part,
left('PostgreSQL', 4) AS first_four,
right('PostgreSQL', 3) AS last_three,
strpos('PostgreSQL', 'SQL') AS sql_position;This returns PostgreS, Post, SQL and 8.
Finding text with strpos and position
strpos(string, search) returns the 1-based position of the first match, or 0 when nothing matches. position(search IN string) does the same job with SQL-standard syntax. Both are case-sensitive.
Cleaning and padding with trim, lpad and rpad
trim(BOTH 'x' FROM s) removes a chosen character from both ends. lpad(s, n, fill) and rpad(s, n, fill) pad a string on the left or right until it reaches n characters. Padding never truncates, so a longer input keeps its full length.
Replacing text with replace, translate and overlay
replace(s, from, to) swaps every occurrence of a substring. translate(s, from, to) maps characters one by one. Characters in from with no partner in to are deleted. overlay(s placing new from n for k) replaces k characters starting at position n.
SELECT lpad('7', 3, '0') AS padded,
rpad('ab', 5, '.') AS dotted,
trim(BOTH 'x' FROM 'xxhixx') AS trimmed,
replace('a-b-c', '-', '/') AS replaced,
translate('12345', '143', 'ax') AS translated,
overlay('Txxxxas' placing 'hom' from 2 for 4) AS overlaid;This returns 007, ab..., hi, a/b/c, a2x5 and Thomas.
Exercise
What does lpad('42', 5, '0') return?
Show answer
00042. lpad adds the fill character on the left until the result has 5 characters.