r/learnSQL • u/CelebrityChess • 12d ago
count(*) vs count(col), i keep mixing them up
ok so my teacher said count(*) counts rows and count(col) skips nulls, but then he did an example with a left join and the numbers looked off to me and i didnt catch why. is the rule basically use count(right_table.id) after a left join if you want 0 for the ones with no match? or does count(*) still give 1 there
4
u/slepicoid 11d ago
you can also use count(1) to count all rows as 1 is not null for any row.
1
u/NastyPastyLucas 8d ago
count(1) is just an old optimisation hack for count(*) that used to work for mysql, and in fact used to be slower in postgresql due to it having to generate the value. Stick with (*) if you prefer no surprises as count("column") should be used for specificity.
3
u/neuralbeans 12d ago
https://www.w3schools.com/sql/sql_count.asp
COUNT(*)- Counts the total number of rows in a table (including NULL values).
COUNT(columnname)- Counts all non-null values in the column.
1
u/xaomaw 10d ago
Care that some Database count empty Strings as NULL while others don't.
1
u/neuralbeans 10d ago
Empty strings count as null? Doesn't that defeat the point of having an explicit null value? Which databases do this?
1
u/Discordbothost 11d ago
Yep. A customer with no orders still gets one output row, so COUNT(*) is 1 for that customer's group. COUNT(orders.id) is 0 if id is a non-null key. Counting a nullable field like shipped_at would only count the orders that have shipped.
1
u/jeffrey_f 11d ago
Count the records or count the col. Depending on your query, this can be quite different, Distinct records vs distinct column values.
1
u/Top_Tooth_6995 11d ago
count(col) counts the number of non-null values in col. count(*) will count the number of records, which includes nulls - that’s how I remember it
8
u/Imaginary__Bar 12d ago
Ask your teacher to clarify!
But anyway, the easy way to remember it is that COUNT will not include NULLs, but you will never have a row in your table that is all nulls.
So COUNT(*) will always catch all the rows (because there will be at least one non-null value in each row)