What does “WHERE 1” mean in SQL?

后端 未结 3 1206
情话喂你
情话喂你 2021-01-03 21:37

Sometimes phpMyAdmin generates queries like:

SELECT * 
FROM  `items` 
WHERE 1 
LIMIT 0 , 30

I wonder if WHERE 1 has any meanin

3条回答
  •  天涯浪人
    2021-01-03 22:30

    It doesn't. It means ALWAYS TRUE so it won't have any filtering impact on your query. Query planner will probably ignore that clause.

    It's usually used when you build a client side query by concatenating filtering conditions.

    So, if your base query is stored in a string like this (example is in PHP, but it certainly applies to many other languages):

    $sql = "select * from foo where 1 ";
    

    Then you can just concatenate a lot of filtering conditions with an AND clause regardless of it being the first condition you are using or not:

    // pseudo php follows...
    if ($filter_by_name) {
        $sql = $sql . " and name = ? ";
    }
    if ($filter_by_number) {
        $sql = $sql . " and number = ? ";
    }
    // so on, and so forth.
    

提交回复
热议问题