How to Get Multiple Counts With One SQL Query?
Last Updated :
12 Dec, 2024
Efficiency is important in database management, and performing operations like data retrieval should be optimized. Obtaining multiple counts in a single query is a useful technique to enhance performance and streamline queries. Instead of executing separate queries for different conditions, we can use SQL aggregate functions like COUNT() with conditional logic to achieve this efficiently.
This article explains how to use a single SQL query to calculate multiple counts, saving time and resources while improving readability and performance.
COUNT ()
The COUNT() function returns the total number of rows that match our given conditions. It is one of the aggerate functions in SQL which provides a powerful mechanism for performing conditional logic and allows you to perform calculations on groups of rows, making them essential for obtaining counts. Below given syntax is used to count rows that satisfy specified conditions, making it essential for obtaining multiple counts in one query.
Syntax
1. Counting all rows
SELECT COUNT(*)
FROM table_name;
2. Counting rows with specific conditions
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
3. Conditional counting using CASE
SELECT COUNT(CASE WHEN condition THEN column_name END)
FROM table_name;
Example 1: Counting Books in a Library Database
In this example, we analyze a library database containing a Books table with columns such as book_id, title, author_id, genre_id, and publication_year. The queries demonstrate how to count books based on specific conditions, such as publication year or author, using the COUNT() function with conditional logic
1. Creating the Books Table
We create a table Books to store information about books in a library, including book ID, title, author ID, genre ID, and publication year.
CREATE TABLE Books ( book_id INT PRIMARY KEY,
title VARCHAR(255),
author_id INT,
genre_id INT,
publication_year INT);
2. Inserting Data
Insert sample data into the Books table to demonstrate counting scenarios. This data includes details such as book IDs, titles, author IDs, genres, and publication years, providing a foundation for performing various count-based queries.
INSERT INTO Books VALUES
(1, 'To Kill a Mockingbird', 101, 201, 1960),
(2, '1984', 102, 202, 1949),
(3, 'Pride and Prejudice', 102, 203, 1813),
(4, 'The Great Gatsby', 104, 204, 1925),
(5, 'The Catcher in the Rye', 105, 205, 1951);
3. Displaying Data
To view the data in the table, use the query. Which retrieves all the rows and columns from the table, displaying the inserted data for verification and analysis.
SELECT * FROM Books;
Output
Books Table4. Total Books Published in the 1900s
To determine the total number of books published during the 1900s, use the following query. Which utilizes the COUNT(*)
function to count all rows where the publication year starts with '19', indicating the 1900s. The result is labeled as total_books
.
Query:
SELECT COUNT( * ) AS total_books
FROM Books
WHERE publication_year LIKE '19%';
Output
total_books outputExplanation:
In this query, the COUNT() function is returns the number of books published in the 1900s. This is achieved by employing the LIKE operator to scan which books were published in years containing the digits `19`.
5. Total Books by Author ID = 102
To find the total number of books with the author ID of 102, use the following query. Which counts all rows where the author_id
is equal to 102 and labels the result as total_author_id
.
Query:
SELECT COUNT( * ) AS total_author_id
FROM Books
WHERE author_id = 102;
Output
total_author_id output6. Multiple Counts in a Single Query
How to get total number of books with author id as 102 and genre id as 202 which where published in year 1900's together in one query.
SELECT COUNT( CASE WHEN publication_year LIKE '19%' THEN 1 END ) AS total_books,
COUNT( CASE WHEN author_id = 102 THEN 1 END ) AS total_author_id,
COUNT( CASE WHEN genre_id = 202 THEN 1 END ) AS total_genre_id
FROM Books;
Output

Explanation:
COUNT(CASE WHEN publication_year LIKE '19%' THEN 1 END)
counts books published in the 1900s.
COUNT(CASE WHEN author_id = 102 THEN 1 END)
counts books by author ID 102.
COUNT(CASE WHEN genre_id = 202 THEN 1 END)
counts books with genre ID 202.
- This single query efficiently retrieves multiple counts based on different conditions, improving performance by reducing the need for multiple separate queries.
Example 2: Counting Citizens Without Voting Cards in a Single SQL Query
In this example, we work with a table named Citizens, which contains data about a group of people who are citizens of a country. The table includes information about individuals of various ages, their eligibility for voting, and whether they possess a voting card if eligible.
1. Creating the Citizens Table
The table consists of the following columns: id, which serves as a unique identifier for each citizen; name, representing the name of the citizen; age, indicating the citizen's age to determine voting eligibility; and has_voting_card, a boolean column (0 or 1) that specifies whether the citizen has a voting card.
citizens table2. Eligible Citizens Without Voting Cards
Using the Citizens table, we aim to calculate the total number of eligible citizens (aged 18 or above) who do not possess voting cards. This calculation is done using a single SQL query with a conditional CASE statement.
Query:
SELECT COUNT(CASE WHEN age >= 18 AND has_voting_card = 0 THEN 1 ELSE NULL END) AS eligible_citizens_without_card
FROM Citizens;
Output
eligible_citizens_without_card outputExplanation:
This query gives us total number of citizens who are eligible for voting aged 18 or above and also don't have voting cards, this is also an example of multiple count in single query we use CASE statement which conditionally count based on the specified condition we have provided.
Conclusion
The ability to calculate multiple counts in one SQL query improves efficiency in database management. Using aggregate functions like COUNT() with conditional logic, we can retrieve data in a more organized and optimized manner. This approach enhances performance, reduces redundancy, and simplifies query structure. Mastering such techniques is a valuable skill for database professionals aiming to handle complex data retrieval tasks effectively.
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.
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 Da
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 co
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 Quer
3 min read
How to Get Multiple Counts With Single Query in SQL Server
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
4 min read
How to SELECT DISTINCT on Multiple Columns in PL/SQL?
PL/SQL language extends SQL by allowing procedural code within Oracle databases. It combines the power of SQL with procedural constructs like loops, conditions, and exception handling. It is a blocked programming language unit that can be named or unnamed blocks. The database does not store unnamed
3 min read
SQL Query to Exclude Multiple Values
To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE stateme
2 min read
Maximizing Query Performance with COUNT(1) in SQL
In SQL, maximizing query performance is paramount for efficient database operations. The COUNT() function, particularly COUNT(1), proves pivotal in this endeavor. COUNT(1) minimizes I/O overhead and memory usage, optimizing query execution speed, especially with large datasets. Understanding its ben
5 min read
Count() vs len() on a Django QuerySet
In Django, when working with database query sets, developers often need to determine the number of records that meet certain criteria. Django offers two primary ways to accomplish this: using the count() method on a QuerySet, or the Python built-in len() function. Each method has its specific use ca
3 min read
How to Use Count With Condition in PostgreSQL?
In PostgreSQL, the COUNT() function serves as a tool for tallying the number of records within a table. This article aims to address this query, delving into the nuances and implications of integrating conditions into the COUNT() function in PostgreSQL. The COUNT() function in PostgreSQL is traditio
4 min read