Q

# Getting a count of zero for unmatched rows

I have a reference table and a data table and wish to perform a GROUP BY. The thing I am trying to accomplish is the pull EVERY 'reference' from the reference table and count the rows from the data table, respectively. Of course I can simply perform the GROUP BY on the data table and get the stats. But this only gives me existing data counts. I was hoping to build a single query that gives counts, including those references with counts of zero. I believe this should be possible. Hopefully the question is clear.

The question is very clear. Don't feel bad, because everybody stumbles over this problem the first time.

The situation can be illustrated with the following sample data:

```References
ID Reference
1  HTML
2  CSS
3  PHP
4  SQL

Data
ID RefID
24  1
24  2
24  4
27  2
27  4
31  1
31  4```

In order to understand how to get the correct counts, let's first write a simple LEFT OUTER JOIN and show the results:

```select References.ID
, References.Reference
, Data.ID     as Data_ID
from References
left outer
join Data
on References.ID = Data.RefID
order
by References.ID
, Data.ID

ID Reference Data_ID
1  HTML      24
1  HTML      31
2  CSS       24
2  CSS       27
3  PHP       null
4  SQL       24
4  SQL       27
4  SQL       31 ```

Notice the row in the result set for PHP. This row shows up in a LEFT OUTER JOIN, but would be eliminated in an INNER JOIN. (Make sure you understand why.)

Now let's add the GROUP BY and the COUNT() function.

```select References.ID
, References.Reference
, count(*)     as Data_rows
from References
left outer
join Data
on References.ID = Data.RefID
group
by References.ID
, Data.ID
order
by References.ID

ID Reference Data_rows
1  HTML      2
2  CSS       2
3  PHP       1
4  SQL       3 ```

Wait a minute, that's wrong! We know there are no rows for PHP, but the count is showing 1. Why is this?

The answer is: COUNT(*) counts rows. There is a row for PHP in the result set.

What you have to do is count the number of Data.RefID values. Note that in the result set, the value of this column for the PHP row is NULL. And as you know, aggregate functions like COUNT() and SUM() ignore nulls.

```select References.ID
, References.Reference
, count(Data.RefID)     as Data_rows
from References
left outer
join Data
on References.ID = Data.RefID
group
by References.ID
, Data.ID
order
by References.ID

ID Reference Data_rows
1  HTML      2
2  CSS       2
3  PHP       0
4  SQL       3 ```

See the difference?

This was last published in May 2005

## Content

Find more PRO+ content and other member only offers, here.

#### Have a question for an expert?

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

#### Start the conversation

Send me notifications when other members comment.

## SearchDataManagement

• ### With better scaling, semantic technology knocks on enterprise's door

Cambridge Semantics CTO Sean Martin says better scalability can lead to richer representations of data. Such advances are behind ...

• ### Big data management and analytics weather tumult -- with more in store

Cloud had a big impact on big data management and analytics last year. Machine learning and streaming designs will contribute to ...

• ### Embedded analytics to feel widest impact of machine learning projects

Ovum analyst Tony Baer discusses machine learning tools, IoT-driven streaming analytics and Hadoop in the cloud, all of which ...

• ### Cognitive computing applications present new business challenges

When implementing cognitive software, enterprises need to worry just as much -- if not more -- about the business implications, ...

• ### Researchers work on AI algorithms to detect fake news

A new challenge to identify fake news will test the boundaries of AI technology and offer a proving ground for innovative new ...

• ### Don't let a data-driven approach ax judgment from analytics equation

Data analytics can help improve decision-making in organizations. But human intuition and judgment need to be part of the picture...

## SearchSAP

• ### SAP HANA, express edition makes HANA easier for non-SAP developers

Relaxed RAM and licensing requirements and the ability to run on local machines could help popularize the HANA in-memory platform...

• ### SAP futurists name five future technology trends to plan for now

Three SAP futurists explain what future technology trends in augmented reality, blockchain, AI, robotics, and contingent labor ...

• ### Abakus acquisition beefs up SAP Hybris marketing portfolio

SAP acquires Abakus marketing measurement software for SAP Hybris marketing suite; openSAP adds new courses for S/4HANA, data ...

## SearchSQLServer

• ### Four trends that will impact SQL Server DBAs in 2017

Flash storage adoption, cloud computing's growth, Linux's increased importance and broader big data integration are a few trends ...

• ### DATEADD and DATEDIFF SQL functions for datetime values

DATEADD and DATEDIFF SQL functions allow you to easily perform calculations, like adding a time interval from a datetime value. ...

• ### SQL Server on Linux signals Microsoft's changing development landscape

Expert Joey D'Antoni explains what SQL Server on Linux and the addition of some Enterprise Edition features to the database's ...

## TheServerSide

• ### Is JSON and XML your REST performance bottleneck?

Learn how ASCII encoding formats like JSON and REST can adversely impact server application performance compared with emerging ...

• ### Making multi-cloud deployment a reality at Netflix with Spinnaker

Learn how Netflix leveraged automation and Spinnaker to perform 4,000 multi-cloud deployments per day.

• ### The benefits of Java microservices in a Docker and DevOps world

To seasoned developers, microservices may sound like SOA by another name. But Java microservices apps delivered via Docker ...

## SearchDataCenter

• ### What should my dimensions be for a data center building design?

Don't get hung up on data center dimensions in the design phase. Focus on length-to-width ratios to get the most out of data ...

• ### Use a Linux file system journal for data integrity, performance

Understand the three different file system journaling modes for Linux, as well as which mount option provides the best levels of ...

• ### Test yourself on modern data center networking architecture

Evolving business needs demand a new approach to data center networking. Keep yourself updated on SDN, VXLAN and other ...

## SearchContentManagement

• ### Using Microsoft MyAnalytics to improve workers' time management

Microsoft MyAnalytics has been hailed as the next great thing for analyzing worker productivity. But how can employees be assured...

• ### Is the Drupal content management system right for your business?

The open source Drupal content management system offers users responsive design and WYSIWYG content and web development tools, as...

• ### Manage your content with the IBM Digital Experience WCM platform

IBM Digital Experience is a WCM platform that offers users features for creating and managing digital content that can be ...

## SearchFinancialApplications

• ### Group-chat software sees explosive growth and intense competition

Microsoft Teams and Workplace by Facebook are facing off against rivals such as HipChat and Slack in a high-stakes competition ...

• ### HR to face sea change in online learning software and accent on teams

Deloitte predicts far-reaching trends for HR, including innovations in learning, an expansion of artificial intelligence, and an ...

• ### Experts lack consensus on discrimination risks of video interviewing

When used too early in the hiring process, video can lead to discrimination based on race, age or sex, but it can have positive ...

Close