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

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

2.4 QUALIFY: keep the newest row of each key

Highlights & notes

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

    Bookmarks

    Bookmark a lesson to see it here.

      You know WHERE (filter rows) and HAVING (filter groups). BigQuery has a third filter, QUALIFY. It filters on the result of a window function, such as ROW_NUMBER().

      Its most common job is removing duplicates: number the rows of each order, newest first, and keep number 1. Without QUALIFY you need a subquery. With it, one short query is enough.

      Must Know:

      Many teams write WHERE TRUE before QUALIFY. It keeps every row and does no harm. BigQuery has at times wanted a WHERE, GROUP BY or HAVING next to QUALIFY, so the habit is safe.

      One row per order, the newest

      Order 106 arrived twice.

      SQL

      SELECT *FROM bronze.order_eventsWHERE TRUEQUALIFY ROW_NUMBER() OVER (  PARTITION BY order_id  ORDER BY updated_at DESC) = 1;

      Rows at this step

      order_id | status    | updated_at
      ---------+-----------+-----------
      106      | delivered | 2026-01-20
      107      | delivered | 2026-01-20

      Quick check

      What does QUALIFY filter on?

      The biggest order of each customer

      RANK instead of ROW_NUMBER.

      SQL

      SELECT customer_id, order_id, amountFROM sales.ordersWHERE TRUEQUALIFY RANK() OVER (  PARTITION BY customer_id  ORDER BY amount DESC) = 1;

      Rows at this step

      customer_id | order_id | amount
      ------------+----------+-------
      1           | 101      | 55000
      2           | 105      | 52000
      3           | 104      | 12000
      4           | 106      | 650

      Quick check

      Two orders of one customer tie for the biggest amount. How many does RANK() = 1 keep for that customer?

      Try it yourself

      1. Run the second walkthrough on your sales.orders table.
      2. Change DESC to ASC to get the smallest order of each customer.

      Question 1 · Easy

      Which clause filters on ROW_NUMBER() directly?

      Question 2 · Medium

      To keep the latest version of each order, you order the window by…

      Question 3 · Hard

      You must keep exactly one row per key, even when two rows tie. Which function?

      Key takeaways

      QUALIFY filters on window functions. ROW_NUMBER with QUALIFY = 1 keeps one row per key and is the standard way to remove duplicates in BigQuery.

      Lesson 9 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
      PreviousQUALIFY: keep the newest row of each key
      Save your progress free for 1 month. Start free · Log in