Tech Tip: Efficient 4D Queries
PRODUCT: 4D | VERSION: 11 | PLATFORM: Mac & Win
Published On: April 16, 2009
Consider the following typical construction of a compound 4D QUERY. It first gets a selection of records and then performs a follow-on compound QUERY SELECTION. It is easy to understand but is it the most efficient way to perform this query?
QUERY([Table_1];[Table_1]Field_A=a;*) QUERY([Table_1];&;[Table_1]Field_B=b) QUERY SELECTION([Table_1];[Table_1]Field_C=c;*) QUERY SELECTION([Table_1];|;[Table_1]Field_D=d) |
Consider the following rewrite of the query:
QUERY([Table_1];[Table_1]Field_C=c;*) QUERY([Table_1];|;[Table_1]Field_D=d;*) QUERY([Table_1];&;[Table_1]Field_A=a;*) QUERY([Table_1];&;[Table_1]Field_B=b) |
Within the 4D Query parsing engine, 4D is actually always grouping the previous conditions when it builds its query plan and query path. So A | B | C is equivalent to (A | B) | C. This results in:
A | = A |
(A) | B | = A | B |
((A) | B) | C | = A | B | C |
(((A) | B) | C) & D | = (A | B | C) & D |
((((A) | B) | C) & D) & E | = (A | B | C) & D & E |
(((((A) | B) | C) & D) & E) | F | = ((A | B | C) & D & E) | F |
So there's no special code to handle similar consecutive conjunctions, it's just how boolean logic works.
The revised query may not be as easily understood, since BOOLEAN logic is not always readily equated to human reasoning. But if you understand how the grouping is done by 4D internally, it can help you write more efficient queries. One query plan and one query path is typically going to be more efficient than two.
Commented by Atanas Atanassov on May 29, 2009 at 4:14 PM
"Get Last Query Plan" and "Get Last Query Path" are great tools for query optimization.