I'm reviewing some SQL statement which uses a COALESCE
statement in an ORDER BY
. I've read the docs about COALESCE
so i'm trying to understand if I understand how it's getting used, in this scenario.
This is the part of the sql statement:
ORDER BY COALESCE([UpdatedOn], [CreatedOn]) DESC
Is it trying to say this (via some fake data I've made up):
** Note: DateFormat is yyyy-mm-dd
ELID | LK | CreatedOn | UpdatedOn | Computed-OrderBy
+---------------------------------------------------------
1 | 'aaa' | 2020-01-01 | 2020-01-02 | 2020-01-02
2 | 'bbb' | 2020-01-01 | NULL | 2020-01-01
so then, that is the result (in memory, etc) and SQL Server will order the results in the Computer-OrderBy
column (which we never really see)
So the results would be ordered:
ELID 2 - 2020-01-01
ELID 1 - 2020-01-02
UPDATE 1: If the COALESCE
was in a SELECT
statement, then I wouldn't be asking a question because I grok it. I'm asking about when ORDER BY
'ing .. how SQL sorta does it, behind the scenes. Notice how I've made up a new column Computed-OrderBy
? Well, I was hoping to see if that's more-or-less what Sql Server does ... so it knows how to order by those 'computed' values.