Get the Row Count from an Outer Table Join

Aggregate functions summarize data over groups of rows from a query result set. When using an aggregate function like COUNT with an “*” or “1”…

OpenText  profile picture
OpenText

October 22, 20191 minute read

Construction site crane building a blue SQL 3D text. Part of a series.

Aggregate functions summarize data over groups of rows from a query result set. When using an aggregate function like COUNT with an “*” or “1” parameter value, you may get a different result when the query implements a LEFT join verses an INNER join.

Example:

dbadmin=> SELECT * FROM t1 ORDER BY 1;
 c
---
 1
 2
 4
(3 rows)

dbadmin=> SELECT * FROM t2 ORDER BY 1;
 c
---
 1
 2
(2 rows)

dbadmin=> SELECT COUNT(*)
dbadmin->   INNER FROM t1
dbadmin->   JOIN t2 ON t1.c = t2.c;
 COUNT
-------
     2
(1 row)

dbadmin=> SELECT COUNT(*)
dbadmin->   FROM t1
dbadmin->   LEFT JOIN t2 ON t1.c = t2.c;
 COUNT
-------
     3
(1 row)

If you want a row count of just the rows from the left outer table that join to the inner table, you have to specify a column name from the left outer table in the COUNT function.

dbadmin=> SELECT COUNT(t2.c) t2_count
dbadmin->   FROM t1
dbadmin->   LEFT JOIN t2 ON t1.c = t2.c;
 t2_count
----------
        2
(1 row)

Have fun!

Share this post

Share this post to x. Share to linkedin. Mail to
OpenText avatar image

OpenText

OpenText, The Information Company, enables organizations to gain insight through market-leading information management solutions, powered by OpenText Cloud Editions.

See all posts

More from the author

All we want for Christmas:  An open letter to Santa from a modern legal team  

All we want for Christmas:  An open letter to Santa from a modern legal team  

As legal professionals embracing digital transformation, our wish list is a bit different this year.

December 11, 2024 4 minute read

OpenText Intelligence Aviator: Your data’s new best friend 

OpenText Intelligence Aviator: Your data’s new best friend 

Creating a data-driven culture within enterprises is a challenge.

November 19, 2024 3 minute read

Supercharge Your Data Strategy with the Latest Insights on Data and AI

Supercharge Your Data Strategy with the Latest Insights on Data and AI

Introducing the 2024 CXO Insights Guide on Data & AI Guide

October 31, 2024 6 minute read

Stay in the loop!

Get our most popular content delivered monthly to your inbox.