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.
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.
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.
But yes, you can use two WHERE.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With