Question

Here's an example (which doesn't make sense, but good as an example)

t = DimensionType.arel_table

q = t.where(
          t[:label].eq('a').and(t[:label].eq('b'))
      .or(t[:label].eq('c').and(t[:label].eq('d')))
      .or(t[:label].eq('e').and(t[:label].eq('f')))
      .or(t[:label].eq('g').and(t[:label].eq('e')))
  ).to_sql

 puts q

Here's the output:

SELECT FROM "dimension_types"  WHERE ((("dimension_types"."label" = 'a' AND "dimension_types"."label" = 'b' OR "dimension_types"."label" = 'c' AND "dimension_types"."label" = 'd') OR "dimension_types"."label" = 'e' AND "dimension_types"."label" = 'f') OR "dimension_types"."label" = 'g' AND "dimension_types"."label" = 'e')

What purpose do the parentheses serve? If none, how to avoid having them? They put the where part in a kind of hierarchical structure which might possibly impact query optimization.

EDIT: the intent is to have a query like this (in a contrived meta language):

(a and b) or (b and c) or (d and e)

which is the same without parentheses because and takes precedence over or

a and b or b and c or d and e

Correct me pls if I'm wrong.

Was it helpful?

Solution

The parentheses change the order of precedence of the boolean operators and act to combine logic together. Without them the meaning is completely different (based on left-to-right reading order and relative precedence of AND/OR).

In simple term, without the parens AND is always evaluated before OR.

These are not equivalent

 A and B or C
 A and (B or C)

The first one evaluates A and B, then ors with C. The second ors B & C before anding with A.

The parentheses ensure specific logical grouping is performed in a specific order.

Update:

In your specific case you are wanting all ANDs to evaluate before ORs, but LINQ converts logic to SQL by navigating a logic "tree" behind the scenes and you have no control over that process. It does it to ensure the result is what you intended, which will often mean extra parentheses.

As the majority of processing time is in getting the data from the drives, not evaluating the parentheses in the SQL, you are worrying unnecessarily. You can assume that any optimization will work at a broader level and still work despite the parentheses (in fact it may even work more efficiently) :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top