Brian Brian - 4 years ago 211
SQL Question

Importance of WHERE 1 in MySQL queries

When making a MySQL query with no WHERE constraints, most people use WHERE 1 in the query. However, omitting WHERE 1 does not influence the query. Is there a difference between the two? Is one considered to be the best practice?

Answer Source

I don't think it's a matter of best practice, but people sometimes use it to make building dynamic queries a bit easier.

string sql = "SELECT * FROM mytable WHERE 1 ";
if ( somecondition ) {
   sql += "AND somefield = somevalue ";

if ( someothercondition ) {
   sql += "AND someotherfield = someothervalue ";

... etc

Without the WHERE 1 in there I would need to check in each if block whether I needed to put in a WHERE or an AND.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download