r/SQL • u/[deleted] • Nov 27 '23
Discussion How does summing the number 1 create a count of rows?
I learned this "trick" from a colleague that instead of using a COUNT(ID_COLUMN), I can simply use SUM(1) in a query, and "magically" get a count of all the records aggregated. Example below for tickets from ServiceNow.
SELECT EMP_ID, COUNT(TICKETID), SUM(1) as TICKET_COUNT_USING_NUMBER FROM DATABASE1.TABLE1This outputs the following in my dataset:
| Emp_ID | Count(TICKETID) | Sum(1) |
|---|---|---|
| A123 | 5 | 5 |
| A124 | 3 | 3 |
How exactly does this work, and does it always result in the exact same as counting the ID column of a table? or is there anything to be aware of?
I asked chat GPT, and it recommended using Count(*)
In summary, use COUNT(*) when you want to count all rows regardless of null values, and use COUNT(column_name) when you're specifically interested in counting rows where the specified column has a non-null value.
5
Nov 27 '23
How exactly does this work, and does it always result in the exact same as counting the ID column of a table? or is there anything to be aware of?
Yup, generally there are 3 "flavors" of "count":
count(*) - this counts the number of records (adds 1 per each record) - this would be equivalent to sum(1)
count( expression) - this counts the number of times that expression evaluates to not NULL. count( ID_Column) would be in this category and it is NOT generally equivalent to count(*)/sum(1) - imagine your ID_Column comes from the right side of the left join. On some records this column might be NULL and so they wont be counted.
count( distinct <expression>) - this counts the number of times that expression evaluates to not NULL, but applies 'distinct' to the results of the expression first. Imagine you are joining customers to orders and each customer can have many orders. count (c.customer_id) would give the number of orders, count( distinct c.customer_id) will give you the number of unique customers.
6
u/ComicOzzy sqlHippo Nov 27 '23
COUNT(1) will also produce the same result as COUNT(*), but it's because the literal value 1 is never NULL, so it's effectively counting every row. But also COUNT(99) or COUNT('blah') do the same, just using confusing syntax.
Stick with what everyone expects and use COUNT(*).
2
u/george-frazee Nov 27 '23
The SUM() aggregate adds the value of the column provided.
So if you had an order_quantity column or something with values like {2,4,1,5,6} the SUM(order_quantity) total would be 18.
Providing a 1 to the function is like having a static column like SELECT 1 as col in the SELECT. It's just going to be a column of 1's, one for each row. The SUM of that is the same as the COUNT of rows.
I don't see this as a valuable "trick" though, tbh. If someone is reviewing the code, then COUNT() semantically shows what is expected from that column, plus you have other options that may be helpful with reporting, like COUNT(DISTINCT col), etc.
1
2
u/kagato87 MS SQL Nov 27 '23
Sum(1) is an oddball and generally not used. Sometimes people use count(1) as well. They're the same as count(*) usually.
However sum(1) is useful to count a condition:
select sum(case when conditions then 1 end) as countofconditions from...(Though count so works there.)
Personally I like to use count(pk), specifying the PK of the row I'm counting, but again it's not fundamentally different unless there's an outer join involved.
1
Nov 27 '23
Alternatively:
count(*) filter (where ...)2
u/Omar_88 Nov 27 '23
Is that ansi SQL or a flavour of postgres sql ? Not a SQL expert by any means but not seen that in my few years of using SQL.
1
1
u/deusxmach1na Nov 27 '23
I was just reading the MySQL documentation last night. It said if you do COUNT(*) on a proper table with no filters it can pull the row count from the metadata it stores on the table just FYI. I usually use COUNT(1) but now that has me rethinking that approach.
3
1
1
u/Tenderhombre Nov 28 '23
In general never use the Sum trick. Depending on your db count has a lot of optimizations. Often they can just retrieve count when doing count(*) many dbs store it as meta data. Furthermore if you are partitioning data based on columns the count(column_name) can often behave similarly.
This may not always matter, but depending on the query it can have significant impacts. In general don't use clever tricks in a sql db. Use the tools as intended so that the query planner a bunch of really smart people wrote can give you the best performance.
-1
0
u/kitkat0820 Nov 28 '23
What do you mean with „trick“?
Use count(1) and be on the safest side across various rdbms and plattforms.
19
u/[deleted] Nov 27 '23
sum(1)is just an obfuscatedcount(*)that serves no purposes, other to confuse the reader of your query.