13

In my SQL query I am selecting data with GROUP BY and ORDER BY clauses. The table has the same numbers across multiple rows with different times in each row. So I think I want to apply a GROUP BY clause.

However in the results return the oldest time with the number, but I need the most recent time.

SELECT * FROM TABLE GROUP BY (numbers) ORDER BY time DESC

The query appears as if it should first apply GROUP BY and then ORDER BY... but the results do not appear to work this way.

Is there any way to fix this?

4
  • 3
    In the docs the behaviour you get if you select columns that are not grouped by is explicitly called out as "indeterminate" in the event that they have multiple values per group. You can't rely on any particular behaviour. Do you need the whole row or just numbers, max(time) Commented Sep 5, 2011 at 9:24
  • Can you provide some rows of data with the result you expect ? Commented Sep 5, 2011 at 9:24
  • Thanks guys, you moved me to the right direction. Commented Sep 5, 2011 at 9:39

5 Answers 5

22
SELECT * 
FROM table t
WHERE time = (
    SELECT max(time)
    FROM table
    WHERE t.numbers = numbers
)
1
  • When I try to run this query on a dummy table, somehow I end up getting all the rows. Removing the WHERE inside subquery works for me, however. Commented Apr 14, 2021 at 13:42
18

work-around is to re-write the query as:

SELECT * FROM (SELECT * FROM table ORDER BY time DESC) AS t GROUP BY numbers;
10
  • 5
    In theory you cannot guarantee that you will always get the same result.
    – Karolis
    Commented Sep 5, 2011 at 9:44
  • 1
    @Karolis agreed, your answer seems to be the more correct one
    – feeela
    Commented Sep 5, 2011 at 9:59
  • 4
    This uses a MySQL extension to group by that is explicitly documented not work reliably: dev.mysql.com/doc/refman/5.7/en/group-by-extensions.html. Commented Sep 7, 2014 at 3:13
  • 1
    @GordonLinoff I guess this is why it didn't work for me, thanks for mentioning that Commented Sep 9, 2016 at 20:37
  • @GordonLinoff Link is broken. Any idea for what I should be searching for? Thanks
    – Houman
    Commented May 28, 2018 at 15:17
3
SELECT * FROM table
    WHERE time IN (
        SELECT MAX(time)
            FROM table
            GROUP BY numbers
    )
2
0

According to the manual you can add desc to the group by list: Example:
group by item1, item2 desc, item3

with or without rollup.

I've tried this and it works in Ubuntu version 5.5.58. The reference page is: https://dev.mysql.com/doc/refman/5.7/en/group-by-modifiers.html

-6
SELECT * FROM TABLE GROUP BY numbers DESC;

This will give you last record from group.

Thanks

1
  • This doesn't answer the question. They want to order before grouping. Commented Oct 22, 2015 at 12:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.