6
Reply

When and why you should use 1=1 in WHERE clause?

    When ever you want to build or create dynamic SQL and when you writing condition but you do not know whether your dynamic query has where clause or not. Use where 1=1 to make sure your dynamic query has where clause

    This will select all records from the mentioned table. Usually used in SQL injection to retrieve all data from Table.

    when we want to retrieve all record of a table..........

    I some time use 1=1 for checking sql injection attack possibilty

    it shows the all records from table

    If you don't know  the list of conditions at compile time and it will built at run time, Then you can made a condition with “where 1=1”. and for other conditions that will affect run time, use
    and .

    1. StringBuilder sb = new StringBuilder();  
    2.          sb.Append("SELECT * FROM Products");  // Your query  
    3.          sb.Append(" WHERE 1=1"); // always true condition  
    4.          // append query's where clause  
    5.          if (catID != 0)  
    6.          {  
    7.              sb.Append(" AND categoryID= {0}", catID);  
    8.          }  
    9.          if (minPrice > 0)  
    10.          {  
    11.              sb.Append(" AND itemPrice >= {0}", minPrice);  
    12.          }  
    13.          SqlCommand cmd = new SqlCommand(sb.ToString(), cnn);  
    14.          SqlDataReader dr = cmd.ExecuteReader();  
    15.          // your code to read data from dr.