patternMajor
Good, Bad or Indifferent: WHERE 1=1
Viewed 0 times
wherebadindifferentgood
Problem
Given this question on reddit, I cleaned up the query to point out where the issue was in the query. I use comma first and
Someone basically said that 1=1 is generally lazy and bad for performance.
Given that I don't want to "prematurely optimize" - I do want to follow good practices. I've looked at the query plans before, but generally only to find out what indexes I can add (or adjust) to make my queries run faster.
The question then really... does
Minor Edit: I've always 'assumed' as well that
I'm not one to optimize, unless needed... but if I'm doing something that is actually "bad", I'd like to minimize the effects or change where applicable.
WHERE 1=1 to make modifying queries easier, so my queries generally end up like this:SELECT
C.CompanyName
,O.ShippedDate
,OD.UnitPrice
,P.ProductName
FROM
Customers as C
INNER JOIN Orders as O ON C.CustomerID = O.CustomerID
INNER JOIN [Order Details] as OD ON O.OrderID = OD.OrderID
INNER JOIN Products as P ON P.ProductID = OD.ProductID
Where 1=1
-- AND O.ShippedDate Between '4/1/2008' And '4/30/2008'
And P.productname = 'TOFU'
Order By C.CompanyNameSomeone basically said that 1=1 is generally lazy and bad for performance.
Given that I don't want to "prematurely optimize" - I do want to follow good practices. I've looked at the query plans before, but generally only to find out what indexes I can add (or adjust) to make my queries run faster.
The question then really... does
Where 1=1 cause bad things to happen? And if so, how can I tell?Minor Edit: I've always 'assumed' as well that
1=1 would be optimized out, or at worst be negligible. Never hurts to question a mantra, like "Goto's are Evil" or "Premature Optimization..." or other assumed facts. Wasn't sure if 1=1 AND would realistically affect query plans or not. What about in subqueries? CTE's? Procedures?I'm not one to optimize, unless needed... but if I'm doing something that is actually "bad", I'd like to minimize the effects or change where applicable.
Solution
The SQL Server parser optimizer has a feature called "Constant Folding" that eliminates tautological expressions from the query.
If you look at the execution plan, nowhere in the predicates you will see that expression appear. This implies that constant folding is performed anyway at compile time for this and other reasons and it has no effect on query performance.
See Constant Folding and Expression Evaluation During Cardinality Estimation for more info.
If you look at the execution plan, nowhere in the predicates you will see that expression appear. This implies that constant folding is performed anyway at compile time for this and other reasons and it has no effect on query performance.
See Constant Folding and Expression Evaluation During Cardinality Estimation for more info.
Context
StackExchange Database Administrators Q#33937, answer score: 21
Revisions (0)
No revisions yet.