Everything you need to know about SQL string functions. Strings are a crucial part of any dataset and being able to confidently manipulate and transform them can make all the difference in your analysis.
STRINGs are a crucial part of any dataset and being able to confidently manipulate and transform them can make all the difference in your analysis. This notebook covers the common STRING manipulations in BigQuery.
STRINGs are their own data type in Big Query. They are the most flexible type - often our dates if not formatted exactly right will be read in as a STRING, or our survey results will be listed as STRINGs of responses. Therefore it's crucial to know how to master them.
How to modify and transform entire STRINGs. Each of these functions returns a STRING.
There are several functions available in BigQuery to add and remove whitespace to your STRINGs. They either involve:
SELECT
' Original String__',
TRIM(' Original String__') AS trimmed,
LTRIM(' Original String__') AS left_trim,
RTRIM(' Original String__', "__") AS right_trimFor trimming, the functions are:
SELECT
RPAD('abc', 5) AS right_spaces,
LPAD('abc', 5, '--') AS left_pad_hypenTRIM(value1[, value2]) -> Removes all leading and trailing characters that match value2 (whitespace if not specified)LTRIM(value1[, value2]) -> Removes only leading characters that match value2 (whitespace if not specified)RTRIM(value1[, value2]) -> Removes only trailing characters that match value2 (whitespace if not specified)| f0_ | trimmed | left_trim | right_trim |
|---|---|---|---|
| Original String__ | Original String__ | Original String__ | Original String |
💡 TRIM is very useful when dealing Substrings as shown in the next section.
For padding, the functions available are:
SELECT
UPPER('AbCd ef') AS upper,
LOWER('AbCd ef') AS lower,
INITCAP('AbCd ef') AS word_capsRPAD(original_value, return_length[, pattern]) -> Returns the original_value appended with the pattern up to the return_length number of characters.LPAD(original_value, return_length[, pattern])-> Returns the original_value prepended with the pattern up to the return_length number of characters.| right_spaces | left_pad_hypen |
|---|---|
| abc | --abc |
A common way to re-format STRINGs is to change the case. To do that in BigQuery, you can use:
SELECT
REVERSE('racecar') AS palindrome,
REVERSE('palindrome') AS not_palindromeLOWER(value)-> Returns value in lowercaseUPPER(value) -> Returns value in uppercaseINITCAP(value[, delimiters]) -> Returns the first character in each word as uppercase and the rest as lowercase| upper | lower | word_caps |
|---|---|---|
| ABCD EF | abcd ef | Abcd Ef |
To re-arrange the characters in a STRING, the most common function is:
SELECT
BYTE_LENGTH('Hello! 👪') AS bytes,
CHAR_LENGTH('Hello! 👪') AS characters,
LENGTH('Hello! 👪') AS lengthREVERSE(value)-> Returns string in reverse order| palindrome | not_palindrome |
|---|---|
| racecar | emordnilap |
How to get information about each STRING. These functions may return INT64 or BOOL.
To find the length of a STRING, there are a surprising number of options in BigQuery:
SELECT
STARTS_WITH('Hello, there', 'Hello') AS starts_with_hello,
'Bob' IN ('Mary', 'John', 'Barry') AS in_list,
('xyzFind Mejf3' LIKE '%Find Me%') AS like_string,
REGEXP_CONTAINS('xyzFind Mejf3', r'Find Me') AS regex_containsBYTE_LENGTH(value) -> Returns the length of the STRING in BYTEsCHAR_LENGTH(value) or CHARACTER_LENGTH(value) -> Returns the length of the STRING in charactersLENGTH(value) -> Returns number of characters| bytes | characters | length |
|---|---|---|
| 11 | 8 | 8 |
SELECT
REGEXP_INSTR('hello@cool_stuff.com', r'@[^.]+.') AS regex_position,
STRPOS('racecar', 'car') AS string_positionWhen building filters or CASE statements, it's common to check whether a STRING is or is similar to another string or substring. To do that we can use one of the STRING comparison functions:
SELECT
REPLACE('My Name is ____', '____', 'Judge') AS replace,
REGEXP_REPLACE('My Name is ____', r'(_+)', 'Judge') AS regex_replaceSTARTS_WITH(value1, value2)-> Returns True/False if value1 starts with the substring value2ENDS_WITH(value1, value2)-> Returns True/False if value1 ends with with the substring value2REGEXP_CONTAINS(value, regexp)-> Returns True/False if value contains the pattern matched in the regexp expressionYou can see BigQuery's regex library here.
in combination with one of the following comparison operators:
SELECT
RIGHT('@hello.com',9) domain,
SPLIT('This is a sentence',' ') words,
SUBSTR('_xyz_',2,3) substring,
REGEXP_EXTRACT_ALL('anything in CAPS is SPECIAL',r'([A-Z]+)') special_wordsIN, NOT INLIKE, NOT LIKE| starts_with_hello | in_list | like_string | regex_contains |
|---|---|---|---|
| true | false | true | true |
💡 For LIKE, the % is a wildcard character
How to find, extract, and modify substrings, or parts of STRINGs. These functions may return INT64, ARRAY or STRING.
When dealing with substrings you often want to first locate a substring within a STRING. To do that, we can use:
SELECT
CONCAT('Hello', " ", "World")REGEXP_INSTR(source_value, regexp [, position[, occurrence, [occurrence_position]]])-> Returns the lowest 1-based index of a regular expression, regexp, in source_valueSTRPOS(value1, value2)-> Returns the 1-based index of the first occurrence of value2 inside value1. Returns 0 if value2 is not found.| regex_position | string_position |
|---|---|
| 6 | 5 |
These functions tell you which index the substring first appears, useful for replacing or extracting substrings given this index.
Once you've found a substring, you likely want to either extract it or replace it. To replace a substring, you can use one of the following:
SELECT
ARRAY_LENGTH(REGEXP_EXTRACT_ALL("how many a's in this sentence?", r'(a)')) AS a_countREPLACE(original_value, from_value, to_value)->Replaces all occurrences of from_value with to_value in original_value.REGEXP_REPLACE(value, regexp, replacement) -> Returns a STRING where all substrings of value that match regular expression regexp are replaced with replacement.SELECT
REPLACE('My Name is ____', '____', 'Judge') AS replace,
REGEXP_REPLACE('My Name is ____', r'(_+)', 'Judge') AS regex_replace
| replace | regex_replace |
|---|---|
| My Name is Judge | My Name is Judge |
SELECT
REGEXP_EXTRACT_ALL('12x12=144', r'([0-9]+)') AS greedy_number_count,
REGEXP_EXTRACT_ALL('12x12=144', r'([0-9])') AS not_greedy_number_countPerhaps the most valuable manipulation to perform on substrings is to extract them to their own column or entity. To do that, there are several options:
LEFT(value, length)-> Returns a STRING value that consists of the specified number of leftmost characters or bytes from valueRIGHT(value, length)-> Returns a STRING value that consists of the specified number of rightmost characters or bytes from valueSPLIT(value[, delimiter]) -> Returns an ARRAY of STRINGs split by the delimiter (or space if omitted) SUBSTR(value, position[, length]) -> Returns a substring of value from the position index up to the length of characters specified REGEXP_EXTRACT(value, regexp[, position[, occurrence]]) or REGEXP_SUBSTR(value, regexp[, position[, occurrence]]) -> Returns a substring of value that matches the regexp expression starting at position index.REGEXP_EXTRACT_ALL(value, regexp)-> Returns an ARRAY of substrings that match the regexp expression| domain | words | substring | special_words |
|---|---|---|---|
| hello.com | This,is,a,sentence | xyz | CAPS,SPECIAL |
To combine substrings together you can use:
CONCAT(value1[, ...])-> Concatenates 2 or more STRINGs into a single result. | f0_ |
|---|
| Hello World |
To do this we can make use of REGEXP_EXTRACT_ALL and ARRAY_LENGTH.
To do this we can again use REGEXP_EXTRACT_ALL
We can choose to make our regex greedy, meaning once it found one number it will look for another one. This is the difference between:
r'([0-9]+)' : which says find 1 or more digits together and r'([0-9])' which says find any digits. Depending on what you want, both can be useful.
| greedy_number_count | not_greedy_number_count |
|---|---|
| 12,12,144 | 1,2,1,2,1,4,4 |