The BETWEEN operator in BigQuery is a shorthand for testing whether a value falls within a given range, inclusive of both endpoints. For example, WHERE age BETWEEN 18 AND 65 is equivalent to WHERE age >= 18 AND age <= 65. It works with numeric, date, timestamp, and string data types, but its behavior with NULLs and its inclusive nature often surprise new users.
What BETWEEN Does in BigQuery
BETWEEN is a comparison operator that returns TRUE if the left-hand expression is greater than or equal to the lower bound and less than or equal to the upper bound. The syntax is:
expression BETWEEN lower_bound AND upper_bound
The AND here is part of the BETWEEN syntax, not a logical AND. You cannot use BETWEEN with more than two bounds; for three or more ranges, you need explicit AND conditions.
BigQuery supports BETWEEN for these data types:
- Numeric types:
INT64,FLOAT64,NUMERIC,BIGNUMERIC - Temporal types:
DATE,TIMESTAMP,DATETIME,TIME - String types:
STRING(lexicographic comparison)
For STRING, comparison is based on the UTF-8 byte order, so it is case-sensitive and locale-independent. For example, 'b' BETWEEN 'a' AND 'c' is TRUE, but 'B' BETWEEN 'a' AND 'c' is FALSE because uppercase letters have lower byte values.
How to Use BETWEEN: Basic Examples
Assume a table orders with columns order_id, amount, and order_date.
Filter numeric range:
SELECT order_id, amount
FROM orders
WHERE amount BETWEEN 100 AND 500;
Filter date range (inclusive of both dates):
SELECT order_id, order_date
FROM orders
WHERE order_date BETWEEN DATE '2024-01-01' AND DATE '2024-01-31';
Filter timestamp range (note: the upper bound is inclusive, so this includes exactly '2024-01-31 00:00:00' but not later that day):
SELECT order_id, order_date
FROM orders
WHERE order_date BETWEEN TIMESTAMP '2024-01-01 00:00:00' AND TIMESTAMP '2024-01-31 00:00:00';
If you want all of January 31, you need to use TIMESTAMP '2024-02-01 00:00:00' as the upper bound with a strict less-than, or use TIMESTAMP_SUB to get the end of day.
BETWEEN vs. >= and <=: What’s the Difference?
Functionally, BETWEEN is identical to >= and <= combined with AND. There is no performance difference; BigQuery's query optimizer treats them the same. The only real difference is readability and the risk of logical errors.
Consider this common mistake: writing WHERE amount BETWEEN 100 AND 500 AND status = 'paid' is fine, but writing WHERE amount BETWEEN 100 AND 500 OR amount BETWEEN 600 AND 800 is correct only if you use parentheses. BETWEEN does not allow you to chain multiple ranges without OR.
Another subtlety: BETWEEN is inclusive, while some other SQL dialects (like PostgreSQL) also use inclusive BETWEEN. But if you come from a language like Python where range() excludes the end, you might assume BETWEEN is exclusive – it is not.
Common Pitfalls and Gotchas
Here are the most frequent issues users run into with BETWEEN in BigQuery:
- NULL handling: If any operand is NULL, the result is NULL (which is treated as FALSE in WHERE). For example,
WHERE amount BETWEEN NULL AND 500returns no rows, even if amount is 100. - Inclusive upper bound with timestamps: As shown above,
BETWEENincludes the exact upper bound. For timestamps with fractional seconds, this can be tricky. UseDATETIME_TRUNCor explicit<to avoid missing data. - String comparison is case-sensitive:
'Apple' BETWEEN 'a' AND 'z'is FALSE because 'A' (65) is less than 'a' (97). UseLOWER()if you need case-insensitive. - Date vs. timestamp mixing: You cannot compare a DATE with a TIMESTAMP directly. You must cast one to the other. For example,
WHERE order_date BETWEEN DATE '2024-01-01' AND TIMESTAMP '2024-01-31'will cause a type mismatch error. - Using BETWEEN in JOIN conditions: It works, but be careful with NULLs and performance. It might be better to use a range join with
>=and<for non-inclusive ranges.
Choosing BETWEEN vs. Other Range Methods
Sometimes BETWEEN is not the best choice. Here are alternatives and when to use them:
- Exclusive upper bound: Use
value >= lower AND value < upper. This is common for date ranges where you want all of January, so you usedate >= '2024-01-01' AND date < '2024-02-01'. - IN for discrete values: If you need to match a set of specific values, use
IN (1, 2, 3)instead ofBETWEEN. - UNNEST for arrays: If you need to check if a value is in an array, use
value IN UNNEST(array_column). - For multiple ranges: Use
(value BETWEEN 1 AND 10) OR (value BETWEEN 20 AND 30).
BETWEEN with NULLs and Data Cleaning
When cleaning data, you often want to exclude NULLs or handle them explicitly. BETWEEN does not match NULLs, so rows with NULL in the column are excluded. If you need to include them, you must add an OR condition:
SELECT *
FROM orders
WHERE amount BETWEEN 100 AND 500 OR amount IS NULL;
This is a common pattern when you want to treat missing amounts as valid for some analysis.
Performance and Best Practices
In BigQuery, BETWEEN does not affect query performance compared to >= and <=. However, to get the best performance, consider these tips:
- If the column is used in a filter, ensure it is partitioned or clustered appropriately. For example, partitioning a table by date and then using
BETWEENon that date column allows BigQuery to prune partitions. - Avoid applying functions to the column in the WHERE clause. For example,
WHERE DATE(order_date) BETWEEN ...prevents partition pruning. Instead, compare the raw column with a range of timestamps. - When using
BETWEENwith strings, be aware of collation. BigQuery uses binary collation, so 'a' and 'A' are different.
Frequently Asked Questions
Does BETWEEN include the endpoints in BigQuery?
Yes, BETWEEN is inclusive of both the lower and upper bounds. For example, WHERE x BETWEEN 1 AND 3 includes 1, 2, and 3.
Can I use BETWEEN with strings in BigQuery?
Yes, you can use BETWEEN with STRING values. It compares lexicographically based on UTF-8 byte order. For example, 'b' BETWEEN 'a' AND 'c' is TRUE, but 'B' BETWEEN 'a' AND 'c' is FALSE.
How do I use BETWEEN with dates to include the entire end day?
Because BETWEEN is inclusive, date BETWEEN '2024-01-01' AND '2024-01-31' includes all of January 31. But if you are using timestamps, you need to use timestamp >= '2024-01-01 00:00:00' AND timestamp < '2024-02-01 00:00:00' to get all of January.
What happens if the lower bound is greater than the upper bound?
If the lower bound is greater than the upper bound, BETWEEN returns FALSE for all non-NULL values. For example, WHERE x BETWEEN 5 AND 1 returns no rows. It does not error.
Can I use BETWEEN in a JOIN condition?
Yes, you can use BETWEEN in a JOIN condition, such as ON a.value BETWEEN b.low AND b.high. This is a common pattern for range joins. Be mindful of NULLs and performance; using >= and < might be clearer for exclusive ranges.
Does BETWEEN work with NULL values?
No, if any of the three expressions (the value, lower bound, or upper bound) is NULL, the result is NULL, which is treated as FALSE in a WHERE clause. To include NULLs, add an explicit OR column IS NULL condition.
Related
- KPI Spreadsheet Setup: Step-by-Step Guide
- Shortcut to Lock Computer: Windows & Mac Keys
- Jurong East Printing Shop: Where to Print in Singapore
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Generate Random Number String: How to Do ItTo generate a random number string, use a dedicated random string generator tool, a programming language’s built-in random…
- Transpose Key in Excel: Shortcut and Other MethodsIn Excel for Microsoft 365 on Windows, copy the cells, select an empty destination, then press Ctrl+Alt+V, E,…
- Amortization Schedule in Excel: Build One Step by StepTo find a ready-made schedule, open Excel for Microsoft 365 on Windows and choose File > New, then…
- Arduino C Programming: What the Language Actually IsYes, you can write C-style code for Arduino, but the usual Arduino sketch is compiled as C++, not…
- PowerPoint Notes: How to Present With Speaker NotesTo present with speaker notes in PowerPoint, add your talking points in the Notes pane, then start the…
- Daily Cash Flow Report Template in Excel: Setup and UseA daily cash flow report template in Excel lists each day’s opening cash, money received, money paid, net…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.