Understanding how aggregate functions operate in SQL is critical to writing correct queries. When adding an aggregate function (like sum, avg, min, max, count) to a query, you are asking the database to perform a group operation on a set of results. Most aggregates, like min and max, will return null when presented with an empty set of rows to operate on. The exception to this is count() - it (correctly) returns 0 when presented with an empty set or rows.
This question arose from the analysis of a much more complex query - one with multiple subquery expressions in the select clause. As it turns out, the addition of count(*) in the select expression caused some havoc to the results - as it started returning a value where none was expected.
What the developer really wanted, was a case where count(*)
would produce null. The easiest way to achieve this is through the use of analytics in Oracle. The query can be written to use the analytic count equivalent: count(*) over ()
select 'abc ' || (select txt from
(select count(*) over (), 'xyz' as txt from dual where 1=2))
from dual