> ## Documentation Index
> Fetch the complete documentation index at: https://docs.narrative.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Window Functions

> Ranking and analytics: ROW_NUMBER, RANK, LAG, LEAD, and more

## Window functions

Window functions perform calculations across a set of rows related to the current row.

### ROW\_NUMBER

Assigns a unique sequential number to each row within a partition.

```sql theme={null}
SELECT
  user_id,
  event_timestamp,
  ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY event_timestamp) AS event_seq
FROM company_data."123"
```

### RANK

Assigns a rank with gaps for ties.

```sql theme={null}
SELECT
  user_id,
  score,
  RANK() OVER (ORDER BY score DESC) AS rank
FROM company_data."123"
```

### DENSE\_RANK

Assigns a rank without gaps for ties.

```sql theme={null}
SELECT
  user_id,
  score,
  DENSE_RANK() OVER (ORDER BY score DESC) AS dense_rank
FROM company_data."123"
```

### PERCENT\_RANK

Returns the relative rank as a percentage (0 to 1).

```sql theme={null}
SELECT
  user_id,
  score,
  PERCENT_RANK() OVER (ORDER BY score) AS percentile
FROM company_data."123"
```

### LAG

Returns the value from a previous row.

```sql theme={null}
SELECT
  event_date,
  value,
  LAG(value, 1) OVER (ORDER BY event_date) AS previous_value,
  value - LAG(value, 1) OVER (ORDER BY event_date) AS change
FROM company_data."123"
```

### LEAD

Returns the value from a following row.

```sql theme={null}
SELECT
  event_date,
  value,
  LEAD(value, 1) OVER (ORDER BY event_date) AS next_value
FROM company_data."123"
```

### SUM / AVG / COUNT (windowed)

Aggregate functions can be used as window functions.

```sql theme={null}
SELECT
  event_date,
  amount,
  SUM(amount) OVER (ORDER BY event_date) AS running_total,
  AVG(amount) OVER (PARTITION BY category) AS category_avg
FROM company_data."123"
```

***

## Related content

<CardGroup cols={2}>
  <Card title="Aggregate Functions" icon="chart-bar" href="/nql/functions/aggregate-functions">
    GROUP BY computations
  </Card>

  <Card title="SELECT" icon="magnifying-glass" href="/nql/commands/select">
    QUALIFY clause for window function filtering
  </Card>

  <Card title="All Functions" icon="function" href="/nql/functions/index">
    Browse all function categories
  </Card>

  <Card title="Common Query Patterns" icon="book" href="/cookbooks/nql/common-queries">
    Real-world deduplication examples
  </Card>
</CardGroup>
