0 votes
1 view
in SQL by (20.3k points)

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:


SELECT FROM Table WHERE 1=1 AND table.Field=Value

1 Answer

0 votes
by (40.4k points)

You don't have to worry about whether you have one or more than one condition, if the list of conditions are built at run time, instead of knowing them at compile time.

You can create them all like this:

and <condition>

and keyword is used to concatenate all of them. With 1=1 at the start, the initial and keyword has something to associate with.

Generally, this won’t be used for any kind of injection protection, for implementation convenience it can be used. The SQL query engine will end up ignoring 1=1 hence, it will not have any performance impact.

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !