I am using Apache Derby 10.8 if that matters.
I have a very simple database with a table full of elements and a table full of bids for these elements. I want to select each item with the highest bid for this item attached to it. The following is my first attempt, and the performance is terrible:
select item.id as item_id, item.name as item_name, item.retail_value as item_retail_value, item.vendor as item_vendor, bid.bid_amount as bid_amount, bid.bidder_name as bid_bidder_name, bid.bidder_phone as bid_bidder_phone, bid.operator_name as bid_operator_name from item left outer join bid on bid.item_id = item.id and bid.bid_amount = (select max(bid.bid_amount) from bid where bid.item_id = item.id and bid.status = 'OK')
I created a test data set that uses 282 elements with 200 bids for each element (a total of 56,400 bids). The above request takes about 30-40 seconds. If I select each item and manually iterate over items that select high bids for each, it takes less than a second.
I tried indexing the bid.bid_amount and bid.status , but that didn't do anything noticeable. SQL is not my strongest area, so if someone wants to explain why , this query is so slow that I am very grateful.
source share