55

For example:

name | weight
jon    100    
jane   120    
joe    130

How do I only return the name of the person with the largest weight?

peterh
  • 11,875
  • 18
  • 85
  • 108

4 Answers4

106
SELECT name FROM tbl ORDER BY weight DESC LIMIT 1

Much more performant than the other answer and results in one row only.

raveren
  • 17,799
  • 12
  • 70
  • 83
  • 5
    Good answer. I also want to note that if weight have an index, sort will performed on index and will be faster. – bmlkc Aug 17 '13 at 04:10
  • 5
    Nice answer, however it won't return two results if two people have the same weight. – Standaa - Remember Monica Apr 21 '16 at 12:23
  • 4
    LIMIT 1 requires a full table scan. This is _not_ performant with lots of rows. Try running `EXPLAIN` on your queries. – Volte Dec 29 '16 at 02:46
  • 2
    If there is any NULL in weight, it returns NULL – alextc Jul 26 '18 at 05:16
  • 3
    Weights with NULL values can be filtered out by using WHERE: `SELECT name FROM tbl WHERE weight IS NOT NULL ORDER BY weight DESC LIMIT 1`. – Orienteerix Jun 28 '20 at 12:23
  • @Standaa-RememberMonica: Simply change the `LIMIT` to whatever value you feel is appropriate, e.g., `SELECT name FROM tbl ORDER BY weight DESC LIMIT 10`. – ToJo Aug 26 '21 at 20:39
  • sorry, very bad solution: what if you have two similar highest values? – simUser Jan 27 '22 at 11:53
50

Use this:

select name
from tbl
where weight = (select max(weight) from tbl)
Hao
  • 8,047
  • 18
  • 63
  • 92
7

If you need to find multiple rows, e.g. date on which each person had maximum weight:

name | weight | day
don    110      1
don    120      20
don    110      30
joe    90       1
joe    80       15
joe    85       30

i.e. for "don" you want to get "don | 120 | 20" and for joe you want "joe | 90 | 1", then you can write:

SELECT name, max(weight), (array_agg(day ORDER BY weight DESC))[1] FROM tbl GROUP BY name
alexkovelsky
  • 3,880
  • 1
  • 27
  • 21
3

ORDER BY DESC puts rows with null values at the top.

To avoid returning results corresponding to null values:

SELECT name FROM tbl WHERE weight = (SELECT MAX(weight) FROM tbl);

Note: This query will return multiple results if multiple people have a weight equal to the maximum weight. To grab just one, add LIMIT 1 to the end of the query.


Acknowledgements and more information:

Why do NULL values come first when ordering DESC in a PostgreSQL query?

MIN/MAX vs ORDER BY and LIMIT

Postgres MAX Function

Matt Kleinsmith
  • 1,017
  • 3
  • 13
  • 24