๐Ÿ”ค String Functions

Real-world text is messy: extra spaces, random capital letters, phone numbers in five different formats. Spark SQL has a large set of string functions to clean, split, search and reshape text, and this tutorial walks through the ones you will use most.

Every query below runs on Spark 3.5 and shows its exact result.


1. Sample Data

This tutorial uses a small customers view with deliberately messy values, typed in by hand the way real sign-up forms often are:

CREATE OR REPLACE TEMP VIEW customers AS
SELECT * FROM VALUES
  (1, '  asha RAO ', 'Asha.Rao@Gmail.com',  '98450-12345',     'Bengaluru'),
  (2, 'ben  thomas', 'ben.t@yahoo.co.in',   '(022) 2345 6789', 'Mumbai'),
  (3, 'CHEN li',     NULL,                  '+91 99001 22334', 'Pune'),
  (4, 'divya',       'divya@company.com ',  '9845012345',      NULL)
AS customers(cust_id, full_name, email, phone, city)
SELECT * FROM customers ORDER BY cust_id
+-------+-----------+------------------+---------------+---------+
|cust_id|full_name  |email             |phone          |city     |
+-------+-----------+------------------+---------------+---------+
|1      |  asha RAO |Asha.Rao@Gmail.com|98450-12345    |Bengaluru|
|2      |ben  thomas|ben.t@yahoo.co.in |(022) 2345 6789|Mumbai   |
|3      |CHEN li    |NULL              |+91 99001 22334|Pune     |
|4      |divya      |divya@company.com |9845012345     |NULL     |
+-------+-----------+------------------+---------------+---------+

Notice the problems: leading and trailing spaces, a double space in "ben thomas", mixed case, a trailing space after Divya's email, and four different phone formats. By the end of this tutorial you will fix all of them in one query.


2. Changing Case: upper, lower, initcap

FunctionWhat it does
upper(s)ALL CAPS
lower(s)all lowercase
initcap(s)First Letter Of Each Word In Capitals
SELECT full_name,
       upper(full_name)   AS upper_name,
       lower(full_name)   AS lower_name,
       initcap(full_name) AS initcap_name
FROM customers
ORDER BY cust_id
+-----------+-----------+-----------+------------+
|full_name  |upper_name |lower_name |initcap_name|
+-----------+-----------+-----------+------------+
|  asha RAO |  ASHA RAO |  asha rao |  Asha Rao  |
|ben  thomas|BEN  THOMAS|ben  thomas|Ben  Thomas |
|CHEN li    |CHEN LI    |chen li    |Chen Li     |
|divya      |DIVYA      |divya      |Divya       |
+-----------+-----------+-----------+------------+

initcap capitalises the first letter of every word and lowercases the rest, so "CHEN li" becomes "Chen Li". It does not remove the extra spaces; that is the job of the trim functions.

Tip: To compare text without caring about case, lower both sides: WHERE lower(email) = 'asha.rao@gmail.com'.


3. Length and Trimming: length, trim, ltrim, rtrim

length counts characters, including spaces. The trim functions remove spaces from the ends of a string:

  • trim(s) removes spaces from both ends.
  • ltrim(s) removes them from the left (start) only.
  • rtrim(s) removes them from the right (end) only.

The brackets in this query make the spaces visible:

SELECT concat('[', full_name, ']')        AS original,
       length(full_name)                  AS len,
       concat('[', trim(full_name), ']')  AS trimmed,
       concat('[', ltrim(full_name), ']') AS left_trimmed,
       concat('[', rtrim(full_name), ']') AS right_trimmed
FROM customers
ORDER BY cust_id
+-------------+---+-------------+-------------+-------------+
|original     |len|trimmed      |left_trimmed |right_trimmed|
+-------------+---+-------------+-------------+-------------+
|[  asha RAO ]|11 |[asha RAO]   |[asha RAO ]  |[  asha RAO] |
|[ben  thomas]|11 |[ben  thomas]|[ben  thomas]|[ben  thomas]|
|[CHEN li]    |7  |[CHEN li]    |[CHEN li]    |[CHEN li]    |
|[divya]      |5  |[divya]      |[divya]      |[divya]      |
+-------------+---+-------------+-------------+-------------+

" asha RAO " has 11 characters, but only 8 of them ("asha RAO") are the name itself. trim only touches the ends, so the double space inside "ben thomas" stays. To collapse repeated spaces inside a string you need regexp_replace, covered in section 9.

Common mistake: Joining or grouping on untrimmed text. 'Mumbai' and 'Mumbai ' are different strings, so a join on them silently finds no match. Trim keys while you load the data.


4. Joining Strings: concat, concat_ws and ||

There are three ways to glue strings together, and they treat NULL differently:

SELECT cust_id,
       concat(trim(full_name), ' - ', city)    AS with_concat,
       trim(full_name) || ' - ' || city        AS with_pipes,
       concat_ws(' - ', trim(full_name), city) AS with_concat_ws
FROM customers
ORDER BY cust_id
+-------+--------------------+--------------------+--------------------+
|cust_id|with_concat         |with_pipes          |with_concat_ws      |
+-------+--------------------+--------------------+--------------------+
|1      |asha RAO - Bengaluru|asha RAO - Bengaluru|asha RAO - Bengaluru|
|2      |ben  thomas - Mumbai|ben  thomas - Mumbai|ben  thomas - Mumbai|
|3      |CHEN li - Pune      |CHEN li - Pune      |CHEN li - Pune      |
|4      |NULL                |NULL                |divya               |
+-------+--------------------+--------------------+--------------------+

Divya has no city, and that changes everything:

  • concat(...) and || return NULL if any input is NULL. Divya's whole value disappears.
  • concat_ws(separator, ...) ("concat with separator") skips NULL inputs, so you still get "divya".

Use concat_ws when some parts may be missing, such as building an address from optional fields. It is also less typing, because you write the separator once.


5. Extracting Parts: substring, left, right

substring(s, start, length) returns part of a string. Positions start at 1, not 0. A negative start counts from the end.

SELECT phone,
       substring(phone, 1, 5)  AS first_five,
       substring(phone, -5, 5) AS last_five,
       substring(phone, 4)     AS from_fourth,
       left(phone, 3)          AS left_three,
       right(phone, 4)         AS right_four
FROM customers
ORDER BY cust_id
+---------------+----------+---------+------------+----------+----------+
|phone          |first_five|last_five|from_fourth |left_three|right_four|
+---------------+----------+---------+------------+----------+----------+
|98450-12345    |98450     |12345    |50-12345    |984       |2345      |
|(022) 2345 6789|(022)     | 6789    |2) 2345 6789|(02       |6789      |
|+91 99001 22334|+91 9     |22334    | 99001 22334|+91       |2334      |
|9845012345     |98450     |12345    |5012345     |984       |2345      |
+---------------+----------+---------+------------+----------+----------+
  • substring(phone, 1, 5) takes characters 1 to 5.
  • substring(phone, -5, 5) starts 5 characters from the end.
  • Leaving out the length, as in substring(phone, 4), takes everything from position 4 to the end.
  • left(s, n) and right(s, n) are shortcuts for the first or last n characters.

substr is another name for substring and works the same way.

Common mistake: Using position 0. In Spark SQL, substring('Spark', 0, 2) behaves like a start of 1 and returns Sp, which hides the bug. Always count from 1 in SQL.


6. Finding Text: instr and locate

Both functions return the position of a substring, or 0 when it is not found:

  • instr(string, substring) puts the string first.
  • locate(substring, string) puts the substring first, and takes an optional start position.

A common use is splitting an email at the @:

SELECT email,
       instr(email, '@')                         AS at_position,
       locate('@', email)                        AS same_with_locate,
       substring(email, 1, instr(email, '@') - 1) AS username,
       substring(email, instr(email, '@') + 1)    AS domain
FROM customers
WHERE email IS NOT NULL
ORDER BY cust_id
+------------------+-----------+----------------+--------+------------+
|email             |at_position|same_with_locate|username|domain      |
+------------------+-----------+----------------+--------+------------+
|Asha.Rao@Gmail.com|9          |9               |Asha.Rao|Gmail.com   |
|ben.t@yahoo.co.in |6          |6               |ben.t   |yahoo.co.in |
|divya@company.com |6          |6               |divya   |company.com |
+------------------+-----------+----------------+--------+------------+

The username is everything before the @, and the domain is everything after it. Because instr returns 0 when the substring is missing, check for that before slicing strings that might not contain it.


7. Replacing and Padding: replace, lpad, rpad

replace(s, search, replacement) swaps every exact occurrence of search. lpad and rpad pad a string to a fixed length on the left or right:

SELECT cust_id,
       replace(phone, '-', '')            AS no_dashes,
       lpad(cast(cust_id AS STRING), 5, '0') AS padded_id,
       concat('C', lpad(cust_id, 4, '0'))  AS customer_code,
       rpad(trim(full_name), 12, '.')      AS dotted_name
FROM customers
ORDER BY cust_id
+-------+---------------+---------+-------------+------------+
|cust_id|no_dashes      |padded_id|customer_code|dotted_name |
+-------+---------------+---------+-------------+------------+
|1      |9845012345     |00001    |C0001        |asha RAO....|
|2      |(022) 2345 6789|00002    |C0002        |ben  thomas.|
|3      |+91 99001 22334|00003    |C0003        |CHEN li.....|
|4      |9845012345     |00004    |C0004        |divya.......|
+-------+---------------+---------+-------------+------------+

lpad(cust_id, 4, '0') is a common way to build fixed-width codes like C0001. Spark converts the number to a string for you, so the explicit cast in padded_id is optional.

If the string is already longer than the target length, lpad and rpad cut it to that length instead of leaving it alone. Pick a length that fits your longest value.


8. Splitting: split, [index] and element_at

split(s, pattern) breaks a string into an array. You then pick elements out of the array:

  • arr[0] uses a 0-based index (the first element is [0]).
  • element_at(arr, 1) uses a 1-based index, and element_at(arr, -1) gives the last element.
SELECT trim(full_name)                             AS name,
       split(trim(full_name), ' ')                 AS parts,
       split(trim(full_name), ' ')[0]              AS first_name,
       element_at(split(trim(full_name), ' '), -1) AS last_name,
       size(split(trim(full_name), ' '))           AS part_count
FROM customers
ORDER BY cust_id
+-----------+---------------+----------+---------+----------+
|name       |parts          |first_name|last_name|part_count|
+-----------+---------------+----------+---------+----------+
|asha RAO   |[asha, RAO]    |asha      |RAO      |2         |
|ben  thomas|[ben, , thomas]|ben       |thomas   |3         |
|CHEN li    |[CHEN, li]     |CHEN      |li       |2         |
|divya      |[divya]        |divya     |divya    |1         |
+-----------+---------------+----------+---------+----------+

Look at Ben: the double space produced an empty string in the middle of the array, so part_count is 3. Clean the spaces before splitting (section 9) to avoid this.

For Divya there is only one word, so the first and last names are both "divya".

Common mistake: The second argument of split is a regular expression, not plain text. Splitting on '.' does not split on dots, because . means "any character" in a regex. Escape it with a backslash:

SELECT split('ben.t@yahoo.co.in', '.')     AS wrong,
       split('ben.t@yahoo.co.in', '\\.')   AS right
+------------------------------------+----------------------+
|wrong                               |right                 |
+------------------------------------+----------------------+
|[, , , , , , , , , , , , , , , , , ]|[ben, t@yahoo, co, in]|
+------------------------------------+----------------------+

The first call splits on every character and returns a list of empty strings. In Spark SQL string literals, a backslash is itself escaped, so the regex \. is written as '\\.'.


9. Regular Expressions: regexp_extract and regexp_replace

Regular expressions describe text patterns. Two functions cover most needs:

  • regexp_replace(s, pattern, replacement) replaces every match of the pattern.
  • regexp_extract(s, pattern, group) returns the part matched by a capture group ( ). Group 0 is the whole match.

Here they remove every non-digit from phone numbers, collapse repeated spaces, and pull the domain out of each email:

SELECT cust_id,
       regexp_replace(phone, '[^0-9]', '')        AS digits_only,
       regexp_replace(trim(full_name), ' +', ' ') AS single_spaced,
       regexp_extract(email, '@(.+)$', 1)         AS domain,
       regexp_extract(email, '\\.([a-z]+)\\s*$', 1) AS last_tld
FROM customers
ORDER BY cust_id
+-------+------------+-------------+------------+--------+
|cust_id|digits_only |single_spaced|domain      |last_tld|
+-------+------------+-------------+------------+--------+
|1      |9845012345  |asha RAO     |Gmail.com   |com     |
|2      |02223456789 |ben thomas   |yahoo.co.in |in      |
|3      |919900122334|CHEN li      |NULL        |NULL    |
|4      |9845012345  |divya        |company.com |com     |
+-------+------------+-------------+------------+--------+
  • [^0-9] means "any character that is not a digit", so replacing it with '' keeps only digits.
  • ' +' means "one or more spaces"; replacing it with a single space fixes "ben thomas".
  • @(.+)$ captures everything after the @. The last_tld pattern allows trailing spaces (\\s*), so Divya's untrimmed email still gives com.
  • If the pattern does not match, regexp_extract returns an empty string. If the input is NULL, it returns NULL, as for Chen.

10. Pattern Matching: LIKE, ILIKE and RLIKE

These return true or false, so you use them in WHERE:

OperatorPattern styleCase-sensitive?Example
LIKE% = any characters, _ = one characterYesemail LIKE '%@gmail.com'
ILIKESame as LIKENoemail ILIKE '%@gmail.com'
RLIKERegular expressionYesphone RLIKE '^[0-9]{10}$'
SELECT cust_id,
       email,
       email LIKE '%@gmail.com'  AS like_gmail,
       email ILIKE '%@gmail.com' AS ilike_gmail,
       phone RLIKE '^[0-9]{10}$' AS is_plain_10_digits
FROM customers
ORDER BY cust_id
+-------+------------------+----------+-----------+------------------+
|cust_id|email             |like_gmail|ilike_gmail|is_plain_10_digits|
+-------+------------------+----------+-----------+------------------+
|1      |Asha.Rao@Gmail.com|false     |true       |false             |
|2      |ben.t@yahoo.co.in |false     |false      |false             |
|3      |NULL              |NULL      |NULL       |false             |
|4      |divya@company.com |false     |false      |true              |
+-------+------------------+----------+-----------+------------------+

Asha's email ends in @Gmail.com with a capital G, so LIKE misses it and ILIKE finds it. Only Divya's phone is exactly ten digits with nothing else. Chen's email is NULL, so both comparisons return NULL rather than false.

RLIKE (also spelled REGEXP) matches if the pattern is found anywhere in the string. Use ^ and $ to anchor it to the start and end, as above.


11. Formatting: format_string and format_number

format_string (also called printf) builds a string from a template, like Python's % formatting. format_number adds thousands separators and fixes the decimal places:

SELECT name,
       format_string('%s earns %d', name, salary)       AS sentence,
       printf('%-6s|%08d', name, emp_id)                AS fixed_width,
       format_number(salary, 0)                         AS salary_text,
       format_number(salary / 12, 2)                    AS monthly
FROM VALUES
  ('Asha', 1, 95000),
  ('Chen', 3, 60000)
AS t(name, emp_id, salary)
ORDER BY name
+----+----------------+---------------+-----------+--------+
|name|sentence        |fixed_width    |salary_text|monthly |
+----+----------------+---------------+-----------+--------+
|Asha|Asha earns 95000|Asha  |00000001|95,000     |7,916.67|
|Chen|Chen earns 60000|Chen  |00000003|60,000     |5,000.00|
+----+----------------+---------------+-----------+--------+
  • %s inserts a string and %d an integer. %-6s left-aligns the text in 6 characters, and %08d pads a number with zeros to 8 digits.
  • format_number returns a string, so use it only for display, never before doing more maths.

12. Putting It Together: Cleaning the Customer Data

Here is the whole cleanup in one query. Each column fixes one of the problems from section 1:

SELECT cust_id,
       initcap(regexp_replace(trim(full_name), ' +', ' '))  AS name,
       lower(trim(email))                                     AS email,
       right(regexp_replace(phone, '[^0-9]', ''), 10)         AS phone,
       coalesce(city, 'Unknown')                              AS city
FROM customers
ORDER BY cust_id
+-------+----------+------------------+----------+---------+
|cust_id|name      |email             |phone     |city     |
+-------+----------+------------------+----------+---------+
|1      |Asha Rao  |asha.rao@gmail.com|9845012345|Bengaluru|
|2      |Ben Thomas|ben.t@yahoo.co.in |2223456789|Mumbai   |
|3      |Chen Li   |NULL              |9900122334|Pune     |
|4      |Divya     |divya@company.com |9845012345|Unknown  |
+-------+----------+------------------+----------+---------+

Read each expression from the inside out:

  1. trim removes the outer spaces, regexp_replace collapses inner spaces, and initcap fixes the case.
  2. lower(trim(email)) makes emails comparable.
  3. Stripping non-digits leaves numbers like 919900122334. right(..., 10) keeps the last 10 digits, which drops Chen's 91 country code and the leading 0 of Ben's 02223456789.
  4. coalesce replaces a missing city with a default. It is covered in the handling NULLs tutorial.

Interview tip: "Clean this column" questions usually want exactly this pattern: nested functions, applied inside out, with a clear reason for each step.


13. Quick Reference

TaskFunctionExampleResult
Change caseupper, lower, initcapinitcap('aSHA rao')Asha Rao
Count characterslengthlength('Spark')5
Remove outer spacestrim, ltrim, rtrimtrim(' hi ')hi
Join, NULL kills resultconcat, ||concat('a', NULL)NULL
Join, NULLs skippedconcat_wsconcat_ws('-', 'a', NULL, 'b')a-b
Slice (1-based)substring, left, rightsubstring('Spark', 2, 3)par
Find positioninstr, locateinstr('a@b', '@')2
Replace textreplacereplace('a-b', '-', '')ab
Pad to widthlpad, rpadlpad('7', 3, '0')007
Split into arraysplitsplit('a,b', ',')[0]a
Regex replaceregexp_replaceregexp_replace('a1b2', '[0-9]', '')ab
Regex extractregexp_extractregexp_extract('id=42', 'id=(\\d+)', 1)42
Templateformat_stringformat_string('%s-%d', 'a', 1)a-1

You can check any row by running it as a query:

SELECT concat_ws('-', 'a', NULL, 'b')            AS concat_ws_demo,
       substring('Spark', 2, 3)                  AS substring_demo,
       regexp_extract('id=42', 'id=(\\d+)', 1)   AS extract_demo
+--------------+--------------+------------+
|concat_ws_demo|substring_demo|extract_demo|
+--------------+--------------+------------+
|a-b           |par           |42          |
+--------------+--------------+------------+

14. Try It in the Online Compiler

Copy this into the PySpark Online Compiler. If your own queries contain backslashes, such as '\\.', put the SQL in a raw Python string (r"""...""") so the backslashes reach Spark unchanged:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL String Functions").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW customers AS
SELECT * FROM VALUES
  (1, '  asha RAO ', 'Asha.Rao@Gmail.com',  '98450-12345',     'Bengaluru'),
  (2, 'ben  thomas', 'ben.t@yahoo.co.in',   '(022) 2345 6789', 'Mumbai'),
  (3, 'CHEN li',     NULL,                  '+91 99001 22334', 'Pune'),
  (4, 'divya',       'divya@company.com ',  '9845012345',      NULL)
AS customers(cust_id, full_name, email, phone, city)
""")

spark.sql("""
SELECT cust_id,
       initcap(regexp_replace(trim(full_name), ' +', ' ')) AS name,
       lower(trim(email))                                  AS email,
       right(regexp_replace(phone, '[^0-9]', ''), 10)      AS phone,
       coalesce(city, 'Unknown')                           AS city
FROM customers
ORDER BY cust_id
""").show(truncate=False)

spark.sql("""
SELECT email,
       substring(email, 1, instr(email, '@') - 1) AS username,
       regexp_extract(email, '@(.+)$', 1)         AS domain
FROM customers
WHERE email IS NOT NULL
ORDER BY cust_id
""").show(truncate=False)

Summary

  • upper, lower and initcap change case; trim, ltrim and rtrim remove spaces from the ends only.
  • concat and || return NULL if any part is NULL; concat_ws skips NULL parts.
  • String positions start at 1 in substring, instr and element_at, but array indexes with [ ] start at 0.
  • split, regexp_replace, regexp_extract and RLIKE take regular expressions, so escape special characters like . as '\\.'.
  • LIKE is case-sensitive; use ILIKE or lower() for case-insensitive matching.
  • Clean messy text by nesting functions and reading them from the inside out.

Next, you will learn how to work with dates and timestamps in Spark SQL.