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
Returns the amount of values (excluding NULL values) in the defined column:
SELECT COUNT(col_name) FROM tbl_name
Theory is great, but we recommend digging deeper!
Returns the total amount of data records in the table:
SELECT COUNT(*) FROM tbl_name
Brings back the amount of values that are distinct (counting duplicate values as one value) from a defined column:
SELECT COUNT(DISTINCT col_name) FROM tbl_name
Below is a section of the customer_orders table – we'll use it as a demo database in our examples:
SQL COUNT Examples
In the code example below the statement calculated the amount of orders from a particular customer:
SELECT COUNT(ID) AS OrderFromCustomers FROM customer_orders WHERE customer_id = 2;
Here we calculate the full amount of orders:
SELECT COUNT(DISTINCT customer_id) AS NumberOfCustomer FROM customer_orders;
The following query will return the amount of unique customers:
SELECT COUNT(DISTINCT ID) AS NumberOfCustomer FROM Orders;