Skip to content
Database

Select first row for each group in Postgres

Given a table seasons:

idteampoints
1Liverpool82
2Liverpool84
3Brighton34
4Brighton28
5Liverpool79

We want to find the rows containing the maximum number of points per team.

The expected output we want is:

idteampoints
3Brighton34
2Liverpool84

Run the following SQL using the SQL Editor in the Supabase Dashboard or with psql over a direct connection. To connect with psql, see Direct connection.

select distinct
on (team) id,
team,
points
from
seasons
order by
team,
points desc;

The important bits here are:

  • The desc keyword to order the points from highest to lowest.
  • The distinct keyword that tells Postgres to only return a single row per team.