Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 471
Jeremy Boyd Avatar asked Feb 05 '09 18:02

Jeremy Boyd


People also ask

What does where 1 1 mean in SQL?

Essentially, where 1 = 1 means no where clause. It will always be true, so all records will be returned. Some people believe, erroneously, that it makes queries go faster. In most cases, it is useless, and the Optimizer will often optimize it away.

What does where 1/2 mean in SQL?

The reason you put the WHERE 1=2 clause in that SELECT INTO query is to create a field-copy of the existing table with no data. If you did this: select * into Table2 from Table1. Table2 would be an exact duplicate of Table1 , including the data rows.

Can you use where clause twice in SQL?

But yes, you can use two WHERE.

What does select 1 from do?

The statement 'select 1' from any table name means that it returns only 1. For example, If any table has 4 records then it will return 1 four times.


2 Answers

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

like image 122
Tundey Avatar answered Oct 16 '22 21:10

Tundey


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

like image 20
sth Avatar answered Oct 16 '22 21:10

sth