Back to Chapters
Chapter Progress: 0 %0 / 5 Lessons Read
‹›

2. Fast and cheap tables: partitions, clusters and nested data

2.2 Clustering: keep similar rows together

Highlights & notes

Select lesson text to highlight it, or tap Add note.

    Bookmarks

    Bookmark a lesson to see it here.

      Inside each drawer, a good clerk also sorts the pages by roll number. Finding roll number 42 is then quick. Clustering does this for a table. BigQuery stores rows with similar values next to each other.

      • You choose up to 4 clustering columns.
      • The order matters. The first column is the main sort.
      • BigQuery re-sorts new data in the background, free of charge.

      Partitioning and clustering work well together. A common recipe is: partition by date, then cluster by the column people filter on most, such as customer_id or country.

      Partition or cluster?

      • The filter is a date, and you want to know the cost before running → partition
      • The filter is a column with many different values, like customer id or email → cluster
      • People use both kinds of filter → use both
      Must Know:

      With clustering, the dry run shows the highest possible cost. The real bytes are known only after the query runs, and they are often much lower.

      How it fits together

      1. Partition: one date
      2. Rows sorted by customer_id
      3. Query jumps to customer 2

      Partition by date, cluster by customer

      Two tools on one table.

      SQL

      CREATE TABLE sales.orders_pcPARTITION BY order_dateCLUSTER BY customer_id ASSELECT * FROM sales.orders;SELECT order_id, amountFROM sales.orders_pcWHERE customer_id = 2;

      Rows at this step

      order_id | amount
      ---------+-------
      102      | 700
      105      | 52000

      Try it yourself

      1. Run the CREATE TABLE statement from the walkthrough.
      2. Open the new table and click the Details tab. Find the lines Partitioned by and Clustered by.
      3. On a tiny practice table the bytes will not drop. Clustering starts to help on tables bigger than about 64 MB.

      Question 1 · Easy

      How many clustering columns can one BigQuery table have?

      Question 2 · Medium

      A table is clustered by (country, city). Which filter gains the most?

      Question 3 · Hard

      Analysts filter by order_date and by customer_id. There are crores of customers. Which design fits?

      Key takeaways

      Clustering stores similar rows together, using up to 4 columns in order. Filters on those columns skip blocks. Partition by date and cluster by the most-filtered column.

      Lesson 7 of 90

      Save your progress

      Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.

      Start free Log in
      PreviousClustering: keep similar rows together
      Save your progress free for 1 month. Start free · Log in