Suppose you have a query that returns multiple date columns, and suppose you want to return the latest date, regardless of which column it came from.
As from SQL Server 2022 we can use the GREATEST()
function to easily achieve this outcome.
Example
The following table contains multiple date columns:
SELECT * FROM t1;
Result:
Date1 Date2 Date3 ---------------- ---------------- ---------------- 2020-01-24 2023-11-17 2021-10-03 1997-10-30 1950-11-23 1970-01-14 2022-01-05 2000-05-15 2201-09-03
Below is how we can use the GREATEST()
function to return the latest date, regardless of which column its stored:
SELECT
GREATEST( Date1, Date2, Date3 ) AS "Latest Date"
FROM t1;
Result:
Latest Date ---------------- 2023-11-17 1997-10-30 2201-09-03
We simply pass the three columns to the GREATEST()
function, and it works out which one is the latest/greatest.