SUBSTR
Definition
The SUBSTR function allows you to extract a section of a longer string in BigQuery.
| location | state |
|---|---|
| New York, NY | NY |
| Miami, FL | FL |
The query above gets the last 2 characters of the location string.
Practical Info
SUBSTRworks withSTRINGorBYTESdata types- The
positionargument is 1-based, so the first character is at position1 - You can use
-1to indicate the last character position - if
length< 0 then the function returns an error
Common Questions
How to dynamically extract sub-strings?
SUBSTR(value, position[, length])What if we have a series of email addresses: [email protected], [email protected], etc. and we want to find the domain (e.g. gmail.com, yahoo.com), we can use SUBSTR in combination with STRPOS and LENGTH to dynamically extract everything after the @.
| domain | |
|---|---|
| [email protected] | gmail.com |
| [email protected] | yahoo.com |
Alternatively, you can use REGEXP_EXTRACT to achieve the same result:
| domain | |
|---|---|
| [email protected] | gmail.com |
| [email protected] | yahoo.com |
Troubleshooting Common Errors
It's rare SUBSTR returns an error unless you call it with the wrong data types (e.g. pass a STRING to the position parameter), but it's often that you don't get what you want.
The best thing to do here is to either use REGEXP functions, or start get your query working with 1-2 example rows before trying to apply it to the entire column.