Skip to content
Advertisement

Generalized way to remove empty row given by aggregate functions

Example:

The below query would give an empty NULL row when no data is present.

The NULL row result looks like this:

MaxNumber
1 NULL

To detect if the query returns data or not I had to do this:

Returns 1 if a max number exists and 0 if empty table. Is this how we generally tackle the empty row produced by the aggregate function or is there a more generalized way?

Usecase in SQLite fiddle.

Fiddle is useful for demonstration, but we ask that posts includes complete examples

Usecase example (See comments in the example):-

TourCompletionDateTime TourID
2022-07-26T09:36:00.730589Z tour5416
TourCompletionDateTime TourID
2022-07-26T09:36:00.730589Z tour5416
2022-07-26T10:36:00.730589Z tour5417
TourCompletionDateTime TourID
2022-07-26T09:36:00.730589Z tour5416
2022-07-26T10:36:00.730589Z tour5417

This question is not relevant to this question. So, don’t suggest that. The previous question’s max aggregate function was not getting used in WHERE condition but this question’s use case makes use of max aggregate in usecase.

Advertisement

Answer

Use HAVING <predicate> to filter out rows after aggregating.

The modified query:

Will return the maximum number. In case the maximum number evaluates to null, it will return zero rows instead.

See example at db<>fiddle.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement