MySQL Count Function
MySQL Count() function is an in-built aggregate function returns the number of rows that match a specified condition.It also calculate the count of non-NULL values in a particular column.
- COUNT (*) - This function is used to return the count no of rows in a result set contains all Non-Null values.
- COUNT (EXPRESSION ) - This function is used to returns the result set without contaning Null rows as result of expresssion
- COUNT (DISTINCT) - This function returns the count of distinct rows without contaning Null rows as result of expresssion
Demo Database:
- Table Name : products
product_id | product_name | product_code | price | unit | category_id |
---|---|---|---|---|---|
1 | The Psychology | 7550 | 250.00 | Piece | 1 |
2 | Stories for Children | 3098 | 350.00 | Piece | 1 |
3 | Harry Potter | 8472 | 275.00 | Piece | 1 |
4 | Tecno Spark | 9468 | 8000.00 | Nos | 2 |
5 | Samsung Galaxy | 7188 | 10000.00 | Nos | 2 |
6 | Panasonic Eluga | 3433 | 7000.00 | Nos | 2 |
7 | Lenovo IdeaPad | 6708 | 45000.00 | Nos | 3 |
8 | ASUS Celeron Dual Core | 3583 | 43000.00 | Nos | 3 |
COUNT (*)
Find the total number of products in the table.
SELECT COUNT(*) FROM products;Try it Yourself
COUNT() with WHERE Clause
Find the number of product where price is lesser than 5000.
SELECT COUNT(product_name) FROM products where price>=5000;Try it Yourself
COUNT (DISTINCT)
COUNT(distinct expression) only counts non-null unique values in the specified column.
SELECT COUNT(DISTINCT unit) FROM products;Try it Yourself