Where 1 1 sql зачем
Перейти к содержимому

Where 1 1 sql зачем

  • автор:

Why use WHERE 1 or WHERE 1=1?

Usually, if conditions are not required in our query statements, we don’t use a WHERE clause. But I’ve seen a WHERE 1 clause being used in many places, even where other conditions are not present.

  • Why is this done?
  • Are there specific benefits to the execution time?
  • Does it enable other functionalities?
  • Is using WHERE 1=1 similar to this?

D M's user avatar

ursitesion's user avatar

6 Answers 6

Basically it is just for programmer convenience since you can just add additional conditions with AND. after that and it has no impact on execution time.

Check out these links to Stackoverflow:

  • Why would someone use WHERE 1=1 AND in a SQL clause?
  • “where 1=1” statement

Note that WHERE 1 is identical to WHERE 1=1 ; both mean WHERE TRUE but the former is rejected by many database management systems as not really being boolean.

Twinkles's user avatar

My main use is that it makes it easier to comment out stuff during development of queries. I lead with , ‘s and and ‘s:

Also makes it easier to programmatically tack stuff unto the end.

Otherwise you’d have to qualify the first option. and have each following option check the previous options. What if the user only chose Option D in the previous example? You’d have to make sure that if A, B and C aren’t chosen then use WHERE else use and . With = at the start, you can just slap the qualifiers to the end of the statement.

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

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:

Sampson's user avatar

21 Answers 21

If the list of conditions is not known at compile time and is instead built at run time, you don’t have to worry about whether you have one or more than one condition. You can generate them all like:

and concatenate them all together. With the 1=1 at the start, the initial and has something to associate with.

I’ve never seen this used for any kind of injection protection, as you say it doesn’t seem like it would help much. I have seen it used as an implementation convenience. The SQL query engine will end up ignoring the 1=1 so it should have no performance impact.

Just adding a example code to Greg’s answer:

Eduardo Molteni's user avatar

I’ve seen it used when the number of conditions can be variable.

You can concatenate conditions using an » AND » string. Then, instead of counting the number of conditions you’re passing in, you place a «WHERE 1=1» at the end of your stock SQL statement and throw on the concatenated conditions.

Basically, it saves you having to do a test for conditions and then add a «WHERE» string before them.

Carl's user avatar

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.

Indirectly Relevant: when 1=2 is used:

this will create a new table with same schema as old table. (Very handy if you want to load some data for compares)

I found this pattern useful when I’m testing or double checking things on the database, so I can very quickly comment other conditions:

Carlos Toledo's user avatar

1 = 1 expression is commonly used in generated sql code. This expression can simplify sql generating code reducing number of conditional statements.

aku's user avatar

Actually, I’ve seen this sort of thing used in BIRT reports. The query passed to the BIRT runtime is of the form:

and the ‘?’ is replaced at runtime by an actual parameter value selected from a drop-down box. The choices in the drop-down are given by:

so that you get all possible values plus » * «. If the user selects » * » from the drop down box (meaning all values of a should be selected), the query has to be modified (by Javascript) before being run.

Since the «?» is a positional parameter and MUST remain there for other things to work, the Javascript modifies the query to be:

That basically removes the effect of the where clause while still leaving the positional parameter in place.

I’ve also seen the AND case used by lazy coders whilst dynamically creating an SQL query.

Say you have to dynamically create a query that starts with select * from t and checks:

  • the name is Bob; and
  • the salary is > $20,000

some people would add the first with a WHERE and subsequent ones with an AND thus:

Lazy programmers (and that’s not necessarily a bad trait) wouldn’t distinguish between the added conditions, they’d start with select * from t where 1=1 and just add AND clauses after that.

Navicat Blog

Have you ever seen a WHERE 1=1 condition in a SELECT query. I have, within many different queries and across many SQL engines. The condition obviously means WHERE TRUE, so it’s just returning the same query result as it would without the WHERE clause. Also, since the query optimizer would almost certainly remove it, there’s no impact on query execution time. So, what is the purpose of the WHERE 1=1? That is the question that we’re going to answer here today!

Does WHERE 1=1 Improve Query Execution?

As stated in the introduction, we would expect the query optimizer to remove the hard-coded WHERE 1=1 clause, so we should not see a reduced query execution time. To confirm this assumption, let’s run a SELECT query in Navicat both with and without the WHERE 1=1 clause.

First, here’s a query against the Sakila Sample Database that fetches customers who rented movies from the Lethbridge store:

The execution time of 0.004 seconds (highlighted with a red outline) can bee seen at the bottom of the Messages tab.

Now, let’s run the same query, except with the addition of the WHERE 1=1 clause:

Again, the execution time was 0.004 seconds. Although a query’s run time can fluctuate slightly, depending on many factors, it is safe to say that the WHERE 1=1 clause had no effect.

So, why use it then? Simply put, it’s.

A Matter of Convenience

The truth of the matter is that the WHERE 1=1 clause is merely a convention adopted by some developers to make working with their SQL statements a little easier, both in static and dynamic form.

In Static SQL

When adding in conditions to a query that already has WHERE 1=1, all conditions thereafter will contain AND, so it’s easier when commenting out conditions on experimental queries.

with _in_static_sql (35K)

This is similar to another technique where you’d have commas before column names rather than after. Again, it’s easier for commenting:

commas (19K)

In Dynamic SQL

It’s also a common practice when building an SQL query programmatically. It’s easier to start with ‘WHERE 1=1 ‘ and then append other criteria such as ‘ and customer.id=:custId’, depending on whether or not a customer ID is provided. This allows the developer to append the next criterion in the query starting with ‘and . ‘. Here’s a hypothetical example:

Conclusion

In this blog, we learned the answer to the age-old question of «what is the purpose of the WHERE 1=1?» It’s not an advanced optimization technique, but a style convention espoused by some developers.

SQL Where 1=1

The statement where 1=1 in SQL means true. It is the same operation as running the select statement without the where clause.

You might ask, what is the purpose of the clause where 1=1?

In most cases, you will only need to use this clause when you need to build dynamic SQL statements. Once you apply the where 1=1 clause, all the subsequent statements after it can start with the ‘and’ keyword.

It is more like a way to include exploratory SQL statements in a much lazy and convenient manner. It also allows you to comment out queries in a simple manner.

Consider an example where you are guessing an id of a column. Assuming you are not sure whether that id exists on the database, you can use something like where 1=1 to return all the rows even if the target id is not on the database.

The query above uses an or statement. Hence, only one of the conditions needs to be true for the query to work.

Even if there is no user with an id of 10, the 1=1 will always evaluate to true, and the query will fetch all the rows in the specified table.

Query Execution

If you are not hunting for information on databases, you will rarely need to concern yourself with the where 1=1 clause.

However, you may ask whether the clause improves the execution time.

The answer is No.

Setting the clause where 1=1 is the same as running the query without a where clause. Most database engines will remove the clause before executing the statement.

Conclusion

This short article describes what the SQL where 1=1 clause and why you can use it.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *