Count Rows in in SQL

There are, in MySQL Server, functions that allow us to count records, calculate sums, averages, obtain maximum and minimum values, in short, perform common arithmetic operations, both with the number of records and with their values.

These functions operate on a set of values ​​(registers), and not on individual data, and return a single value.

Let’s imagine that our “qualifications” table contains many records. To find out the amount without having to count them manually we use the COUNT() function.

SELECT COUNT(*) FROM alumni.qualifications;

The COUNT(*) function counts the number of records in a table, including those with a null value.

We can also use this function together with the WHERE clause for a more specific query, through filtering.

For example, you may want to know the number of users with a rating greater than 100:

SELECT COUNT(*) FROM alumni.qualifications WHERE qualification > 100;

To count the records that have a specific string (without taking into account those that have a null value), use the COUNT() function and in the parentheses we put the name of the field that we need to count:

SELECT COUNT(name) FROM alumni.qualifications;

Note that COUNT(*) returns the number of records in a table (including those with a “null” value) while COUNT(name) returns the number of records in which the ‘name’ field is not null.

In other words, COUNT(*) counts records, if instead of an asterisk we put the name of a field as an argument, the records whose value in that field is NOT null are counted.

Leave a Reply

Your email address will not be published.