Sling Academy
Home/MySQL/MySQL: How to count the number of rows by a condition

MySQL: How to count the number of rows by a condition

Last updated: January 25, 2024

Introduction

Understanding how to count rows in MySQL subject to certain criteria is a fundamental skill useful in many scenarios. Counting rows with a condition can help you analyze your data effectively – whether it’s for simple tasks like tallying the number of users in a system, or more complex operations like generating reports or informing business logic. In this tutorial, we will discuss various ways to count rows by a condition using the MySQL database management system.

Basic Count Syntax

To start with, the COUNT() function in MySQL is used to return the number of rows that match a specified condition. It’s one of the Aggregate Functions that MySQL supports, allowing users to perform a calculation on a set of values and return a single value.

SELECT COUNT(*) FROM table_name WHERE condition;

Using * in the COUNT() function counts all rows, regardless of NULL values. If you need to count only rows where a certain column is not NULL, you could use the column name instead of *.

SELECT COUNT(column_name) FROM table_name WHERE condition;

Counting Rows with Simple Conditions

Let’s look at an example using a fictional users table:

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(255) NOT NULL,
  active BOOLEAN DEFAULT TRUE
);

To count all active users:

SELECT COUNT(*) FROM users WHERE active = TRUE;

If we want to count only active users with usernames starting with ‘A’, we would use the LIKE operator:

SELECT COUNT(*) FROM users WHERE active = TRUE AND username LIKE 'A%';

This will count all active users whose usernames start with the letter ‘A’.

Counting Rows with Multiple Conditions

SQL allows for the use of multiple conditions using AND and OR operators. For example:

SELECT COUNT(*) FROM users WHERE (active = TRUE OR active IS NULL) AND (username LIKE 'A%' OR username LIKE 'B%');

This query would return the number of users who are either active or have a NULL ‘active’ value and whose username starts with ‘A’ or ‘B’.

Grouping Results

Counting rows often goes hand in hand with the GROUP BY clause, which is used to group rows that have the same values in specified columns into summary rows:

SELECT column_name, COUNT(*) FROM table_name WHERE condition GROUP BY column_name;

For example, if you wanted to know how many users have the same username, erroneous duplicates, you would use:

SELECT username, COUNT(*)
FROM users
GROUP BY username
HAVING COUNT(*) > 1;

This query groups users based on their username, then counts how many times each username appears and only shows those that appear more than once.

Advanced Conditions with JOINs

Complex conditions might require a JOIN operation, which combines rows from two or more tables, based on a related column between them. Here’s an example of counting rows after joining tables:

SELECT COUNT(DISTINCT u.id)
FROM users AS u
JOIN orders AS o ON u.id = o.user_id
WHERE o.status = 'completed';

This query would count the number of users who have placed an order with a ‘completed’ status, accounting for distinct users.

Utilizing Subqueries

A subquery or inner query or nested query is a query within another SQL query, which can be used to perform operations that require a temporary table:

SELECT COUNT(*) FROM (
  SELECT username FROM users WHERE active = TRUE
) AS active_users;

Here, we count active users from a derived table that contains only usernames of active users.

Conclusion

Mastering the COUNT() function along with various conditions and clauses is essential for data manipulation in MySQL. In this tutorial, we looked over how to perform this task, showing how versatile and powerful SQL queries can be when retrieving data. As you work more with databases, you’ll find countless ways to adapt these approaches to suit your data analytics and reporting needs.

Next Article: Using AND & OR operators in MySQL 8: A Practical Guide

Previous Article: MySQL: How to Select DISTINCT Rows

Series: MySQL Tutorials: From Basic to Advanced

MySQL

You May Also Like

  • MySQL: How to reset the AUTO_INCREMENT value of a table
  • MySQL: How to add a calculated column to SELECT query
  • MySQL: Eliminate orphan rows in one-to-many relationships
  • MySQL: Using R-Tree Indexes for Spatial Data Types
  • How to Create Custom Collations in MySQL
  • Using Hash Indexes in MySQL: A Practical Guide
  • Understanding Full-Text Indexes in MySQL
  • Partial Indexes in MySQL: A Practical Guide
  • MySQL: How to Remove FOREIGN KEY Constraints
  • Using ENUM in MySQL 8: A Practical Guide (with Examples)
  • MySQL: Creating a Fixed-Size Table by Using Triggers
  • One-to-Many Relationship in MySQL 8: A Practical Guide
  • Using Regular Expressions in MySQL 8: The Complete Guide
  • Using Loops in MySQL: A Practical Guide (with Examples)
  • How to Execute an SQL File in VS Code
  • Making use of the JSON_REMOVE() function in MySQL 8
  • MySQL 8: How to count rows in related tables
  • Replication in MySQL 8: A Comprehensive Guide
  • MySQL 8: FIRST_VALUE(), LAST_VALUE(), and NTH_VALUE() functions – Explained with examples