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

隐身守侯 提交于 2019-11-28 10:12:16

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

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'";
}

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 ...).

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.

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.

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

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