The Wayback Machine - https://web.archive.org/web/20241127025716/https://www.geeksforgeeks.org/count-function-in-sql-server/
Open In App

COUNT() Function in SQL Server

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The COUNT() function in SQL Server is a fundamental aggregate function used to determine the number of rows that match a specific condition. Counting rows provides valuable insights into data sets such as the total number of records, distinct values, or records meeting certain criteria.

In this article, We will learn the COUNT() Function in SQL Server by understanding various examples in detail.

What is the SQL Server COUNT() function

  • The COUNT() function in SQL Server is an aggregate function used to return the number of rows that match a specified condition.
  • It counts the number of items in a set, which can be all rows or rows that meet a certain criterion, depending on the query.

Syntax of the COUNT() function:

COUNT(expression)

expression: The column or expression for which the count is calculated. It can be a column name, a constant, or an asterisk (*).

Features OF COUNT() Function in SQL Server

  1. This function finds the number of indexes as returned from the query selected.
  2. This function comes under Numeric Functions.
  3. This function accepts only one parameter namely expression.
  4. This function ignores NULL values and doesn’t count them.

Examples of COUNT() Function in SQL Server

Consider the following example table named Employees:

EmployeeID Name Department Status
1 Alice HR Active
2 Bob IT Inactive
3 Charlie HR Active
4 David IT Active
5 Eve Finance Active

Let’s explore various ways to use the COUNT() function with this table.

Example 1: Count All Rows in the Employees Table

SELECT COUNT(*) AS TotalRows
FROM Employees;

Output:

TotalRows
5

Explanation: This query returns the total number of rows in the Employees table, which is 5.

Example 2: Count Distinct Values in the Department Column

SELECT COUNT(DISTINCT Department) AS UniqueDepartments
FROM Employees;

Output:

UniqueDepartments
3

Explanation: This query counts the number of unique departments in the Employees table, which are HR, IT, and Finance.

Example 3: Count Rows where the Status is ‘Active’

SELECT COUNT(*) AS ActiveEmployees
FROM Employees
WHERE Status = 'Active';

Output:

ActiveEmployees
4

Explanation: This query returns the number of employees with the status ‘Active’, which is 4.

Example 4: Count Employees in Each Department

SELECT Department, COUNT(*) AS NumberOfEmployees
FROM Employees
GROUP BY Department;

Output:

Department NumberOfEmployees
HR 2
IT 2
Finance 1

Explanation: This query counts the number of employees in each department, providing a breakdown by department.

Example 5: Using COUNT() with SUM() and AVG()

Assuming the Employees table has a Salary column:

SELECT Department, COUNT(*) AS TotalEmployees, SUM(Salary) AS TotalSalary, AVG(Salary) AS AverageSalary
FROM Employees
GROUP BY Department;

Output:

Department TotalEmployees TotalSalary AverageSalary
HR 2 120000 60000
IT 2 150000 75000
Finance 1 80000 80000

Explanation: This query counts the number of employees, calculates the total salary, and finds the average salary for each department.

Conclusion

The COUNT() function is a powerful tool for summarizing data by counting rows based on given conditions or criteria. Whether you’re calculating the total number of records, counting unique values, or aggregating data across groups, COUNT() provides crucial metrics that aid in data analysis.

FAQs

What is the function COUNT in SQL Server?

The COUNT() function in SQL Server is an aggregate function that returns the total number of rows in a result set, based on a specified condition. It can count all rows or non-null values in a specified column.

What is the difference between COUNT() and COUNT(*)?

COUNT(column) counts the number of non-null values in the specified column, whereas COUNT(*) counts all rows in the result set, including rows with null values.

Does COUNT() count duplicates?

Yes, COUNT() includes duplicate values unless you use COUNT(DISTINCT column) to count only unique values.



Similar Reads

Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
Count(*) vs Count(1) in SQL Server
In SQL Server, the COUNT() function is used to return the number of rows in a query result. There are different ways to use the COUNT() function such as COUNT(*) and COUNT(1). Although they produce the same result, there are subtle differences in how they work internally. In this article, we will try to understand the difference between Count(*) vs
4 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
Dynamic SQL in SQL Server
In SQL Server, at times the SQL Queries need to be dynamic and not static, meaning the complete SQL query may be built dynamically at run time as a string using the user inputs and any specific application logic. This can be done in queries run from back-end applications or inside stored procedures. In this article let us look into the details abou
6 min read
Dynamic SQL and Temporary Tables in SQL Server
In SQL Server, creating and using Temp Tables using dynamic SQL is a good feature when we need to temporarily create tables at run time and delete automatically all within a session. They can be very useful when we need to store temporary data in a structured format and do data manipulation using Data Manipulation Language in SQL. In this article l
6 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL Server | Convert Tables in T-SQL into XML
XML (Extensible Markup Language) is a widely-used markup language designed to store and transfer structured data between different systems and platforms. While HTML focuses on the visual representation of data OverviewXML is similar to HTML which is designed to structure and store data for sharing across different systems and platforms.Unlike HTML,
3 min read
SQL Query to Convert DateTime to Date in SQL Server
In SQL Server, working with DateTime data types can be a bit complex for beginners. This is because DateTime includes both the date and time components, while many scenarios only require the date. Whether you're working with large datasets, performing data analysis, or generating reports, it's common to need the date portion only. In this article,
4 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Different Ways to Know Count of TempDB Data Files in SQL Server
The TempDB database is one of the most significant SQL Server system databases, and it's used to store temporary user objects like user-defined temporary tables, temporary stored procedures, table variables, and indexes, as well as transient stored procedures, table variables, and indexes. To allow transactions to be rolled back, operations in temp
3 min read
How to Count Based on Condition in SQL Server?
In SQL Server, the COUNT() function is also utilized for tallying the number of records within a table. This article intends to explore the query, focusing on incorporating conditions into the COUNT() function in SQL Server. The COUNT() function in SQL Server is commonly utilized to count all records within a dataset. Nonetheless, there are scenari
4 min read
QUOTENAME() Function in SQL Server
QUOTENAME() function : This function in SQL Server is used to return a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier. Features : This function is used to find a Unicode string with delimiters added. This function accepts only strings and delimiters. This function add delimiters by default i
3 min read
SESSIONPROPERTY() Function in SQL Server
SESSIONPROPERTY() function : This function in SQL Server is used to return the settings of the session that is specified in the argument section. Features : This function is used to find the settings of the session state.This function comes under Advanced Functions.This function accepts only one parameter namely option. Syntax : SESSIONPROPERTY(opt
2 min read
TRANSLATE() Function in SQL Server
TRANSLATE() function : This function in SQL Server is used to return the translated string of the string stated in the first argument of this function, when the characters stated in the characters argument of the above function are converted into the characters stated in the last argument i.e, translations. Features : This function is used to find
2 min read
SIN() and COS() Function in SQL Server
1. SIN() Function : The SIN() function returns the sine of a number. Syntax : SIN(number) Parameter : Required. A numeric value. number : It is a numeric value. Returns : It returns the float_expression of the sine of a number. Example-1 : When the argument holds a positive number. SELECT SIN(5); Output : -0.95892427466313845 Example-2 : When the a
1 min read
DATEADD() Function in SQL Server
DATEADD() function : This function in SQL Server is used to sum up a time or a date interval to a specified date, then returns the modified date. Features : This function is used to sum up a time or a date interval to a date specified. This function comes under Date Functions. This function accepts three parameters namely interval, number and date.
3 min read
SQL Server LEAD() function Overview
At many instances, user would really like to check the worth of the present row with the worth of the subsequent row. to resolve this problem in SQL Server’s LEAD() window function are often used. LEAD() : Function provides access to a row at a set physical offset following this row. LEAD() function will allows to access data of the following row,
2 min read
ASCII() Function in SQL Server
The ASCII() function returns the ASCII value of the leftmost character of a character expression. Syntax : ASCII(character_expression) Parameter : This method accepts a single-parameter as mentioned above and described below : character_expression : It can be a literal character, an expression of a string, or a column. If more than one character is
2 min read
STR() Function in SQL Server
The STR() function converts a numeric value to a character value. Syntax : STR(float_expression [, length [, decimal]]) Parameter : This method accepts three parameters as mentioned above and described below : float_expression : It is a numeric expression that evaluates to an approximate number with a decimal point. length : It is the total length
1 min read
UNICODE() Function in SQL Server
In this article, we are going to cover UNICODE() function where you will see the Unicode for given specific character or for expression character. UNICODE() : It is the function that gets the integer value for the first character of the input expression, as defined by the Unicode standard. Syntax : UNICODE(ncharacter_expression) Parameter : UNICODE
1 min read
RTRIM() Function in SQL Server
The RTRIM() function removes trailing spaces from a string. Syntax : RTRIM(input_string) Parameter : RTRIM() function accepts single-parameter like input_string. input_string : It is an expression of character or binary data. It can be a literal string, variable, or column. Returns - It returns a string after truncating all trailing blanks. Example
1 min read
FLOOR() and CEILING() Function in SQL Server
1. FLOOR() Function : The FLOOR() function returns the largest integer value which is less than or equal to a number. Syntax : FLOOR(number) Parameter : Required. A numeric value. number : It is a numeric value. Returns : It returns the integer value. Example-1 : When the argument holds a positive number. SELECT FLOOR(21.53); Output : 21 Example-2
1 min read
TAN() and COT() Function in SQL Server
1. TAN() Function : The TAN() function returns the tangent of a number. Syntax : TAN(number) Parameter : Required. A numeric value. number : It is a numeric value. Returns : It returns the float_expression of the tangent of a number. Example-1 : When the arguments holds a positive number. SELECT TAN(3.25); Output : 0.10883402551332971 Example-2 : W
2 min read
DEGREES() and RADIANS() Function in SQL Server
1. DEGREES() Function : The DEGREES() function converts a value in radians to degrees. Syntax : DEGREES(number) Parameter : Required. A numeric value. number : It is a numeric value. Returns : It returns a value whose data type matches the data type of numeric_expression. Example-1 : Converts a radian value into degrees. SELECT DEGREES(1); Output :
1 min read
ATN2() Function in SQL Server
In this article, we are going to cover the ATN2()function in which we will see how we can get the arc tangent of two given numbers. Let's discuss one by one. // here val1 and val2 are input. Input : ATN2(val1, val2) Output : Arc tangent result. ATN2() : It is the function that returns the arc tangent of two numbers. Syntax : ATN2(val1, val2) Parame
1 min read
LOG10() Function in SQL Server
This function returns the logarithm of a number to base 10. Syntax : LOG10(number) Parameter : This method accepts a single-parameter as mentioned above and described below. number - This parameter hold a number which is greater than 0. Returns - It returns the base-10 logarithm of the specified number. Let's consider the following examples. Exampl
1 min read
Article Tags :
three90RightbarBannerImg