Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
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:

CREATE VIEW vTest AS

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

1 Answer

0 votes
by (40.7k 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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...