Select NULL As Max or Min in SQL Query

Who is online?  0 guests and 1 members
Home  »  Blogs  »  BradSchacht  »  Select NULL As Max or Min in SQL Query
 
0
/5
Avg: 0/5: (0 votes)

Comments (2)

gcovain
gcovain said:

Hello Brad,

One problem with this technique is that, as you said in your post, it counts on the fact that the data itself will never include the replacement value.
I think this presents a risk as other developers can use the same improbable value (from the business point of view) to implement some special cases, and insert it in the table.

For your example, there is at least one alternative solution based on ROW_NUMBER and CTEs :

For the MIN case, we can use the behavior of the ORDER BY clause regarding NULL values : "Null values are treated as the lowest possible values."
-- CODE --
;WITH IntermediateDataCTE AS
(
    SELECT
        StoreID,
        ROW_NUMBER() OVER (PARTITION BY StoreID
                           ORDER BY EndDate ASC) AS DateRank,
        EndDate AS Date
    FROM WorkSchedule
)
SELECT
    StoreID,
    Date
FROM IntermediateDataCTE
WHERE DateRank = 1
-- END OF CODE --


For the MAX case, it gets a bit uglier :
-- CODE --
;WITH IntermediateDataCTE AS
(
    SELECT
        StoreID,
        ROW_NUMBER() OVER (PARTITION BY StoreID
                           ORDER BY CASE WHEN EndDate IS NULL THEN 1 ELSE 0 END DESC,
                                    EndDate DESC) AS DateRank,
        EndDate AS Date
    FROM WorkSchedule
)
SELECT
    StoreID,
    Date
FROM IntermediateDataCTE
WHERE DateRank = 1
-- END OF CODE --

If there is any NULL value it ends up at the first position thanks to the first part of the ORDER BY expression, otherwise the greater date ends up at the first position thanks to the second part.
At worst the CASE WHEN thing can be defined as a computed column expression, in order to be included in an index.

This obviously need in-situation performance testing on a case-by-case basis, and probably will be difficult to use in more complex queries, but I think it can be worth the test :-)


Gaël

8/29/2010
 · 
 
by
BradSchacht
BradSchacht said:

Someone posted a comment for this blog on another article on BIDN by mistake.  The question was

"Would

SELECT
StoreID,
Max(ISNULL(EndDate,'12/31/2099'))
FROM WorkSchedule
GROUP BY StoreID

Not work in this scenario?"

 

This would not work if you wanted to actually return NULL since the query above would return 12/31/2099.  That is why we have to have the case statement in there to replace the 12/31/2099 with NULL.

8/30/2010
 · 
 
by
Blogs RSS Feed

BradSchacht's latest blog posts

Blogs RSS Feed

Latest community blog posts