Open In App

How to Get Multiple Counts With Single Query in SQL Server

Last Updated : 16 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In SQL Server, obtaining multiple counts with a single query is a common requirement, especially when we are analyzing data across different conditions. Whether we are tallying the number of active and inactive users or counting orders based on their status by using a single query can speed our data retrieval process and improve query performance. In the article, we will learn about how to Get Multiple Counts With a Single Query in an SQL Server with the help of various techniques and methods along with their examples and so on.

How to Get Multiple Counts With Single Query?

The COUNT() function is used to return the number of rows that match a specified condition. It can be used in various scenarios to count the number of records in a table. Two methods can be used to get the Multiple Counts With a Single Query in SQL Server which are given below.

  1. Using Count( ) with CASE Statement
  2. Using Count( ) and Sum( ) with CASE Statement

let’s Setting Up an Environment to Get Multiple Counts

But before that, let us consider creating a sample Database with some random records. We will create an as-usual Orders table with 5 random records:

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,a
    ProductName VARCHAR(50),
    Quantity INT,
    OrderDate DATE
);

-- 5 rows inserted with 2 products orderDate as same (i.e. Product B and Product C) and 2 rows with same quantity
INSERT INTO Orders (OrderID, ProductName, Quantity, OrderDate) VALUES (1, 'Product A', 10, '2024-02-14');
INSERT INTO Orders (OrderID, ProductName, Quantity, OrderDate) VALUES (2, 'Product B', 5, '2024-02-15');
INSERT INTO Orders (OrderID, ProductName, Quantity, OrderDate) VALUES (3, 'Product C', 8, '2024-02-15');
INSERT INTO Orders (OrderID, ProductName, Quantity, OrderDate) VALUES (4, 'Product D', 12, '2024-02-17');
INSERT INTO Orders (OrderID, ProductName, Quantity, OrderDate) VALUES (5, 'Product E', 7, '2024-02-18');

Output:

orders

Output

Explanation: In the above Query, Our Orders table has been created.

1. Using Count() with Case Statement

Here, we will make use of Count() function and add a case condition as arguments, so that it will count for specific conditions and return us counts for different items in the table.

Syntax:

SELECT count(*) as <alias_one>,
COUNT(case when <condition_1> then 1 else null end) as <alias_2>,
COUNT(case when <condition_2> then 1 else null end) as <alias_3>,
. . .
FROM <Table>;

Example

Let’s counting the total number of orders and the number of orders placed on a specific date (2024-02-15) and the number of orders with a quantity of 12 from an “Orders” table in SQL Server.

Query:

SELECT count(*) as total_count,
COUNT(case when OrderDate='2024-02-15' then 1 else null end) as [OrderDate_2024-02-15_Count],
COUNT(case when Quantity=12 then 1 else null end) as Quantity_12_Count
FROM Orders;

Output:

Count()withCase

Output

Explanation: Here it returns 5 for first count, 2 for 2nd that is for the OrderDate 2024-02-15 and 2 for the records with same quantity 12.

2. Using Count() and Sum() with Case Statement

Here the syntax remains same as above method with replacement of count to sum from second variable

Syntax:

SELECT count(*) as <alias_one>,
SUM(case when <condition_1> then 1 else 0 end) as <alias_2>,
SUM(case when <condition_2> then 1 else 0 end) as <alias_3>,
. . .
FROM <Table>;

Example

Let’s calculates the total number of orders, the number of orders placed on a specific date (2024-02-15) and the number of orders with a quantity of 12 from an “Orders” table in SQL Server.

Query:

SELECTcount(*) as total_count,
SUM(case when OrderDate='2024-02-15' then 1 else 0 end) as [OrderDate_2024-02-15_Count],
SUM(case when Quantity=12 then 1 else 0 end) as Quantity_12_Count
FROM Orders;

Output:

Count()withSum()withCase

Output

Explanation: This sums the count for OrderDate and Quantity with given condition and takes as 1 if it satisfies else 0. With this we can implement to get multiple counts in single row without having to create multiple SELECT statements, but need to use CASE conditional statements to add extra conditions you build the count for. You can also create counts per group if you use GROUP BY clause along with the above syntax.

Conclusion

Overall, the SQL Server offers efficient ways to retrieve multiple counts with a single query, which can significantly improve performance and simplify code. By using the COUNT() and SUM() functions with CASE statements, developers can easily specify different conditions to count records based on various criteria. This eliminates the need for multiple queries or complex logic, making the process more streamlined and manageable.


Similar Reads

How to Get Multiple Counts With Single Query in PL/SQL?
In PL/SQL, it's very common that we need to count rows based on the different conditions in the single query. This can be done using conditional aggregation or we also do this with the multiple subqueries within the SELECT statement. Here, the SELECT statement is necessary to perform this operation. In this article, we will explore both approaches
4 min read
How to Get Multiple Counts With Single Query in MySQL
MySQL is an open-source Relational Database Management System that stores data in a structured format using rows and columns. MYSQL language is easy to use as compared to other programming languages like C, C++, Java, etc. By learning some basic commands we can work, create, and interact with the Database. MySQL is open-source and user-friendly. It
5 min read
How to Get Multiple Counts With Single Query in SQLite?
In data analysis, obtaining multiple counts for different categories is a common requirement. SQLite, a lightweight and versatile database management system, offers a powerful feature that allows us to achieve this efficiently. In this article, we'll explore how to use SQLite to retrieve multiple counts with a single query, simplifying data analysi
3 min read
How to Get Multiple Counts With Single Query in PostgreSQL?
Efficient data analysis often requires counting occurrences of different categories within a dataset. PostgreSQL, a powerful relational database management system offers a feature that allows us to achieve this efficiently. In this article, we'll explore how to Get Multiple Counts With a Single Query using various methods along with examples and so
3 min read
How to Get Multiple Counts With One SQL Query?
In database management efficiency is key. SQL operations from data retrieval to manipulation, need to be optimized to ensure smooth processing. One common requirement is the need to obtain multiple counts from the table based on different conditions. While it's logical to execute separate queries, SQL provides a more elegant solution of obtaining m
5 min read
How to Get Counts of all Tables in a Schema in PL/SQL?
In Database Management System, it is essential to retrieve the statistical information about tables with the schema. Whether it is for monitoring the database health, optimizing the performance, or simply understanding the data structures having access to row counts of the tables can be more valuable. How to Get Counts of all Tables in a Schema in
5 min read
How to Escape a Single Quote in SQL Server?
SQL stands for structured query language and is used to query databases for analytical needs. While using arithmetic queries, some results require strings to help them understand better. Strings can be formed by enclosing text in quotes. However in a case when quotes are themselves required in a string, then we need to escape them. In this article,
4 min read
SQL Server Query Plan Cache
In the SQL server, the query plan cache plays an important role in ensuring efficient and optimized query execution. In this article, we are going to dive deep into the basics of query plan cache and its workflow. We will also learn how to view the query plan cache in our SQL Server databases. What is a Query Plan Cache?The query plan cache, as its
4 min read
How to Enable SQL Server Query Logging?
In the domain of database management, the SQL query is found to be very helpful in improving performance, safety, and diagnosing problems. The query logging SQL Server provides help in that administrators of database servers can view and analyze the queries executed against their servers. Query logging will give us information such as users' habits
4 min read
SQL Server INSERT Multiple Rows
SQL Server is a relational Database Management System(RDBMS). It offers various features for creating, and managing databases with its efficient tools. It can handle both small-scale and large-scale industry database applications. INSERT Statement in SQL ServerThe Insert statement is a command of the Data Manipulation Language (DML) of DBMS. After
4 min read