sql
  1. sql-select-count

SQL SELECT Statement: SELECT COUNT

The SELECT COUNT statement in SQL is used to return the number of rows that match a specified condition.

Syntax

The syntax for SELECT COUNT statement is as follows:

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

Where:

  • column_name: The name of the column whose values are to be counted (optional; * counts all rows).
  • table_name: The name of the table.
  • condition: The condition to be used to filter the rows (optional).

Example

Let's say we have a table named "employees" with the following data:

id name job_title salary
1 John Doe Developer 50000
2 Jane Doe Project Manager 75000
3 Bob Smith Developer 55000
4 Mary Johnson Designer 45000
5 Joe Brown Developer 60000

To count the number of rows in the employees table, we would use the following query:

SELECT COUNT(*)
FROM employees;

The output for this query would be:

COUNT(*)
5

Explanation

The SELECT COUNT(*) statement returns the total number of rows in the employees table. The * (asterisk) symbol can be used to count all rows, regardless of whether they satisfy a specific condition or not.

Use

The SELECT COUNT statement is used in scenarios where you want to get a count of rows that match a specific condition. It is commonly used in reports and analytics when you need to get a quick count of records.

Important Points

  • The SELECT COUNT statement is used only for counts; it does not return any data.
  • If you want to count the number of distinct values in a column, use the DISTINCT keyword.
  • If you want to count the number of rows that meet multiple conditions, use the AND or OR operators to combine conditions in the WHERE clause.

Summary

  • The SELECT COUNT statement is used to count the number of rows in a table that match a specific condition.
  • The syntax of the SELECT COUNT statement includes the name of the column to be counted, the table name, and an optional WHERE clause.
  • The * symbol can be used to count all rows in the table.
  • The SELECT COUNT statement is commonly used in reports and analytics for quick record counts.
Published on: