EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

SQL COUNT

Home » Data Science » Data Science Tutorials » SQL Tutorial » SQL COUNT

SQL COUNT

Introduction to SQL COUNT

COUNT() function in standard query language (SQL) is an aggregate function that returns the total number of records returned by a SELECT query based on the specified conditions. COUNT(*) function counts all the records. COUNT() function counts only non-NULL records. COUNT(), when used with the DISTINCT keyword, returns the count of only unique records in the result set of the SELECT statement. The function returns 0 if there is no matching record.

Syntax and Parameters of SQL COUNT

The basic syntax used for using the COUNT function in SQL is as follows:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

SELECT COUNT(expression)
FROM table_name;

The syntax for writing COUNT function with a DISTINCT keyword.

SELECT COUNT(DISTINCT column_name)
FROM table_name;

The syntax for writing COUNT function in GROUPBY clause.

SELECT count(column_name1), column_name2
FROM table_name
GROUP BY column_name2;

The parameters used in the above-mentioned syntax are as follows:

  • expression: The expression can be ‘*’, column_name or 1. ‘*’ and 1 in COUNT function counts all the rows in the given table, whereas column_name counts only non-null values.
  • column_name: The column_name is the field names whose values will be counted.
  • table_name: The database table from which these columns are being fetched.
  • column_name1: The column on which counting will be performed.
  • column_name2: The column on which grouping will be performed and then counting will be done group-wise for column_name1.

Here we have used the minimum possible clauses. You may add WHERE, HAVING, ORDER BY etc., to these syntaxes based on your requirement.

Examples of SQL COUNT

In order to illustrate the working of the COUNT() function in SQL, what could be better than trying a few examples on a dummy table.

Ergo, let us create a dummy table called “registrations”. Here is the create a statement for creating the table.

Code:

CREATE TABLE registrations (
regis_id INT NOT NULL,
username VARCHAR(255),
city VARCHAR(255),
date_of_birth DATE,
date_of_regis DATE
);

Having successfully created the registrations table.

Let’s insert a few records in it to work with.

Popular Course in this category
Sale
JDBC Training (6 Courses, 7+ Projects)6 Online Courses | 7 Hands-on Projects | 37+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (9,284 ratings)
Course Price

View Course

Related Courses
PHP Training (5 Courses, 3 Project)Windows 10 Training (4 Courses, 4+ Projects)SQL Training Program (7 Courses, 8+ Projects)PL SQL Training (4 Courses, 2+ Projects)Oracle Training (14 Courses, 8+ Projects)

Code:

INSERT INTO registrations(
regis_id, username, city, date_of_birth, date_of_regis)
VALUES (1,'Mohit Kumar','New Delhi','2000-01-01','2020-06-05'),
(2,'Reshma Khan','New Delhi','1998-11-21','2020-06-15'),
(3,'Biju Mathews','Bangalore','2000-01-15','2020-05-25'),
(4,'Samantha','Bangalore','1999-12-06','2020-05-01'),
(5, NULL,'Bangalore','2000-03-04','2020-05-15'),
(6,'Varun Reddy','Hyderabad','1999-01-01','2020-06-25'),
(7,'Mohini Gupta','New Delhi','2000-01-11','2020-06-05'),
(8,'Mohit Sharma','New Delhi',NULL,NULL);

The query returned successfully. The data in the registrations table looks something as follows:

Code:

SELECT * FROM registrations;

Output:

SQL COUNT 1

Now we are all set to do a few examples based on the COUNT() function.

COUNT (*) and COUNT(1) functions.

Example #1

Find the total number of rows/records in the registrations table.

Code:

SELECT COUNT(*)
FROM registrations;

Output:

SQL COUNT 2

Code:

SELECT COUNT(1)
FROM registrations;

Output:

SQL COUNT 3

Both the queries return the same output and serve the same purpose, then what is the difference between them? The difference is count(1) performs better than count(*). It returns queries quicker than the latter.

COUNT(column_name) and COUNT(DISTINCT column_name).

Example #2

Find the total number of usernames in the registrations table.

Code:

SELECT COUNT(username)
FROM registrations;

Output:

SQL COUNT 4

You must be wondering; the select query might have returned 8 records, then why does COUNT() function return 7? This is because the count() function does not count NULL values, and one of the usernames is a NULL value.

Example #3

Find the total number of regis_ids in the registrations table.

Code:

SELECT COUNT(regis_id)
FROM registrations;

Output:

total number of regis_ids

Here, we did not have any NULL value, and hence the function returned 8.

Example #4

Find the total number of cities in the registrations table.

Code:

SELECT COUNT(city) as "No. of cities"
FROM registrations;

Output:

SQL COUNT 6

Example #5

Find the total number of unique cities in the registrations table.

Code:

SELECT COUNT( DISTINCT city) as "No. distinct of cities"
FROM registrations;

Output:

total number of unique cities

COUNT() with GROUP BY clause.

Example #6

Find the total number of registrations grouped together on a monthly basis.

Code:

SELECT date_part('Month',date_of_regis) as "Month",
count(regis_id) as "Total no. of registrations"
FROM registrations
GROUP BY date_part('Month',date_of_regis)
ORDER BY 1;

Output:

SQL COUNT 8

Example #7

Find the total number of registrations made from different cities.

Code:

SELECT city,
count(regis_id) as "Total no. of registrations"
FROM registrations
GROUP BY city
ORDER BY city;

Output:

made from different cities.

COUNT() with HAVING clause.

Example #8

Find the total number of registrations grouped together by year of birth of the users having more than 2 registrations.

Code:

SELECT DATE_PART('Year', Date_of_birth) as "Birth Year",
count(regis_id) as "No. of registration"
FROM registrations
GROUP BY DATE_PART('Year', Date_of_birth)
HAVING COUNT(regis_id) >= 2;

Output:

total number of registrations

Example #9

Find the total number of registrations grouped together by city having registrations more than 1 but less than 4.

Code:

SELECT city,
count(regis_id) as "Total no. of registrations"
FROM registrations
GROUP BY city
HAVING count(regis_id) BETWEEN 1 AND 3;

Output:

SQL COUNT 11

COUNT() with ORDER BY clause.

Example #10

Find the total number of users grouped together by date of registration. Order the records fetched according to the total number of usernames.

Code:

SELECT date_of_regis, count(username)
FROM registrations
GROUP BY date_of_regis
ORDER BY count(username);

Output:

SQL COUNT 12

Advantages of SQL COUNT

Given below are the advantages mentioned:

  • COUNT() is a statistical function that helps to count the number of records in the result set of a SELECT query.
  • COUNT(), when used with DISTINCT, helps to count the number of unique records in the table.
  • COUNT(), when used as an aggregate function in the GROUP BY clause, helps in finding the number of records in each group.
  • COUNT(), when used with the HAVING clause, helps to filter records based on the number of records.

Conclusion

COUNT() is an aggregate function in SQL that returns the total number of records fetched by a SELECT statement based on the specified conditions in the WHERE, GROUP BY or HAVING clauses.

Recommended Articles

This is a guide to SQL COUNT. Here we discuss the introduction, examples of SQL COUNT, along with advantages, respectively. You may also have a look at the following articles to learn more –

  1. SQL ORDER BY CASE
  2. SQL GROUP BY Month
  3. SQL GROUP BY Multiple Columns
  4. SQL NOT Operator

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
SQL Tutorial
  • Functions
    • SQL Date Function
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL Window Functions
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite?functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL MOD()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Server Permission
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ADD Column
    • SQL Ranking Function
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Server Versions
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • GROUP BY clause in SQL
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • Alternate Key in SQL
    • SQL Super Key
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • SQL Formatter
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • NoSQ
    • NoSQL Databases List
    • NoSQL Injection
    • NoSQL vs SQL Databases
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

4th of July Offer - JDBC Training Course Learn More