I am trying to find if the below is a well documented pattern (or anti-pattern for that matter) for reducing application latency. I have tried this technique and on face this looks to be saving me some 20% in latency. I would like to know if there are any side affects that I should be aware of
Context:
You have got a method/function/procedure which makes multiple SELECT calls to database and you need to optimize it.
lets say the flow of your method is :
getDBConnection()
execute("Select a,b from tableA");
bind a with varA
bind b with varB
---SOME Business Logic-----
execute("Select c,d from tableB");
bind c with varC
bind d with varD
---SOME more Business Logic-----
execute("Select e,f from tableC");
bind e with varE
bind f with varF
---SOME more Business Logic-----
releaseConnection()
Solution :
Use Union ALL to make a single call to Database
getDBConnection()
execute("Select a,b,'sqlA' from tableA"+
" UNION ALL "+
" Select c,d,'sqlB' from tableB"+
" UNION ALL "+
"Select e,f,'sqlC' from tableC");
bind a,b where records have "sqlA"
bind c,d where records have "sqlB"
bind e,f where records have "sqlC"
releaseConnection()
--------Do all Business Logic here-----
The use of
unionlimits the “shape” of your queries. They basically have to all return the same number and (compatible) types of columns, in the same order.A better approach would be to use multiple queries in a single command and then deal with multiple result sets:
Or maybe create a dedicated stored procedure that runs these queries.
Apart from this, this optimization technique can lump together unrelated operations, which will limit the reusability of individual operations later on. You might want to consider a design that better separates these operations and uses some kind of
QueryManagerto first collect them and later run them all together.