WHERE clause with multiple AND statements

11 views
Skip to first unread message

Thomas Devoogdt

unread,
Sep 6, 2017, 11:51:39 AM9/6/17
to python-sql
Is there a reason why multiple AND statements are converted like this.


(stm1) & (stm2) & (stm3)

->

(((stm1) AND (stm2)) AND (stm3))

and not

((stm1) AND (stm2) AND (stm3))


Thanks in advance.

Cédric Krier

unread,
Sep 6, 2017, 12:25:05 PM9/6/17
to python-sql
This is because '&' which is __and__ operator in Python is binary and
Python evaluate from left to the right.
So the first "(stm1) & (stm2)" is evaluated which result in the
construction of "And((stm1, stm2))".
After that "And((stm1, stm2)) & (stm3)" is evaluated which result in the
construction of "And((And((stm1, stm2)), stm3))" which is the expression
you get.

If you really want to have your simplified version, you must use the And
operator instead of the syntax sugar __and__:

And((stm1, stm2, stm3))

Now I anticipate the question about optimizing the __and__ operator to
append to the first And instead of encapsulate. I think it is an
optimization that will increase code complexity for a very small gain (2
chars).

--
Cédric Krier - B2CK SPRL
Email/Jabber: cedric...@b2ck.com
Tel: +32 472 54 46 59
Website: http://www.b2ck.com/
Reply all
Reply to author
Forward
0 new messages