Dear readers of our blog, we'd like to recommend you to visit the main page of our website, where you can learn about our product SQLS*Plus and its advantages.
 
SQLS*Plus - best SQL Server command line reporting and automation tool! SQLS*Plus is several orders of magnitude better than SQL Server sqlcmd and osql command line tools.
 

REQUEST COMPLIMENTARY SQLS*PLUS LICENCE

Enteros UpBeat offers a patented database performance management SaaS platform. It proactively identifies root causes of complex revenue-impacting database performance issues across a growing number of RDBMS, NoSQL, and deep/machine learning database platforms. We support Oracle, SQL Server, IBM DB2, MongoDB, Casandra, MySQL, Amazon Aurora, and other database systems.

Sql Count Function

7 July 2020

COUNT SQL function

Sql Count Function – COUNT is used to calculate the number of rows returned in the SELECT operator.

Syntax for COUNT function in SQL

SELECT COUNT(aggregate_expression_id)
FROM tabs
[WHERE conds]
[ORDER BY [ ASC | DESC ]];

Or syntax for COUNT function when grouping results by one or more columns.

SELECT expression1_id,2_id, ..._n_id,
COUNT(aggregate_expression_id)
FROM tabs
[WHERE conds]
GROUP BY1_id, 2_id, ..._n_id
[ORDER BY [ ASC | DESC ]];

Parameters or arguments:

  • expression1_id,2_id,… – Expressions that are not encapsulated in the COUNT function and must be included in the GROUP BY sentence at the end of the SQL query.
  • aggregate_expression_id – This is the column or expression whose non-zero values will be taken into account.
  • tabs – The tables from which you want the records. The FROM sentence must contain at least one table
  • WHERE conds – It’s optional. These are the conditions that must be met to select records.
  • ORDER BY – It’s optional. The expression used to sort the records in the result set. If more than one expression is specified, the values must be separated by commas.
  • ASC – It’s optional. ASC sorts the resultant set in ascending order by. This is the default behavior if no modifier is specified.
  • DESC – It’s optional. DESC sorts the result set in descending order of colors.

COUNT function only includes NOT NULL values

Not everyone understands this, but the COUNT function will only count those records in which NULL is NOT equal to COUNT(s). When expressions is NULL, it is not included in COUNT calculations. Let’s look at this further.

In this example, we have a table with the following data:

custom_idf_namel_namefav_website
4000JustinBiebergoogle.com
5000SelenaGomezbing.com
6000 MilaKunisyahoo.com
7000TomCruiseoracle.com
8000JohnnyDeppNULL
9000RussellCrowegoogle.com

 

Enter the following SELECT query that uses the COUNT function.

SELECT COUNT(custom_id)
FROM customs;

1 entry will be selected. Here are the results that you should get.

COUNT(custom_id)
6

 

In this example, the query will return 6 because the customer table has 6 records and all custom_id values are NOT NULL (i.e. custom_id is the primary key for the table).

But what happens when we encounter a value of NULL using the function COUNT? Let’s enter the following SELECT operator, which will calculate the fav_website column, which may contain values NULL.

SELECT COUNT(fav_website)
FROM customs;

1 entry will be selected. Here are the results that you should get.

COUNT(fav_website)
5

 

In the second example, value 5 will be returned. Since one of the fav_website values is NULL, it will be excluded from the COUNT function calculation. As a result, the query will return 5 instead of 6.

Tip: Use primary key in COUNT or COUNT(*) function if you want to make sure that records are not excluded in the calculations.

Use a single expression in the COUNT function

Let’s look at an example that shows how to use the COUNT function with a single expression in a query.

In this example, we have a table with the following data:

empl_numberf_namel_namesalary_iddept1_id
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

 

Enter the following SQL statement.

SELECT COUNT(*) AS total_id
FROM empls
WHERE salary_id > 50,000;

1 entry will be selected. Here are the results that you should get.

total_id
3

 

In this example, we will return the number of employees with salaries over $50,000. We have assigned the COUNT(*) nickname total to make our query results more readable. The total_id will now appear as the column header when we return the result set.

Using GROUP BY with COUNT function

In some cases you will need to use the GROUP BY operator with the COUNT function. This happens when the SELECT operator contains columns that are not part of the COUNT function. Let us look at this further.

Again, using a table filled with the following data.

empl_numberf_namel_namesalary_iddept1_id
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

 

Enter the following SQL statement.

SELECT dept1_id,
COUNT(*) AS total_id
FROM empls
WHERE salary_id > 50,000
GROUP BY dept1_id;

Two entries will be selected. Here are the results that you should get.

dept1_idtotal_id
5002
5011

 

In this example, the COUNT function will return the number of employees who earn over $50,000 for each dept1_id. Since the dept1_id column is not included in the COUNT function, it must be specified in the GROUP BY operator.

Using DISTINCT with function COUNT

Did you know that you can use DISTINCT in the COUNT function? This allows only unique values to be calculated.

Using the same table as in the previous example.

empl_numberf_namel_namesalary_iddept1_id
1001JustinBieber62000500
1002SelenaGomez57500500
1003MilaKunis71000501
1004TomCruise42000501

 

Enter the following SQL statement.

SELECT COUNT(DISTINCT dept_id) AS total
FROM employees
WHERE salary > 50,000;
1 entry will be selected. Here are the results that you should get.

total_id
2

In this example, the COUNT function will return a unique number of dept1_id values, in which at least one employee has more than $50,000.

TIP: Configuring performance with the COUNT function
Since the COUNT function will return the same results regardless of which NOT NULL fields are included in the COUNT function parameters (i.e. in brackets), you can use COUNT(1) to improve performance. Now the database kernel will not need to extract any data fields, instead it will just get an integer value of 1.

For example, instead of entering this operator.

SELECT dept1_id,
COUNT(*) AS total_id
FROM empls
WHERE salary_id > 50,000
GROUP BY dept1_id;

You can replace COUNT(*) with COUNT(1) to increase productivity.

SELECT dept1_id,
COUNT(1) AS total_id
FROM empls
WHERE salary_id > 50,000
GROUP BY dept1_id;

The COUNT function now does not need to extract all fields from the employees table as it would have been if the COUNT(*) syntax had been used. It will simply get a numeric value of 1 for each entry that matches your criteria.

Sql Training Online – Sql Count Function

 
Tags: , , , , , ,

MORE NEWS

 

Preamble​​NoSql is not a replacement for SQL databases but is a valid alternative for many situations where standard SQL is not the best approach for...

Preamble​​MongoDB Conditional operators specify a condition to which the value of the document field shall correspond.Comparison Query Operators $eq...

5 Database management trends impacting database administrationIn the realm of database management systems, moreover half (52%) of your competitors feel...

The data type is defined as the type of data that any column or variable can store in MS SQL Server. What is the data type? When you create any table or...

Preamble​​MS SQL Server is a client-server architecture. MS SQL Server process starts with the client application sending a query.SQL Server accepts,...

First the basics: what is the master/slave?One database server (“master”) responds and can do anything. A lot of other database servers store copies of all...

Preamble​​Atom Hopper (based on Apache Abdera) for those who may not know is an open-source project sponsored by Rackspace. Today we will figure out how to...

Preamble​​MongoDB recently introduced its new aggregation structure. This structure provides a simpler solution for calculating aggregated values rather...

FlexibilityOne of the most advertised features of MongoDB is its flexibility.  Flexibility, however, is a double-edged sword. More flexibility means more...

Preamble​​SQLShell is a cross-platform command-line tool for SQL, similar to psql for PostgreSQL or MySQL command-line tool for MySQL.Why use it?If you...

Preamble​​Writing an application on top of the framework on top of the driver on top of the database is a bit like a game on the phone: you say “insert...

Preamble​​Oracle Coherence is a distributed cache that is functionally comparable with Memcached. In addition to the basic function of the API cache, it...

Preamble​​IBM pureXML, a proprietary XML database built on a relational mechanism (designed for puns) that offers both relational ( SQL / XML ) and...

  What is PostgreSQL array? In PostgreSQL we can define a column as an array of valid data types. The data type can be built-in, custom or enumerated....

Preamble​​If you are a Linux sysadmin or developer, there comes a time when you need to manage an Oracle database that can work in your environment.In this...

Preamble​​Starting with Microsoft SQL Server 2008, by default, the group of local administrators is no longer added to SQL Server administrators during the...