String Functions

Updated · 8 min read
easyPostgreSQL 18sqlstring-functionsconcatsubstringtrimtext

String functions take text and return changed text, or facts about it: its length, where a word appears, a piece cut out of it. Reports rarely show text exactly as it's stored. A receipt wants R-00007, not 7; a greeting wants "Navika Anamaneni", built from two columns; a cleanup job wants spaces trimmed and phone numbers reduced to digits. This lesson covers the everyday string functions, with real Fee Tracker results, the trap of joining text with NULL, and a table of names across databases, because string functions are where databases differ most.

In One Minute

  • length, upper, lower and trim measure, change case and remove surrounding spaces.
  • a || b joins text; any NULL makes the whole result NULL. concat() and concat_ws() skip NULLs.
  • substring(text, start, count), left, right and split_part cut pieces out; positions start at 1.
  • position('x' IN text) finds a piece; replace(text, old, new) swaps every occurrence.
  • lpad and rpad pad to a fixed width, as in lpad('7', 5, '0') giving 00007.

Length and Case

SQL▶ Try it
SELECT first_name,
       length(first_name) AS letters,
       upper(first_name)  AS upper_case,
       lower(first_name)  AS lower_case
FROM students
ORDER BY student_id;
Output
 first_name | letters | upper_case | lower_case
------------+---------+------------+------------
 Srihitha   |       8 | SRIHITHA   | srihitha
 Advitha    |       7 | ADVITHA    | advitha
 Navika     |       6 | NAVIKA     | navika
(3 rows)

length counts characters. upper and lower are the standard way to compare text without caring about case: WHERE upper(first_name) = 'NAVIKA' matches however the name was typed. initcap('navika anamaneni') capitalizes each word (PostgreSQL and Oracle).

Joining Text

|| joins text in standard SQL, but one NULL makes the whole result NULL. concat treats NULL as empty instead:

SQL▶ Try it
SELECT first_name || ' ' || email     AS with_pipes,
       concat(first_name, ' ', email) AS with_concat
FROM students
ORDER BY student_id;
Output
               with_pipes                |               with_concat
-----------------------------------------+-----------------------------------------
 Srihitha srihitha.anamaneni@example.com | Srihitha srihitha.anamaneni@example.com
 NULL                                    | Advitha
 NULL                                    | Navika
(3 rows)

Advitha and Navika have no email, so || gives NULL for them, while concat just leaves the email out. concat_ws ("with separator") goes further: it puts the separator between the values and skips NULLs entirely, so no stray separators appear:

SQL▶ Try it
SELECT concat_ws(', ', city, state)    AS place,
       concat_ws(' / ', email, phone)  AS contacts
FROM students
ORDER BY student_id;
Output
       place       |                    contacts
-------------------+-------------------------------------------------
 San Francisco, CA | srihitha.anamaneni@example.com / (415) 555-0142
 San Francisco, CA | (415) 555-0178
 Dallas, TX        |
(3 rows)

Advitha gets just her phone, with no dangling " / ", and Navika gets an empty string.

|| turns the whole result NULL when the email is missing; concat and concat_ws skip it

Trimming Spaces

trim removes spaces from both ends; ltrim and rtrim from one end. Stray spaces from forms and spreadsheets make 'Navika ' and 'Navika' different values:

SQL▶ Try it
SELECT '  Navika  '        AS raw,
       trim('  Navika  ')  AS trimmed,
       length(trim('  Navika  ')) AS letters;
Output
    raw     | trimmed | letters
------------+---------+---------
   Navika   | Navika  |       6
(1 row)

Cutting Pieces Out

Positions in SQL strings start at 1, not 0. substring(text, start, count) takes count characters starting at start; left and right take from either end:

SQL▶ Try it
SELECT title,
       left(title, 4)       AS first_four,
       right(title, 6)      AS last_six,
       substring(title, 6, 3) AS from_sixth
FROM courses
ORDER BY course_id
LIMIT 3;
Output
      title       | first_four | last_six | from_sixth
------------------+------------+----------+------------
 Java Basics      | Java       | Basics   | Bas
 Java OOP         | Java       | va OOP   | OOP
 Java Collections | Java       | ctions   | Col
(3 rows)

position('x' IN text) finds where a piece starts, or 0 if it isn't there. Together with substring, it splits an email at the @. PostgreSQL's split_part does the same in one step:

SQL▶ Try it
SELECT email,
       substring(email FROM 1 FOR position('@' IN email) - 1) AS user_name,
       split_part(email, '@', 2) AS domain
FROM students
WHERE email IS NOT NULL;
Output
             email              |     user_name      |   domain
--------------------------------+--------------------+-------------
 srihitha.anamaneni@example.com | srihitha.anamaneni | example.com
(1 row)
Positions start at 1: the @ is at position 19, so the user name is characters 1 to 18

Replacing and Padding

replace(text, old, new) swaps every occurrence of old:

SQL▶ Try it
SELECT title, replace(title, 'Basics', 'Fundamentals') AS renamed
FROM courses
WHERE title LIKE '%Basics'
ORDER BY course_id;
Output
       title       |         renamed
-------------------+-------------------------
 Java Basics       | Java Fundamentals
 SQL Basics        | SQL Fundamentals
 JavaScript Basics | JavaScript Fundamentals
 Git Basics        | Git Fundamentals
(4 rows)

lpad(text, width, fill) pads on the left to a fixed width, perfect for receipt numbers:

SQL▶ Try it
SELECT payment_id, 'R-' || lpad(payment_id::text, 5, '0') AS receipt
FROM payments
ORDER BY payment_id;
Output
 payment_id | receipt
------------+---------
          1 | R-00001
          2 | R-00002
          3 | R-00003
          4 | R-00004
          5 | R-00005
          6 | R-00006
          7 | R-00007
(7 rows)

payment_id is a number, so ::text turns it into text first. rpad pads on the right. For pattern-based changes, regexp_replace is more powerful: regexp_replace(phone, '[^0-9]', '', 'g') keeps only the digits of (415) 555-0142.

The Same Functions in Other Databases

TaskPostgreSQLMySQLSQL ServerOracle
Lengthlength(s)CHAR_LENGTH(s)LEN(s)LENGTH(s)
Joins1 || s2, concat()CONCAT() (|| is OR)s1 + s2, CONCAT()s1 || s2, CONCAT()
Piecesubstring(s, 1, 3)SUBSTRING(s, 1, 3)SUBSTRING(s, 1, 3)SUBSTR(s, 1, 3)
Findposition('x' IN s)LOCATE('x', s)CHARINDEX('x', s)INSTR(s, 'x')
Trimtrim(s)TRIM(s)TRIM(s) (2017+)TRIM(s)

Two traps: in MySQL, || means logical OR by default, not concatenation; and in Oracle, an empty string '' is NULL. Tabs showing each database's version are coming to this course.

Length and find-a-piece in PostgreSQL, MySQL, SQL Server and Oracle

Common Mistakes

Joining with || when a value can be NULL. The whole result becomes NULL. Use concat or concat_ws.

Counting from 0. substring(title, 0, 3) returns only two characters. Positions start at 1.

Padding a number. lpad(payment_id, 5, '0') fails; convert first with payment_id::text.

Comparing with different case or spaces. 'navika' isn't 'Navika '. Use lower(trim(...)) on both sides.

Interview Corner

What's the difference between || and CONCAT in PostgreSQL?

Both join text, but || returns NULL if any part is NULL, while concat() treats NULL as an empty string. concat_ws() also adds a separator and skips NULLs.

How do you extract the domain from an email address?

split_part(email, '@', 2) in PostgreSQL, or substring(email FROM position('@' IN email) + 1) in standard SQL.

Do SQL string positions start at 0 or 1?

At 1. The first character is position 1, and position() returns 0 when the text isn't found.

Practice

Challenge: Build a label for each student: their full name, then their city and state in parentheses, such as Navika Anamaneni (Dallas, TX). Sort by student_id.

Show solution
SQL▶ Try it
SELECT concat(first_name, ' ', last_name, ' (', city, ', ', state, ')') AS label
FROM students
ORDER BY student_id;
Output
                 label
----------------------------------------
 Srihitha Anamaneni (San Francisco, CA)
 Advitha Anamaneni (San Francisco, CA)
 Navika Anamaneni (Dallas, TX)
(3 rows)

None of these columns can be NULL, so || would work too; concat is the habit that stays safe if that ever changes.

Quick check: String functions

3 questions
1Advitha has no email. What is first_name || ' ' || email for her?
2What does substring('Navika', 1, 3) return?
3Which builds R-00007 from payment_id 7?

Key Takeaways

You want toWrite
Full nameconcat(first_name, ' ', last_name)
List with separatorsconcat_ws(', ', city, state)
Email domainsplit_part(email, '@', 2)
Receipt number'R-' || lpad(payment_id::text, 5, '0')
Case-insensitive matchWHERE lower(first_name) = 'navika'

Was this tutorial helpful?

Lesson 51 of 115