Contents
SQL COUNT: Main Tips
- This function returns the amount of rows that satisfy the defined criteria.
- COUNT(DISTINCT) is only supported by Microsoft SQL Server and ORACLE.
Syntax of SQL COUNT
COUNT(col_name)
Returns the amount of values (excluding NULL values) in the defined column:
Example
SELECT COUNT(col_name) FROM tbl_name
Pros Main Features
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
Pros Main Features
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
Pros Main Features
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
COUNT(*)
Returns the total amount of data records in the table:
Example
SELECT COUNT(*) FROM tbl_name
COUNT(DISTINCT col_name)
Brings back the amount of values that are distinct (counting duplicate values as one value) from a defined column:
Example
SELECT COUNT(DISTINCT col_name) FROM tbl_name
Demo Database
Below is a section of the customer_orders table – we'll use it as a demo database in our examples:
id | customer_id | employee_id |
---|---|---|
20408 | 2 | 7 |
85471 | 37 | 3 |
75864 | 77 | 8 |
SQL COUNT Examples
COUNT(col_name)
In the code example below the statement calculated the amount of orders from a particular customer:
Example
SELECT COUNT(ID) AS OrderFromCustomers FROM customer_orders WHERE customer_id = 2;
COUNT(*)
Here we calculate the full amount of orders:
Example
SELECT COUNT(DISTINCT customer_id) AS NumberOfCustomer FROM customer_orders;
COUNT(DISTINCT col_name)
The following query will return the amount of unique customers: