SQL Basics | Functions | COUNT
COUNT can retrieve how many rows of data are returned from a table.
COUNT syntax
SELECT COUNT("field_name")
FROM "table_name";
COUNT example
For example, suppose you want to find how many non-empty values exist in the store_name field of the table below.
store_information table
| store_name | sales | txn_date |
|---|---|---|
| Los Angeles | 1500 | Jan-05-2018 |
| San Diego | 250 | Jan-07-2018 |
| Los Angeles | 300 | Jan-08-2018 |
| Boston | 700 | Jan-08-2018 |
Enter the following command.
SELECT COUNT(store_name)
FROM store_information
WHERE store_name IS NOT NULL;
The result is as follows.
| COUNT(store_name) |
|---|
| 4 |
IS NOT NULL indicates that this field is not NULL, meaning it is not empty.
COUNT and DISTINCT are used together when you want to remove duplicate data from a table and count how many distinct values remain. For example, to count how many store_name values exist in the table, enter the following.
SELECT COUNT(DISTINCT store_name)
FROM store_information;
The result is as follows.
| COUNT(DISTINCT store_name) |
|---|
| 3 |