String Functions
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,lowerandtrimmeasure, change case and remove surrounding spaces.a || bjoins text; anyNULLmakes the whole resultNULL.concat()andconcat_ws()skipNULLs.substring(text, start, count),left,rightandsplit_partcut pieces out; positions start at 1.position('x' IN text)finds a piece;replace(text, old, new)swaps every occurrence.lpadandrpadpad to a fixed width, as inlpad('7', 5, '0')giving00007.
Length and Case
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; 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:
SELECT first_name || ' ' || email AS with_pipes,
concat(first_name, ' ', email) AS with_concat
FROM students
ORDER BY student_id; 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:
SELECT concat_ws(', ', city, state) AS place,
concat_ws(' / ', email, phone) AS contacts
FROM students
ORDER BY student_id; 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.
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:
SELECT ' Navika ' AS raw,
trim(' Navika ') AS trimmed,
length(trim(' Navika ')) AS letters; 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:
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; 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:
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; email | user_name | domain
--------------------------------+--------------------+-------------
srihitha.anamaneni@example.com | srihitha.anamaneni | example.com
(1 row)Replacing and Padding
replace(text, old, new) swaps every occurrence of old:
SELECT title, replace(title, 'Basics', 'Fundamentals') AS renamed
FROM courses
WHERE title LIKE '%Basics'
ORDER BY course_id; 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:
SELECT payment_id, 'R-' || lpad(payment_id::text, 5, '0') AS receipt
FROM payments
ORDER BY payment_id; 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
| Task | PostgreSQL | MySQL | SQL Server | Oracle |
|---|---|---|---|---|
| Length | length(s) | CHAR_LENGTH(s) | LEN(s) | LENGTH(s) |
| Join | s1 || s2, concat() | CONCAT() (|| is OR) | s1 + s2, CONCAT() | s1 || s2, CONCAT() |
| Piece | substring(s, 1, 3) | SUBSTRING(s, 1, 3) | SUBSTRING(s, 1, 3) | SUBSTR(s, 1, 3) |
| Find | position('x' IN s) | LOCATE('x', s) | CHARINDEX('x', s) | INSTR(s, 'x') |
| Trim | trim(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.
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
SELECT concat(first_name, ' ', last_name, ' (', city, ', ', state, ')') AS label
FROM students
ORDER BY student_id; 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.
Key Takeaways
| You want to | Write |
|---|---|
| Full name | concat(first_name, ' ', last_name) |
| List with separators | concat_ws(', ', city, state) |
| Email domain | split_part(email, '@', 2) |
| Receipt number | 'R-' || lpad(payment_id::text, 5, '0') |
| Case-insensitive match | WHERE lower(first_name) = 'navika' |
Was this tutorial helpful?