Deduplication Methods

In Snowflake, I want to have a way to day these steps. I will have multiple subqueries. For each subquery there will do these steps logically: 1. Create the result set for the subquery with its where clause criteria 2. Remove records in this result set where they are any duplicate records from the previous results sets, using one or more keys to match. If it is the first query, then there will be no previous result sets to remove from. 3. Choose the number of records in this result set that will be include (using a limit if it makes the most sense)

ChatGPT said:

Thought for 27s

You can do this in Snowflake in (at least) two clean ways. I’ll show the one that most literally matches your step-by-step logic first, then a more compact “priority + window function” pattern.

1. “Step-by-Step” with CTEs + NOT EXISTS (most literal)

This follows your 3 steps for each subquery:

  • Build the result set
  • Remove rows that already appeared before (by key)
  • Apply a limit

Assume:

  • You have 3 subqueries q1, q2, q3
  • Your de-dupe keys are key1, key2
  • You want different limits for each query.

This pattern:

  • Mirrors your step order exactly.
  • Lets you use different limits, sorts, or filters per subquery.
  • Scales to more subqueries; you just keep adding NOT EXISTS against the previous _final CTEs.

If you have many subqueries, you can also combine the anti-joins (e.g., one NOT EXISTS on a UNION ALL of previous results), but the idea is the same.

2. Compact “Priority + Window Function” Pattern

If you’re okay defining a priority order for the subqueries (q1 wins over q2 wins over q3 when keys collide), you can do it in one structure:

  1. UNION all subqueries with a priority column.
  2. Pick the earliest priority per key.
  3. Then apply a per-priority limit.

This:

  • Ensures each key appears at most once (in the highest-priority subquery that produced it).
  • Applies per-subquery limits after deduplication.

Which should you use?

  • If you want to mirror the mental model of “do q1, then q2 minus q1, then q3 minus q1 & q2…” → use approach 1 with NOT EXISTS.
  • If you’re comfortable with a priority-based model and want something more compact, especially as the number of subqueries grows → use approach 2 with window functions.

If you share your actual subqueries / keys, I can plug them into one of these patterns so you can drop it straight into Snowflake.