I’m trying to optimize a query where I’ve concluded that the order doesn’t matter. So I’m trying to remove ORDER BY in the following scenario:
SELECT item, price FROM supplydemand
GROUP BY item
ORDER BY timestamp ASC
Here’s what’s going on: the table supplydemand keeps track of prices for various items. For every item I have 4 or 5 different prices, and therefore different rows. The query above gives me the “oldest” price per item. The grouping is done on item, and the ascending timestamp gives me the oldest row. This query works correctly.
I’ve noticed that as long as I have the oldest price, I don’t actually care if the returned rows are sorted. So I wanted to get rid of ORDER BY. Here’s what I’ve tried:
SELECT item, price, timestamp FROM supplydemand
GROUP BY item
HAVING timestamp = MIN(timestamp)
The query above should result in an identical data except not sorted. The MIN inside of HAVING has to rely on the GROUP therefore comparing the timestamp of every grouped item to the oldest timestamp within the group.
The Problem
The second query returns less rows. For some reason certain rows are missing from the second query, and I cannot figure out why. The remaining rows return identical price, but I’m missing almost 20% of the data.
would be one way.