Performance of COUNT (*) and COUNT (1)

14

What is the difference between COUNT(1) and COUNT(*) in an SQL query.

For example:

SELECT COUNT(1) FROM USUARIOS; 

and

SELECT COUNT(*) FROM USUARIOS; 
  • Is there any difference in interactions within SBGD?
  • Which would be faster?
  • Would it depend on the DBMS I'm using?
asked by anonymous 20.06.2017 / 19:41

4 answers

4

What database are you talking about? In what database? When speaking of performance it is difficult to make definitive assertions. It may change according to the implementation, so SQL Server can do one thing and PostgreSQL give another. It can change from one version to another, it can change according to the configuration of that bank or the whole system. It may vary according to the data stored. Performance depends on the implementation detail.

If the database optimizer thinks it should be exactly the same.

Note that the syntax there is very simple. In more complex queries ( JOIN ) may not even give the expected result when using COUNT(1) . Otherwise the fact of having a constant in place of all fields will not differ because the count will be made on all lines that pass through the filter.

You have a excellent answer about this in the OS .

    
06.07.2017 / 15:31
3

The queries of Count (*) or Count (column or anything else), have no difference in performance levels, even was one of the subjects discussed in the blog of Gustavo Maia in the category "SQL Server Myths", more details in:

link

More in good practice it is advisable to put the column name as long as the NOT NULL column.

    
23.06.2017 / 14:23
1

The difference is simple:

  • COUNT (*) will count the number of records.
  • COUNT (column_name) will count the number of non-null records.
19.10.2017 / 21:02
0

The two selects have no difference in performance.

In both cases, it counts all values in the table, even if the columns are null. To count the rows, SQL scans the entire table (Table Scan) and then performs COUNT (Stream Aggregate) operations.

    
06.07.2017 / 16:12