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

ROW_NUMBER, RANK and DENSE_RANK

ROW_NUMBER numbers rows; RANK and DENSE_RANK preserve ties with different rules for the following rank.

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
ROW_NUMBEROne number per row; choose a deterministic tie-breaker.
RANKTies share a rank and leave gaps.
DENSE_RANKTies share a rank without gaps.

A concrete example

Amounts 100, 50 and 50 have ranks 1, 2 and 2; the next lower amount has rank 4 but dense rank 3.

Remember: Keep ranking by amount separate from tie-breaking an individual row selection.

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

Three different ranking questions

Suppose A’s known amounts are 100, 50 and 50. Do you want a unique position for every event, a shared competition rank, or a shared rank without gaps? These are three different questions.

ROW_NUMBER assigns a different sequential number to every record. RANK gives tied values the same rank and leaves gaps after ties. DENSE_RANK gives tied values the same rank without those gaps.

Walk through a tie

For A, ordering by amount descending with NULL last gives 100, 50, 50, NULL. RANK produces 1, 2, 2, 4. Two records occupy rank 2, so the next position is 4. DENSE_RANK produces 1, 2, 2, 3 because there are three distinct ordered value groups.

ROW_NUMBER gives positions 1, 2, 3, 4. To decide consistently which 50 comes first, add the unique event_id as a tie-breaker to that function’s ordering.

Do not accidentally destroy the tie

For RANK and DENSE_RANK, we intentionally order only by amount in this example. Adding unique event_id there would make the combined ordering values distinct, so the two 50 amounts would no longer tie.

This is why one universal ordering expression is not always right for every window function. The tie policy is part of the business requirement.

Top two rows versus top two ranks

ROW_NUMBER <= 2 keeps at most two records per partition. RANK <= 2 includes both records tied at second place, so A contributes three rows. DENSE_RANK <= 2 keeps the top two distinct value groups, which can also exceed two rows.

Decide whether the request means a fixed number of records or all records sharing qualifying positions. Do not guess after the report is already published.

Unknown values need a stated position

NULLS LAST makes our choice explicit: unknown amounts go after known amounts. The unknown event still receives a position or rank; that is not proof that its amount is the smallest real number.

You could exclude unknown amounts before ranking if the question calls for ranking known values only. That would change the input population, and the explanation should say so.

Words used in this lesson
ROW_NUMBER
A unique sequential position within the chosen window order.
RANK
A rank shared by ties, with gaps afterward.
DENSE_RANK
A rank shared by ties, without gaps afterward.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 4

ROW_NUMBER, RANK and DENSE_RANK

100
50 and 50
NULL

Order A

Known amounts descend, then the unknown value is placed last.

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. Order A

    Known amounts descend, then the unknown value is placed last.

  2. Row number

    Unique event IDs decide the order of the two equal amounts.

  3. Rank

    A tie consumes two positions before the next rank.

  4. Dense rank

    Distinct value groups receive consecutive ranks.

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.

Compare the three functions

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, amount,
 ROW_NUMBER() OVER (ORDER BY amount DESC NULLS LAST, event_id) AS row_no,
 RANK() OVER (ORDER BY amount DESC NULLS LAST) AS competition_rank,
 DENSE_RANK() OVER (ORDER BY amount DESC NULLS LAST) AS dense_position
FROM sales
WHERE customer = 'A'
ORDER BY row_no;

What to expect and why

WHERE leaves A’s four rows before ranking. Only ROW_NUMBER uses the ID tie-breaker. The other functions preserve equal-amount ties.

Expected result for the supplied input (not live output)
EVENT_IDAMOUNTROW_NOCOMPETITION_RANKDENSE_POSITION
1100111
250222
350322
4NULL443

Check your understanding

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

For 100, 50, 50, what does RANK return in descending order?

Try it yourself

How many A rows pass RANK() <= 2, and how many pass ROW_NUMBER() <= 2?

Compare your reasoning

Three pass the rank filter: 100 and both 50s. Two pass the row-number filter with the unique tie-breaker.

Official sources and curriculum

Module 04 · See module scope