Open In App

How to Get Multiple Counts With One SQL Query?

Last Updated : 12 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
Books Table

4. 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-output
total_books output

Explanation:

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-output
total_author_id output

6. 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
total_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-table
citizens table

2. 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-output
eligible_citizens_without_card output

Explanation:

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.


Next Article

Similar Reads