What does “select count(1) from table_name” on any database tables mean?

前端 未结 9 585
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 18:38

When we execute select count(*) from table_name it returns the number of rows.

What does count(1) do? What does 1 signify here

相关标签:
9条回答
  • 2020-12-22 19:25

    The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.)

    There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained.

    Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).

    0 讨论(0)
  • 2020-12-22 19:28

    This is similar to the difference between

    SELECT * FROM table_name and SELECT 1 FROM table_name.  
    

    If you do

    SELECT 1 FROM table_name
    

    it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

    0 讨论(0)
  • 2020-12-22 19:32
    SELECT COUNT(1) from <table name>
    

    should do the exact same thing as

    SELECT COUNT(*)  from <table name>
    

    There may have been or still be some reasons why it would perform better than SELECT COUNT(*)on some database, but I would consider that a bug in the DB.

    SELECT COUNT(col_name) from <table name>
    

    however has a different meaning, as it counts only the rows with a non-null value for the given column.

    0 讨论(0)
提交回复
热议问题