SQL COUNT Function using SELECT command

SQL

In SQL, the COUNT function is a powerful aggregate function used to count the number of rows in a result set or the number of occurrences of a specific value in a column.

Basic Syntax of SQL SELECT COUNT

SELECT COUNT(*) FROM TABLE;

Now let’s understand with different examples:

Database Structure:

Table: users

user_idusernameage
1John25
2Jane22
3Bob30
4Alice28

Table: orders

order_iduser_idproduct_id
10111
10222
10313
10431
10542

Example 1: Counting all records in a table

SELECT COUNT(*) FROM users;
COUNT(*)
4

Example 2: Counting users older than 18.

SELECT COUNT(*) FROM users WHERE age > 18;
COUNT(*)
3

Example 3: Counting orders for each product.

SELECT product_id, COUNT(*) FROM orders GROUP BY product_id;
product_idCOUNT(*)
12
22
31

Example 4: Counting users with a specified attribute, handling NULLs.

SELECT COUNT(age) FROM users;
COUNT
4

Example 5: Misusing the COUNT function in a subquery.

SELECT username, (SELECT COUNT(*) FROM users) as total_count FROM users;
usernametotal_count
John4
Jane4
Bob4
Alice4

Example 6: Counting NULL Values

-- Counting NULL values in the "age" column of the "users" table
SELECT COUNT(*) FROM users WHERE age IS NULL;

Output:

Count
0