- You have to specify
ORDER BY
to define some sorting of the rows.
- I believe any solution for MySQL would effectively mean that your query is executed at least twice, so it is really better to do it on the client.
If you are OK with running the same query twice, then do something like this.
Get the ID of the last row first:
SELECT @LastID := ID
FROM ...
WHERE ...
GROUP BY ...
ORDER BY ID DESC
LIMIT 1;
Use that ID in the main query:
SELECT *
, CASE WHEN ID = @LastID THEN FALSE ELSE TRUE END AS IsLast
FROM ...
WHERE ...
GROUP BY ...
ORDER BY ID ASC;
As is, most likely it will break if the table is updated while these two queries run (the remembered ID may become not the last one if rows are added or deleted, unless you do something to address this issue).
Of course, you can put it all into one query:
SELECT
*,
CASE WHEN ID = LastID THEN FALSE ELSE TRUE END AS IsLast
FROM
YourTable
CROSS JOIN
(
SELECT ID AS LastID
FROM YourTable
ORDER BY ID DESC
LIMIT 1
) AS TableLastID
ORDER BY ID ASC;
You need to check whether MySQL is smart enough to run the inner SELECT LIMIT 1
only once or it will run it for every row of the main table. Still, even in the best case the query is effectively executed twice.