What does it mean by select 1 from table?

前端 未结 15 1833
南方客
南方客 2020-12-07 07:32

I have seen many queries with something as follows.

Select 1  
From table

What does this 1 mean, how will it be executed and,

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 08:02

    Although it is not widely known, a query can have a HAVING clause without a GROUP BY clause.

    In such circumstances, the HAVING clause is applied to the entire set. Clearly, the SELECT clause cannot refer to any column, otherwise you would (correct) get the error, "Column is invalid in select because it is not contained in the GROUP BY" etc.

    Therefore, a literal value must be used (because SQL doesn't allow a resultset with zero columns -- why?!) and the literal value 1 (INTEGER) is commonly used: if the HAVING clause evaluates TRUE then the resultset will be one row with one column showing the value 1, otherwise you get the empty set.

    Example: to find whether a column has more than one distinct value:

    SELECT 1
      FROM tableA
    HAVING MIN(colA) < MAX(colA);
    

提交回复
热议问题