I find that sometimes, my results are incorrectly sorted with the following SQL (MySQL) query:
SELECT u.id, u.firstName, u.lastName, u.email, u.ssoProfile, u.vip, SUM(p.number) AS totalPoints
FROM (
SELECT u.id FROM user u
ORDER BY u.firstName ASC, u.lastName ASC, u.email ASC
LIMIT 100, 10
) u2
INNER JOIN `user` u
ON u2.id = u.id
LEFT JOIN `point` p
ON u.id = p.user
AND p.expiryDate > NOW()
GROUP BY u.id
As you can see I sorted by users in the subquery. However, I noticed sometimes, very rarely, I get results that do not follow the specified order. I think I need to order by on the outer query? But I want to understand whats wrong with this query. Why are my users' order messed up?
UPDATE
I've added an order by to the outer query. And surprisingly, I find that my results can still be returned in the wrong order
SELECT u.id, u.firstName, u.lastName, u.email, u.ssoProfile, u.vip, SUM(p.number) AS totalPoints
FROM (
SELECT u.id FROM user u
ORDER BY u.firstName ASC, u.lastName ASC, u.email ASC
LIMIT 100, 10
) u2
INNER JOIN `user` u
ON u2.id = u.id
LEFT JOIN `point` p
ON u.id = p.user
AND p.expiryDate > NOW()
GROUP BY u.id
ORDER BY u.firstName ASC, u.lastName ASC, u.email ASC
The results come back like:
[ { id: 4834, firstName: 'F01', lastName: 'L01' },
{ id: 4835, firstName: 'F00', lastName: 'L00' }, // << notice F00 is after F01?
{ id: 4836, firstName: 'F02', lastName: 'L02' },
{ id: 4837, firstName: 'F03', lastName: 'L03' },
{ id: 4838, firstName: 'F04', lastName: 'L04' },
{ id: 4839, firstName: 'F05', lastName: 'L05' },
{ id: 4840, firstName: 'F06', lastName: 'L06' },
{ id: 4841, firstName: 'F07', lastName: 'L07' },
{ id: 4842, firstName: 'F08', lastName: 'L08' },
{ id: 4843, firstName: 'F09', lastName: 'L09' } ]
@lad2025 mentioned that it could be because of my incorrect use of GROUP BY in the comments. However, I checked the IDs match. Meaning F00 does belong to user ID 4835 for example.