Search code examples
sql-serveraggregate-functionsisnull

Execution of ISNULL in SQL Server


Here is how i am using ISNULL condition to check for student address. It works fine but how ISNULL function treat the null codition i.e the second parameter which is display if first condition is null.

Will it calculate Value for second parameter when first condition is not null?

select 
   ...
   ...
   (CASE 
      WHEN st.ADDRESS='Y' THEN st.LOCATION
        ELSE 
          ISNULL(
                 (SELECT TOP 1 STDLOC.LOCATION FROM STDLOC 
                  INNER JOIN COMLOC ON STKLOC.LOCATION=COMLOC.CODE  AND COMLOC.ADDRESS='Y' 
                  WHERE STDLOC.ZIBCODE=st.ZIBCODE)
                ,(SELECT TOP 1 COMLOC.LOCATION  FROM COMLOC COMLOC.ZIBCODE=st.ZIBCODE))                       
       END
        ) AS STDUDENTLOCATION
   FROM STUDENT st

Solution

  • Both queries inside the ISNULL will be executed, even if the first query will return a value.

    Here is a simple test I've made:

    Create and populate sample table:

    DECLARE @T AS TABLE
    (
        Col int
    )
    INSERT INTO @T Values(1),(2)
    
    SELECT ISNULL(
        (SELECT TOP 1 Col FROM @T ORDER BY Col DESC), 
        (SELECT TOP 1 Col FROM @T ORDER BY Col )
    )
    

    Execution plan image:

    enter image description here

    As you can clearly see, the execution plan includes both queries.