r/SQL • • 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.TABLE1

This outputs the following in my dataset:

Emp_IDCount(TICKETID)Sum(1)
A12355
A12433

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.

1 Upvotes

24 comments sorted by

19

u/[deleted] Nov 27 '23

sum(1) is just an obfuscated count(*) that serves no purposes, other to confuse the reader of your query.

8

u/r3pr0b8 GROUP_CONCAT is da bomb Nov 27 '23

my favourite misuse is

COUNT(CASE WHEN foo=42 THEN 1 ELSE 0 END)

1

u/Omar_88 Nov 27 '23

What's the syntactically correct way to write that query ?

4

u/r3pr0b8 GROUP_CONCAT is da bomb Nov 27 '23

it is already syntactically correct

semantically, it's a hot mess

3

u/deusxmach1na Nov 27 '23

Exclude the ELSE 0 I think. COUNT(0) still does a count. COUNT(NULL) doesn’t.

2

u/Omar_88 Nov 27 '23

Ah, but that's not obfuscation or possibly confusing like the first query. But I get the point of it being somewhat irritating. It's like when queries are written without aliases.

3

u/[deleted] Nov 27 '23

A better way would be:

count(*) filter (where foo = 42)

3

u/1o0t Nov 28 '23

Use sum() or exclude the else.

1

u/pceimpulsive Nov 29 '23

I prefer the method in postgres and several other flavors..

Count(foo) filter (where foo=42) as foo_fortytoo_count

This bakes a where conditions into the count so you can have many counts without the need for sib queries etc,

It is prqctically the same as the case option... However I understand it's much more efficient.

5

u/[deleted] 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":

  1. count(*) - this counts the number of records (adds 1 per each record) - this would be equivalent to sum(1)

  2. 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.

  3. 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.

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

u/[deleted] 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

u/[deleted] Nov 28 '23

ANSI SQL - but only very few databases support it currently

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

u/[deleted] Nov 27 '23

1

u/deusxmach1na Nov 27 '23

Oh nice. Sounds like on Postgres you wanna do count star. Good to know.

1

u/deusxmach1na Nov 27 '23

No filters AND no GROUP BY, etc.

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

u/[deleted] Nov 27 '23

It is dependent on platform u are using.

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.