Best Practices
Pay attention to table structure.
Large tables are partitioned and clustered according to common access patterns. Prune only the partitions you need, and filter or aggregate by clustered fields when possible. Joining tables on strings is expensive. Refrain from joining on string keys if you can utilize integer keys instead. Read the docs on Viewing Metadata to learn more about table metadata.Example - Profiling Operation Types
Let’s say you wanted to profile the types of operations submitted to the Stellar Network monthly. ======== Let’s say you wanted to profile the types of operations submitted to the Stellar Network monthly.history_operations table is partitioned by batch_run_date and clustered by transaction_id, source_account and type. Query costs are greatly reduced by pruning unused partitions. In this case, you could filter out operations submitted before 2023. This reduces the query cost by 4x.
type, which is a clustered field, will cut costs by a third:
Be as specific as possible.
Do not writeSELECT * statements unless you need every column returned in the query response. Since BigQuery is a columnar database, it can skip reading data entirely if the columns are not included in the select statement. The wider the table is, the more crucial it is to select only what you need.
Example - Transaction Fees
Let’s say you needed to view the fees for all transactions submitted in May 2023. What happens if you write aSELECT *?
Filter early.
When writing complex queries, filter the data as early as possible. PushWHERE and GROUP BY clauses up in the query to reduce the amount of data scanned.
Push transformations and mathematical functions to the end of the query when possible. Functions like TRIM(), CAST(), SUM(), and REGEXP_* are resource intensive and should only be applied to final table results.
Estimating Costs
If you need to estimate costs before running a query, there are several options available to you:BigQuery Console
The BigQuery Console comes with a built-in query validator. It verifies query syntax and provides an estimate of the number of bytes processed. The validator can be found in the upper right hand corner of the Query Editor, next to the green checkmark. To calculate the query cost, convert the number of bytes processed into terabytes, and multiply the result by $5:(estimated bytes read / 1TB) * $5
Paste the following query into the Editor to view the estimated bytes processed.