How can I include null values in a MIN or MAX?
When dealing with NULL
inclusivity in MIN
or MAX
, place your bets on COALESCE
function to transform NULL
s to limit values suitable to your query's goal. Use a very high value for dealing with MIN
cases (as NULL
as the highest possible value), and a very low value for MAX
(to treat NULL
as the lowest conceivable value).
For minimum:
For maximum:
Choose sentinel values that fall beyond the practical limits for your column
.
Addressing the nuances
While infusing replacement value for NULL
, place weight on maintaining data type consistency with the column. For instance, if dealing with NULL
s in numeric columns, replace them with appropriate numeric extremes:
For cases where NULL
signifies ongoing timespans, consider GETDATE()
to provide an up-to-date maximum:
Juggling with group scenarios
With GROUP BY
involved in your calculations alongside MIN
and MAX
, you might run into NULL
values causing improper skewing. Group your results on RecordID or a meaningful key to ensure that your aggregates treat NULL
s consistently:
This measure caters towards the integrity of your grouped calculations, making null values a team player in the aggregation.
Paddling through alternatives
Count on NULLIF
In circumstances where you wish to exclude particular values from your MIN
or MAX
calculations and convert them into NULL
, NULLIF
steps in. It hands out a NULL if the two expressions put up an equal fight:
The counting game
When you're curious about the presence of NULL
values during your aggregations, play around with COUNT(column)
and COUNT(*)
. COUNT(column)
counts only the non-NULL values:
Calling up CASE statements
Bring out the CASE
statement to include NULLs into your calculations when working with more complex conditions:
Was this article helpful?