COALESCE in Left Join

  • DonlSimpson (4/29/2015)


    Luis Cazares (4/29/2015)


    chgn01 (4/29/2015)


    How about use ISNULL?

    -- Q3

    SELECT

    *

    FROM

    #abc a

    LEFT JOIN #xyz x

    ON ISNULL(a.a, 9) = ISNULL(x.x, 9)

    AND ISNULL(a.b, 9) = ISNULL(x.y, 9);

    In this case, they'll act the same way. But that won't be always the case.

    If there's no coercing data going on, it should be the same. There's probably some esoteric exception though.

    There are 2 main differences between ISNULL() and COALESCE():

    The first (and widely known) difference is that ISNULL() will always accept 2 parameters (no more, no less) and COALESCE() can accept more parameters.

    The second difference is the way they handle the data types. ISNULL() will use the data type of the first parameter and will try to convert the second parameter into the first parameter data type. COALESCE(), on the other hand, will use the data type with the highest data type precedence and convert the rest of the parameters to that data type. If you're unaware of these rules, you might get some unexpected errors.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Carlo Romagnano (4/29/2015)


    Toreador (4/29/2015)


    Only 54% correct? I was expecting close to 100%!

    It depends if one has enough time to read correctly the question of th day.

    Yup! I *almost* answered wrong because I focused too much on the join condition and the NULL values, causing me to overlook that the query uses an outer join.

    Noticed my mistake just in time...


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/

  • I think I must be getting old and decrepit. Got it right, but it strained my brain 🙁

    Tom

  • Correct your 2nd table insert statement to "INSERT INTO #xyz values". Not "INSERT INTO #abc values".

  • When you look carefully you will know it.

Viewing 5 posts - 16 through 19 (of 19 total)

You must be logged in to reply to this topic. Login to reply