Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Ordering
Limiting the output
Eliminating duplicate results
Aggregation
12. Count the rows
Grouping
HAVING: filtering and ordering groups
Let's practice

Instruction

You already know that your database can do computations because we've already added or subtracted values in our SQL instructions. But the database can do much more than that – it can also compute statistics for multiple rows. This operation is know as aggregation.

Let's start with something simple:

SELECT
  COUNT(*) AS OrdersNumber
FROM Order;

Instead of the asterisk (*), which basically means "all columns", we've put the expression COUNT(*).
COUNT() is a function. A function in T-SQL always has a name followed by parentheses. In the parentheses, you can put information that the function needs to work. For example, COUNT() calculates the number of rows specified in the parentheses.

In this case, we've used COUNT(*), which basically means "count all rows". As a result, we'll just get the total number of rows in the Order table – and not their contents.

Note that we have given an alias to the column. SQL Server doesn't give any name to aggregate columns by default. It's good practice to name such a column.

Exercise

Count all rows in the Employee table. Name the column EmployeeNumber.

Stuck? Here's a hint!

Type:

SELECT
  COUNT(*) AS EmployeeNumber
FROM Employee;