Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   MySQL (https://www.askmehelpdesk.com/forumdisplay.php?f=442)
-   -   How to get only the highest and the lowest number as output in a set of data (https://www.askmehelpdesk.com/showthread.php?t=115762)

  • Aug 2, 2007, 06:41 AM
    alfredlionel
    How to get only the highest and the lowest number as output in a set of data
    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.
  • Aug 2, 2007, 06:49 AM
    ScottGem
    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.
  • Aug 2, 2007, 03:29 PM
    Nosnosna
    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)
  • Aug 2, 2007, 03:42 PM
    ScottGem
    Comments on this post
    alfredlionel 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.
  • Sep 10, 2007, 12:29 PM
    pandydurai
    Nosnosa's query is easy.. the other way would be use a union operator which simply combines both queries and returns required values

  • All times are GMT -7. The time now is 08:47 PM.