We find the number of records in a data set with the Count function. For example, we can find the number of records in a table or the number of records in a data set grouped with GROUP BY.
Let’s make examples for a better understanding of COUNT Function.
Example:
First, we create a table with the help of the following script and add a few records into this table.
1 2 3 4 5 6 7 8 9 10 11 12 | CREATE TABLE [dbo].[MyTable] ([ID] INT IDENTITY, [Name] VARCHAR(20), [Product] VARCHAR(20) ) INSERT [dbo].[MyTable] VALUES ('Hakan GURBASLAR','Product1'), ('Nurullah CAKIR','Product2'), ('Faruk ERDEM','Product3'), ('Nurullah CAKIR','Product4'), ('Nurullah CAKIR','Product5'), ('Hakan GURBASLAR','Product6') |
Let’s calculate the number of records in the table with one of the following queries: (Both queries return the same result. If you type a column name instead of 1 or *, null records are not calculated.)
1 | SELECT Count(1) FROM [dbo].[MyTable] |
or
1 | SELECT Count(*) FROM [dbo].[MyTable] |
Calculate how many products each person has by grouping table by [Name] column:
1 2 3 | Select [Name],COUNT(Product) AS Product_Count FROM [dbo].[MyTable] GROUP BY [Name] ORDER BY COUNT(Product) DESC |