When I was practicing SQL queries, I had a question with the way of doing one. I would like to know what is the difference between:
SELECT open_date, COUNT (*) FROM accounts
with this other
SELECT COUNT (open_date) FROM accounts
When I was practicing SQL queries, I had a question with the way of doing one. I would like to know what is the difference between:
SELECT open_date, COUNT (*) FROM accounts
with this other
SELECT COUNT (open_date) FROM accounts
The difference is that:
► The first query: SELECT open_date, COUNT(*) FROM accounts
You will return a single row with two columns, the first column will have the first value you find in the field open_date
, and the second column will tell you the total number of records in the table.
As you can understand, asking for an additional column in SELECT
that way would not make much sense.
However, you can use COUNT
with an additional column (or with several), when you want to know the amount of elements that there are (s) column (s), combining it with GROUP BY
.
For example, if you want to know how many animals there are of each species:
SELECT species, COUNT(*) FROM pet GROUP BY species;
+---------+----------+
| species | COUNT(*) |
+---------+----------+
| bird | 2 |
| cat | 2 |
| dog | 3 |
| hamster | 1 |
| snake | 1 |
Using this procedure, you can get counts on several types of columns (for other examples see the code examples in the link at the end of this answer).
► The second query: SELECT COUNT(open_date) FROM accounts
It will tell you the total number of records in the table, but ignoring the values NULL
of the column open_date
if there were . That is to say that in that case it could not be doing a count of all the rows of the table.
► In summary:
COUNT(*)
: will count all the records in the table. You can also use COUNT(1)
. However, the form that is usually used is that with *
.
COUNT(columna)
: will count all the records in the table where the value of columna
is not NULL
. This use is not safe if you want to know how many records are in the table, regardless of null values.
For more details and examples you can see the MySQL documentation .