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

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

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

If you automatically want to add restrictions to your query, it makes your life 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 ...).

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