If I want to fetch data from a table, and filter it later, will it be a better idea than running a condtional MySQL query?
Example -
list.stream.filter(x-> x.getSalary() > baseSalary).collect(Collectors.toList());
select * from employees where salary > 10000;
, Running this query through JPA.
Which is faster? Should we depend on the DB Engine for faster results or handling this in our code makes it better. The above is just an example, please don't consider that as real time.
No, it is never a good idea to filter in java the result of the DB query. First, your unfiltered select may bring the un-known amount of records most of which you didn't need in the first place. You will not only waste the network load but also the memory of your java process, and time first to bring the info over and then to iterate through a much longer list than needed and filter it. DB is designed for "heavy lifting" on data and you should utilize it. Also, there is a general rule of thumb: perform logical operations on data as close as possible to the data. I.e. in your case fetch and filter your data in DB before sending it over to the next "station" - your java server-side
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With