SQL: Where 1=1 and 1=2

In SQL, would you mind explaining the following:

when to use where 1=1, 
when to use where 1=2, 
when to use where 1=1 and 1=2? 

It would be great to explain with some examples. Thank you!

  1. WHERE 1=1 表示always true, 有时会用于SQL代码生成:
base_query = "SELECT * FROM table_name WHERE 1=1 "
if (some_condition)
    base_query += "AND column1 = value1 "
if (another_condition)
    base_query += "AND column2 = value2 "

WHERE 1=1 ,你可以用AND 添加其他条件,不需要检查它是否是第一个条件。

  1. WHERE 1=2, always false:
SELECT * FROM table_name WHERE 1=2;

这个query不会返回任何数据,但会给column names aka metadata.经常用于把table structure copy给另一个table

  1. where 1=1 and 1=2 感觉一般不会这么写…
1 个赞