Why would a sql query have “where 1 = 1” [duplicate]

坚强是说给别人听的谎言 提交于 2019-12-28 15:36:55

问题


I was going through a few queries I am maintaining, and a programmer had put in the queries "where 1=1" to me that always seems to evaluate to true.

Are there benefits to this?

Duplicate: Why would someone use WHERE 1=1 AND in a SQL clause?

That question isn't an answer to this question.

Where-clause:

select * from table where 1=1 and sStatus not in ('status1','status2','status3')

No programming or if statements to push an and in there. A straight query.

If you could un-close this, I would like to know whether there is a purpose so that I may rewrite and remove the 1=1 if it is unnecessary.


回答1:


Was it dynamic queries? Sometimes that's helpful when building dynamic queries based on parameters that are optional.




回答2:


If you automatically want to add restrictions to your query, it makes your live easier:

string sql = "SELECT * FROM table WHERE 1=1";

if (someflag) {
  sql += " AND valid = 1";
}

if (someotherflag) {
  sql += " AND special = 1";
}

execute(sql);

Without WHERE 1 = 1 you would in each case have to check if it's the first restriction you add (and then use WHERE ...) or if you already added some other restriction before (and then add AND ...).




回答3:


If you are dynamically building a where clause, you can be a bit lazy and assume that every clause you add can be prefixed with "AND", e.g.

$str="select foo from bar where 1=1";

if ($filter1)
{
    $str.=" and col1='frobozz'";
}



回答4:


I use this for dynamic where clauses when I'm doing some lazy programming and don't want to always check if the clause is empty to determine if I now need an "AND" between my dynamic clauses.




回答5:


This really only makes sense in dynamic queries. If you are adding parameters in a loop instead of having to check if there is a WHERE already you can just append AND Column = Value every time.




回答6:


I've seen two reasons for this, when you always want a true result, or when there is going to be an arbitrary number of "and condition = value" appended to the statement




回答7:


That is very interesting... The WHERE clause contains nothing but 1=1? I have seen this frequently in SQL injection attempts in which the WHERE clause is set to xyz="something" OR 1=1; as a means to always return a list of results.

Can you tell us more about what is going on with this query so we might be able to answer the question better?

  • Nicholas


来源:https://stackoverflow.com/questions/517107/why-would-a-sql-query-have-where-1-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!