---
title: "Recipe: Leaderboard with Ranking"
description: "Top N users by score with rank numbers in teenybase, using a ROW_NUMBER() window function in a raw SQL action."
url: https://teenybase.com/docs/recipes/leaderboard
last_updated: 2026-04-19
---

> Documentation index: https://teenybase.com/llms.txt lists every teenybase docs page with a link to its Markdown version. All docs in one file: https://teenybase.com/llms-full.txt

# Leaderboard with Ranking

Top N users by score, with rank numbers. Uses `ROW_NUMBER()` window function in a raw SQL action.

### Config

Add a `score` field to your users table (or a separate `scores` table), then define the action:

```typescript
actions: [{
    name: 'leaderboard',
    description: 'Top 10 users by score with rank',
    applyTableRules: false,
    sql: {
        type: 'SELECT',
        table: 'scores',
        selects: [
            { q: 'ROW_NUMBER() OVER (ORDER BY score DESC)', as: 'rank' },
            'user_id',
            'score',
        ],
        orderBy: 'score DESC',
        limit: 10,
    },
}]
```

### API call

```bash
curl -X POST http://localhost:8787/api/v1/action/leaderboard
# → [[{"rank": 1, "user_id": "abc", "score": 980},
#     {"rank": 2, "user_id": "def", "score": 870}, ...]]
```
