Log in

View Full Version : How to get only the highest and the lowest number as output in a set of data


alfredlionel
Aug 2, 2007, 06:41 AM
Dear sir,
I would like to know how to get the highest and the lowest ages as answer in a set of data with many range of ages.the output should be with the name place and age of the person with the highest and the lowest age.kindly let me me know the answer.

ScottGem
Aug 2, 2007, 06:49 AM
You can't do it on one query.

Try SELECT TOP 1 Name, Place, Age
FROM table
ORDER BY Age Desc

Drop the Desc to get the youngest.

Nosnosna
Aug 2, 2007, 03:29 PM
SELECT name, place, age from TABLE order by age DESC LIMIT 1

This will give the entry with the highest value.

As Scott said above, remove the DESC to get the lowest value.

Note that there is a severe limitation to this approach: in any non-trivial data set, there are going to be multiple people with the maximum and minimum ages. To get all of the entries with the highest or lowest value for age in a single query, you can use:

SELECT name, place, age FROM table WHERE age = (SELECT MAX(age) FROM table) OR age = (SELECT MIN(age) FROM table)

ScottGem
Aug 2, 2007, 03:42 PM
Comments on this post
alfredlionel (https://www.askmehelpdesk.com/members/alfredlionel.html) disagrees: not got the output needed I need only the highest and the lowest numbet to be displayed

Excuse me, but that's what the TOP 1 qualifier does. In other SQL dialects TOP might be replaced by a different keyword. To get both highest and lowest you change the sort order.

You might try understanding the answer before you mistakenly rate it. And James has a very valid point. There is very likely to be multiple people with the same age. Its not a good idea to store age since that changes. Better to store DOB.

pandydurai
Sep 10, 2007, 12:29 PM
Nosnosa's query is easy.. the other way would be use a union operator which simply combines both queries and returns required values