I agree with the previous commenters regarding making sure that you have an optimized database. Correct indices are critical
Since you haven't provided any perl code, we can't give you very much advice. What I can offer, is that I often read data from a database and load it into a perl HashRef that is shaped in a way to allow me to access the data very directly for my purpose. This assumes that the data can fit within memory. See perlref and perlreftut for information on references if you are not familiar with them.