Module 04 · Lesson 8 of 16Detailed study · about 24 min

QUALIFY, latest records and deduplication

QUALIFY filters rows after window calculations, making latest-record and top-per-group queries easier to read.

Understand the idea

Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.

Key ideas in simple English
ConceptWhat it means
WHEREFilters inputs before the window calculation.
QUALIFYFilters after window values exist.
Business keyDefines which records are versions of the same entity.

A concrete example

Rank events inside each customer by date and event ID, then keep ROW_NUMBER = 1.

Remember: A deterministic result needs a complete ordering rule; QUALIFY does not delete source rows.

Explain it step by step · full theory

The seven input events

Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.

Sample inputs for this window lesson
EVENT_IDCUSTOMEREVENT_DATEAMOUNT
1A2025-01-01100
2A2025-01-0250
3A2025-01-0250
4A2025-01-05NULL
5B2025-01-0180
6B2025-01-0320
7B2025-01-040

Why WHERE is not enough

WHERE selects input rows before window results are calculated. It cannot filter the current SELECT’s newly computed row number at that same stage. QUALIFY filters after window calculation in Snowflake.

Think of it as two questions: first number the candidate records, then keep number 1. You can write the window expression in QUALIFY or reference a suitable selected window alias.

Pick the latest record per customer

Partition by customer, then order dates descending. If two records share the latest date, event_id descending chooses one consistently in this exercise. QUALIFY ROW_NUMBER() ... = 1 keeps one record per customer.

A’s latest record is event 4 on January 5 with an unknown amount. B’s latest is event 7 on January 4 with amount 0. Latest does not mean largest or non-NULL.

Filtering before ranking changes the question

If WHERE amount IS NOT NULL runs first, event 4 is excluded before ranking. A’s winner becomes event 3. The question has changed from “latest record” to “latest record with a known amount.”

Both questions can be useful. The error is choosing one accidentally and explaining it as the other. State the candidate population before selecting a winner.

Deduplication needs a business key

Deduplication means selecting the intended representative when several records represent the same business item. Partition by that business key and define a justified precedence rule, such as a source version and ingestion sequence.

Our sale events are not duplicates merely because they belong to the same customer. Keeping the latest event per customer is a selection task. The same SQL shape can support deduplication only when the partition key and winner rule match the business meaning.

A result filter is not a cleanup operation

QUALIFY changes the returned result, not the source dataset. It does not delete older events. If another process later reads the source directly, those records remain.

When porting to a system without QUALIFY, calculate the window value in a CTE or subquery and filter it in an outer WHERE. A CTE is also useful when a later calculation needs the filtered rows.

Words used in this lesson
QUALIFY
Filters records after window functions are evaluated.
Tie-breaker
An additional rule that resolves equal ordering values.
Business key
Fields identifying the real-world item being represented.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 4

QUALIFY, latest records and deduplication

A: four events
B: three events
No amount filter

Candidates

All seven events participate. Unknown amounts are still valid candidates for latest-event selection.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Candidates

    All seven events participate. Unknown amounts are still valid candidates for latest-event selection.

  2. Number

    Order newest first inside each customer. Event ID resolves tied dates for this example.

  3. Qualify

    Keep the numbered winners. Other source rows remain stored or supplied.

  4. Change the question

    Exclude NULL before numbering and A’s candidate set changes.

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Seven fictional events are included in each SQL block below. Run each block independently in an authorized learning session with a warehouse; no stored SALES table is required. Results are illustrative.

Keep the latest event for each customer

SQL · example
WITH sales AS (
 SELECT column1::NUMBER AS event_id,
        column2::VARCHAR AS customer,
        TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
        column4::NUMBER(12,2) AS amount
 FROM VALUES
  (1, 'A', '2025-01-01', 100),
  (2, 'A', '2025-01-02', 50),
  (3, 'A', '2025-01-02', 50),
  (4, 'A', '2025-01-05', NULL),
  (5, 'B', '2025-01-01', 80),
  (6, 'B', '2025-01-03', 20),
  (7, 'B', '2025-01-04', 0)
)
SELECT event_id, customer, event_date, amount
FROM sales
QUALIFY ROW_NUMBER() OVER (
 PARTITION BY customer
 ORDER BY event_date DESC, event_id DESC
) = 1
ORDER BY customer;

What to expect and why

Partitioning creates one competition per customer. Descending date puts the latest event first. The ID makes the tie policy explicit.

Expected result for the supplied input (not live output)
EVENT_IDCUSTOMEREVENT_DATEAMOUNT
4A2025-01-05NULL
7B2025-01-040

Keep the latest event with a known amount

SQL · example
WITH sales AS (
 SELECT column1::NUMBER AS event_id,
        column2::VARCHAR AS customer,
        TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
        column4::NUMBER(12,2) AS amount
 FROM VALUES
  (1, 'A', '2025-01-01', 100),
  (2, 'A', '2025-01-02', 50),
  (3, 'A', '2025-01-02', 50),
  (4, 'A', '2025-01-05', NULL),
  (5, 'B', '2025-01-01', 80),
  (6, 'B', '2025-01-03', 20),
  (7, 'B', '2025-01-04', 0)
)
SELECT event_id, customer, amount
FROM sales
WHERE amount IS NOT NULL
QUALIFY ROW_NUMBER() OVER (
 PARTITION BY customer
 ORDER BY event_date DESC, event_id DESC
) = 1
ORDER BY customer;

What to expect and why

WHERE excludes the unknown event first. A’s latest remaining date has two events, so the higher ID wins. This is intentionally a different question.

Expected result for the supplied input (not live output)
EVENT_IDCUSTOMERAMOUNT
3A50
7B0

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

Does QUALIFY delete the rows that do not pass?

Try it yourself

Explain why partitioning by customer does not necessarily deduplicate orders.

Compare your reasoning

A customer can legitimately have many distinct events or orders. Deduplication must partition by the actual identity of the item whose repeated representations are being resolved.

Official sources and curriculum

Module 04 · See module scope