Why would someone use WHERE 1=1 AND <conditions>
in a SQL clause (Either SQL obtained through concatenated strings, either view definition)
I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.
If there is injection WHERE 1 = 1 AND injected OR 1=1
would have the same result as injected OR 1=1
.
Later edit: What about the usage in a view definition?
Thank you for your answers.
Still, I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.
Take this for example:
CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 AND table.Field=Value
Using a predicate like
1=1
is a normal hint sometimes used to force the access plan to use or not use an index scan. The reason why this is used is when you are using a multi-nested joined query with many predicates in the where clause where sometimes even using all of the indexes causes the access plan to read each table - a full table scan. This is just 1 of many hints used by DBAs to trick a dbms into using a more efficient path. Just don't throw one in; you need a dba to analyze the query since it doesn't always work.Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.
Just adding a example code to Greg's answer:
Indirectly Relevant: when 1=2 is used:
CREATE TABLE New_table_name as select * FROM Old_table_name WHERE 1 = 2;
this will create a new table with same schema as old table. (Very handy if you want to load some data for compares)
Here's a closely related example: using a SQL
MERGE
statement to update the target tabled using all values from the source table where there is no common attribute on which to join on e.g.I've seen homespun frameworks do stuff like this (blush), as this allows lazy parsing practices to be applied to both the
WHERE
andAND
Sql keywords.For example (I'm using C# as an example here), consider the conditional parsing of the following predicates in a Sql query
string builder
:The "benefit" of
WHERE 1 = 1
means that no special code is needed:AND
is required. Since we already have at least one predicate with the1 = 1
, it meansAND
is always OK.WHERE
must be dropped. But again, we can be lazy, because we are again guarantee of at least one predicate.This is obviously a bad idea and would recommend using an established data access framework or ORM for parsing optional and conditional predicates in this way.