Can you count?
Let’s have a little sequel quiz today, inspired by what I have seen in a real interview.
It will be about COUNT(),our favorite hard-worker among aggregate functions.
Close your IDE or CLI you are using, and try answering yourself first before checking the right answer.
Quiz
Imagine we have a table like this:
-
What will you get if you run
SELECT COUNT(*)
from this table? -
What will you get if you run
SELECT COUNT(num)
from this table? -
What will you get if you run
SELECT COUNT('num')
from this table? -
What will you get if you run
SELECT COUNT(null)
from this table? -
What will you get if you run
SELECT COUNT(#)
from this table?
Click to see the answer #1:
Click to see the answer #2:
Click to see the answer #3:
Click to see the answer #4:
Click to see the answer #5:
Explanation
Well, first one was pretty obvious, wasn’t it? COUNT(*)
will give you the count of all rows in the table, in this case: 6.
Pro tip: COUNT(1)
,COUNT(0)
,COUNT(-1)
will also give you all rows count: 6.
COUNT(num)
counts all non-NULL values in the columns, hence: 4
COUNT('num')
will also be 6 because 'num'
is a string constant, so same output is produced as in COUNT(1)
.
COUNT(NULL)
will return 0, as NULLs are ignored. \
COUNT(#)
is a syntax error.
Try it yourself
This code snippet can help you reproduce the quiz and play with it yourself:
This is what you get in DuckDB (see my previous post for installation):