Select first row for each group in Postgres
A guide from Supabase
Apps on Plentiful run on Supabase's open-source database, sign-in, file storage and live updates, so most of this guide applies. The differences: your app reaches its database through its own server — not Supabase's data API (supabase.from(…)) — there are no Edge Functions (your app's server does that work), and scheduled work uses Jobs. Where it says "Supabase dashboard", use your app's Dashboard. Ask the builder when in doubt.
Given a table seasons:
| id | team | points |
|---|---|---|
| 1 | Liverpool | 82 |
| 2 | Liverpool | 84 |
| 3 | Brighton | 34 |
| 4 | Brighton | 28 |
| 5 | Liverpool | 79 |
We want to find the rows containing the maximum number of points per team.
The expected output we want is:
| id | team | points |
|---|---|---|
| 3 | Brighton | 34 |
| 2 | Liverpool | 84 |
From the SQL Editor, you can run a query like:
1select distinct2 on (team) id,3 team,4 points5from6 seasons7order BY8 id,9 points desc,10 team;The important bits here are:
- The
desckeyword to order thepointsfrom highest to lowest. - The
distinctkeyword that tells Postgres to only return a single row per team.
This query can also be executed via psql or any other query editor if you prefer to connect directly to the database.