The SUBSTRING function in BigQuery extracts a portion of a string starting at a specified position, with an optional length. Its basic syntax is SUBSTRING(value, position[, length]), and it returns a STRING type. For example, SUBSTRING('BigQuery', 4) returns ‘Query’.
Background: Why SUBSTRING Matters in SQL
String manipulation is a core part of data cleaning and transformation in SQL. In BigQuery, you often work with raw text fields—URLs, log messages, product codes, or user input—that need to be parsed into meaningful parts. The SUBSTRING function (also available as SUBSTR) is the standard way to slice out a fixed portion of text. Unlike some other SQL dialects that use SUBSTR as the primary name, BigQuery supports both spellings interchangeably, so you can use whichever reads better in your query.
How SUBSTRING Works: Syntax and Arguments
The function takes three arguments, the last of which is optional:
- value (required): The input string or expression that evaluates to a STRING or BYTES type.
- position (required): A positive integer specifying the starting character. Position 1 is the first character. If you use 0 or a negative number, BigQuery treats it differently—see the note below.
- length (optional): A non-negative integer specifying how many characters to return. If omitted, the function returns everything from
positionto the end of the string.
Important nuance: In BigQuery, position is 1-based. If you pass a position of 0, it is treated as 1. If you pass a negative position, it counts from the end of the string. For example, SUBSTRING('abcdef', -3) returns ‘def’. This behavior matches many other SQL databases but differs from some programming languages like Python, where negative indices are common.
Concrete Examples with Output
Let’s look at a few practical queries. Assume you have a table products with a column sku containing values like ‘ABC-123-XYZ’.
- Extract from position to end:
SELECT SUBSTRING(sku, 5) AS part FROM products;For ‘ABC-123-XYZ’, this returns ‘123-XYZ’. - Extract a fixed length:
SELECT SUBSTRING(sku, 5, 3) AS part FROM products;Returns ‘123’. - Extract last 3 characters:
SELECT SUBSTRING(sku, -3) AS part FROM products;Returns ‘XYZ’. - Using SUBSTR alias:
SELECT SUBSTR(sku, 1, 3) AS prefix FROM products;Returns ‘ABC’.
All of these return STRING values. If your input is BYTES, the function works on bytes rather than characters, which matters for multi-byte encodings like UTF-8—see the caution below.
Choosing Between SUBSTRING, SPLIT, and REGEXP_EXTRACT
While SUBSTRING is great for fixed positions, it’s not always the best tool. Here’s a quick decision guide:
- Fixed position and fixed length: Use
SUBSTRING. Example: extracting the 3rd to 5th characters of a code. - Delimiter-separated values: Use
SPLIT(returns an array) orREGEXP_EXTRACTfor patterns. For instance, to get the part after the first hyphen,SPLIT(sku, '-')[OFFSET(1)]is cleaner. - Pattern-based extraction: Use
REGEXP_EXTRACTwhen the position varies but the format is predictable, like extracting a 4-digit year from a date string.
For example, if you have ‘2023-05-14’ and want the month, SUBSTRING(date, 6, 2) works, but REGEXP_EXTRACT(date, r'-(\d{2})-') is more robust if the format changes.
Common Pitfalls and Errors
Several issues trip up new users:
- Position out of bounds: If
positionis greater than the string length, BigQuery returns an empty string, not an error. Iflengthis negative, you get an error:SUBSTRING('abc', 1, -1)fails. - Zero or negative position: As noted, 0 becomes 1, and negative counts from the end. This can surprise people expecting an error.
- Character vs. byte semantics: For STRING (UTF-8),
SUBSTRINGoperates on characters. For BYTES, it operates on bytes. If you have multi-byte characters (e.g., emojis),SUBSTRING('😀', 1, 1)returns ‘😀’, butSUBSTRING(CAST('😀' AS BYTES), 1, 1)returns a single byte, which is not valid UTF-8. Always work with STRING unless you have a specific reason. - NULL handling: If any argument is NULL, the function returns NULL. This is standard but can cause unexpected results in joins if you forget to handle it.
Performance and Cost Considerations
In BigQuery, you are billed by the amount of data processed, not by function calls. SUBSTRING itself is not a performance bottleneck—it runs on the data that is already being scanned. However, using it on a column in a WHERE clause can prevent partition pruning or make the query less efficient if the column is not a partition key. For example, WHERE SUBSTRING(transaction_id, 1, 3) = 'ABC' forces a full scan of that column. If you need to filter on a prefix, consider storing it as a separate column or using a LIKE pattern with a prefix, which BigQuery can optimize better in some cases. Also, avoid wrapping large string columns in SUBSTRING unnecessarily—it doesn’t increase cost, but it can make the query harder to read.
Alternatives and Related Functions
BigQuery offers several other string functions that complement SUBSTRING:
LEFTandRIGHT: Extract from the start or end.LEFT('abc', 2)returns ‘ab’,RIGHT('abc', 2)returns ‘bc’. These are syntactic sugar forSUBSTRINGwith position 1 or negative.SPLIT: Returns an array of substrings split by a delimiter. Useful for CSV-like data.REGEXP_EXTRACT: Extracts the first matching group from a regular expression. More powerful for variable patterns.INSTR: Finds the position of a substring, which you can combine withSUBSTRINGto extract dynamic portions. For example, to get everything after the first comma:SUBSTRING(str, INSTR(str, ',') + 1).
For instance, to extract the domain from an email: SUBSTRING(email, INSTR(email, '@') + 1). This is a common pattern.
Frequently Asked Questions
What is the difference between SUBSTR and SUBSTRING in BigQuery? There is no difference. Both are synonyms and behave identically. Use whichever you prefer; the documentation lists both.
Does SUBSTRING work with NULL values? Yes, if any argument is NULL, the result is NULL. If you want to avoid that, use COALESCE on the input string, like SUBSTRING(COALESCE(column, ''), 1, 5).
How do I extract a substring between two delimiters? Combine SUBSTRING with INSTR or use REGEXP_EXTRACT. For example, to get the part between the first and second hyphen: REGEXP_EXTRACT('A-B-C', r'-(.*)-') returns ‘B’. Or use SPLIT and array indexing.
Can I use SUBSTRING on an array or struct? No, it only works on STRING or BYTES. For arrays, use array functions like ARRAY_SLICE (if available) or OFFSET on the array. For structs, access fields directly.
Why does SUBSTRING with a negative position return different results than in Python? In Python, negative indices start from the end and 0 is the first character. In BigQuery, 0 is treated as 1, and negative counts from the end. So SUBSTRING('abc', -1) returns ‘c’, not ‘b’ as in Python’s s[-1] which is ‘c’ as well—actually the same. The difference is that 0 in Python is the first character, but in BigQuery 0 is 1. So SUBSTRING('abc', 0) returns ‘abc’, while Python’s s[0] returns ‘a’. Keep that in mind.
Is there a way to get the length of a string before using SUBSTRING? Yes, use LENGTH() for STRING or BYTE_LENGTH() for BYTES. For example, to get the last 4 characters safely: SUBSTRING(str, LENGTH(str) - 3), but note that if the string is shorter than 4, the position becomes negative and counts from the end, which might give unexpected results. Better to use RIGHT(str, 4).
Related
- Data Entry Pay: Hourly Rates & Salaries in 2024
- COUNTIF Formula in Google Sheets: How to Use It
- Random Number 1-30: How to Generate One
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- SQL SPLIT Function: Syntax, Examples, and AlternativesThere is no single, standard SQL SPLIT() function that works in every database. To split text into rows,…
- SUBSTITUTE Formula in Excel: Examples and UsesWith the text to edit in cell A2, use =SUBSTITUTE(A2,"-","") to remove every hyphen; if A2 contains INV-204-INV,…
- Excel Filter Shortcut: How to Add or Remove FiltersIn Excel for Microsoft 365 on Windows, press Ctrl+Shift+L to add filter drop-downs to the current data range;…
- How to Hide the Formula Bar in Excel on Windows and MacTo hide the formula bar in Excel for Microsoft 365, open the View tab, then in the Show…
- Excel Won’t Calculate Formulas? Causes, Checks, and FixesIf Excel does not calculate a formula, first check Formulas > Calculation Options and select Automatic. If that…
- Excel Length of Service Formula: Calculate Years and MonthsIf the start date is in B2 and the date to measure service through is in C2, use…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.