Text functions

Topic 2 of 5 in Working with values10 min readBeginnerFree course

Overview

Text in a database is rarely in exactly the shape you need. Names arrive in odd capitals, emails need splitting into user and domain, codes need padding, and reports need tidy labels. SQL has a toolbox of text functions for all of this, and because they run inside the database, they work on every row at once.

Useful text functions with their results. lower(‘Asha’) gives ‘asha’. upper(‘pune’) gives ‘PUNE’. length(‘Chamomile’) gives 9. trim(’  tea  ’) gives ‘tea’. first_name || ’ ’ || last_name gives ‘Asha Rao’. concat_ws(’, ’, city, country) gives ‘Pune, India’. substring(‘Assam’ from 1 for 3) gives ‘Ass’. left(‘Darjeeling’, 4) gives ‘Darj’. replace(‘Tea Pot’, ’ ’, ‘’) gives ‘TeaPot’. split_part(‘a@b.com’, ‘@’, 2) gives ‘b.com’. position(‘@’ in ‘a@b.com’) gives 2. initcap(‘jasmine green’) gives ‘Jasmine Green’. || joins text, but anything || NULL is NULL; concat() and concat_ws() skip NULLs instead. String positions start at 1 in SQL, not 0.

A function is written as its name followed by arguments in brackets. Every example in the diagram is checked below.

Changing case

SQL
SELECT lower('Asha')            AS lower,
       upper('pune')            AS upper,
       initcap('jasmine green') AS initcap;
Text
 lower | upper |    initcap    
-------+-------+---------------
 asha  | PUNE  | Jasmine Green
(1 row)

initcap capitalises the first letter of each word. These are most useful for comparing text regardless of how it was typed — WHERE lower(email) = lower('Asha.Rao@Example.com') — and for consistent display.

Length and trimming

SQL
SELECT length('Chamomile')        AS chars,
       length('  tea  ')          AS with_spaces,
       trim('  tea  ')            AS trimmed,
       length(trim('  tea  '))    AS trimmed_length;
Text
 chars | with_spaces | trimmed | trimmed_length 
-------+-------------+---------+----------------
     9 |           7 | tea     |              3
(1 row)

trim removes spaces from both ends (ltrim and rtrim do one side each), and you can trim other characters too: trim(both '-' from '--tea--') gives tea. Stray spaces are a common reason why WHERE city = 'Pune' misses a row that “obviously” says Pune.

length counts characters, not bytes, so accented letters count once:

SQL
SELECT last_name, length(last_name) AS chars, octet_length(last_name) AS bytes
FROM customers
WHERE id = 5;
Text
 last_name | chars | bytes 
-----------+-------+-------
 García    |     6 |     7
(1 row)

“García” is six characters but seven bytes, because í takes two bytes in UTF-8.

Taking pieces: left, right, substring

SQL
SELECT left('Darjeeling', 4)                 AS left_4,
       right('Darjeeling', 4)                AS right_4,
       substring('Assam' from 1 for 3)       AS substring_1,
       substring('Assam Breakfast' from 7)   AS from_7;
Text
 left_4 | right_4 | substring_1 |  from_7   
--------+---------+-------------+-----------
 Darj   | ling    | Ass         | Breakfast
(1 row)

Positions start at 1 in SQL, not 0 as in most programming languages. substring(text from start for length) takes length characters from position start; leave out for to take everything to the end. PostgreSQL also accepts the shorter substr(text, start, length).

Finding and replacing

SQL
SELECT position('@' in 'a@b.com')         AS at_sign,
       replace('Tea Pot', ' ', '')         AS no_spaces,
       replace('Pour-Over', '-', ' ')      AS dash_to_space;
Text
 at_sign | no_spaces | dash_to_space 
---------+-----------+---------------
       2 | TeaPot    | Pour Over
(1 row)

position returns 0 when the text isn’t found. replace replaces every occurrence and is case-sensitive.

Splitting: split_part

split_part(text, delimiter, n) splits text on a delimiter and returns the nth piece — perfect for emails, codes and file paths:

SQL
SELECT email,
       split_part(email, '@', 1) AS user_name,
       split_part(email, '@', 2) AS domain
FROM customers
WHERE country = 'India';
Text
         email          | user_name  |   domain    
------------------------+------------+-------------
 asha.rao@example.com   | asha.rao   | example.com
 farhan.ali@example.com | farhan.ali | example.com
 isha.patel@example.com | isha.patel | example.com
(3 rows)

With a negative n, it counts from the end: split_part('a.b.c', '.', -1) is c.

Combining text: ||, concat and concat_ws

You met || in SELECT and columns. It has one sharp edge: anything joined to NULL is NULL. Building a contact line from a phone that might be missing goes wrong:

SQL
SELECT first_name,
       first_name || ' – ' || phone AS with_pipes
FROM customers
WHERE id IN (2, 3);
Text
 first_name |      with_pipes       
------------+-----------------------
 Ben        | Ben – +44 7700 900123
 Chen       | 
(2 rows)

Chen’s line has vanished entirely. concat treats NULL as empty text, and concat_ws (“with separator”) puts a separator between the pieces and skips NULLs:

SQL
SELECT first_name,
       concat(first_name, ' – ', phone) AS with_concat,
       concat_ws(', ', first_name, phone, city) AS with_concat_ws
FROM customers
WHERE id IN (2, 3);
Text
 first_name |      with_concat      |       with_concat_ws        
------------+-----------------------+-----------------------------
 Ben        | Ben – +44 7700 900123 | Ben, +44 7700 900123, Leeds
 Chen       | Chen –                | Chen, Singapore
(2 rows)

concat_ws is ideal for addresses and labels where some parts are optional — notice there’s no dangling comma where Chen’s phone would be.

Templates with format

format() fills a template with values: %s inserts a value as text, and %I / %L safely quote identifiers and literals when building SQL (useful later in your career):

SQL
SELECT format('%s %s lives in %s, %s.', first_name, last_name, city, country) AS sentence
FROM customers
WHERE id <= 3;
Text
                sentence                 
-----------------------------------------
 Asha Rao lives in Pune, India.
 Ben Carter lives in Leeds, UK.
 Chen Wei lives in Singapore, Singapore.
(3 rows)

Padding and repeating

lpad and rpad pad text to a fixed width — handy for codes and simple text reports:

SQL
SELECT lpad(id::text, 5, '0') AS order_code,
       rpad(status, 10, '.') || shipping_fee AS line
FROM orders
WHERE id IN (1, 21, 23);
Text
 order_code |      line      
------------+----------------
 00001      | delivered.4.99
 00021      | paid......6.50
 00023      | pending...0.00
(3 rows)

lpad needs text, so the integer id is cast with ::text first. repeat('-', 20) makes a line of 20 dashes.

Putting functions together

Functions can be nested: the output of one becomes the input of the next, evaluated from the inside out. Here’s a tidy product code built from the name and the id:

SQL
SELECT name,
       upper(left(replace(name, ' ', ''), 4)) || '-' || lpad(id::text, 3, '0') AS sku
FROM products
WHERE category_id = 2
ORDER BY name;
Text
          name          |   sku    
------------------------+----------
 Assam Breakfast        | ASSA-005
 Chamomile Calm         | CHAM-007
 Darjeeling First Flush | DARJ-004
 Jasmine Green          | JASM-006
(4 rows)

Read nested calls from the inside: remove spaces, take the first four characters, upper-case them, then append a dash and the zero-padded id.

Where to find more

PostgreSQL has dozens more text functions — reverse, starts_with, translate, md5, string_to_array, and the aggregate string_agg, which you’ll use in GROUP BY. In psql, \df *trim* lists every function with “trim” in its name, and the PostgreSQL documentation’s String Functions and Operators page is the full reference.

Other databases: the basics (upper, lower, trim, replace, substring) are standard. Names vary for the rest: SQL Server uses + and LEN, MySQL uses CONCAT and has no || by default, and split_part is PostgreSQL-specific (SQL Server has STRING_SPLIT, MySQL SUBSTRING_INDEX).

Exercise

Name badges and usernames

Bean & Leaf is printing name badges and creating accounts on a new support system. For every customer, sorted by id, return three columns: badge — the first name, a space, and the first letter of the last name followed by a full stop (for example Asha R.); username — the part of the email address before the @; and city_code — the first three letters of the city in capitals (for example PUN).

SQL
SELECT first_name,
       last_name,
       email,
       city
FROM customers
ORDER BY id;

Summary

  • Functions are called as name(arguments) and are evaluated for every row; they can be nested, like upper(left(city, 3)).
  • upper, lower and initcap change case; trim removes surrounding spaces; length counts characters.
  • left, right and substring take pieces; position finds text; replace and split_part rewrite and split it. Positions start at 1.
  • || joins text but returns NULL if any part is NULL; concat and concat_ws skip NULLs.
  • format() builds text from a template, and lpad/rpad or to_char line values up for display.