Greatest Function
Greatest() Function
Last updated:
Warning: Review and test in a non-production environment before running.
-- Examples from Microsoft Learn: GREATEST (Transact-SQL) – https://learn.microsoft.com/en-us/sql/t-sql/functions/logical-functions-greatest-transact-sql
Greatest Function
SQL Server 2022 (16.x) Preview
This function returns the maximum value from a list of one or more expressions.
GREATEST ( expression1 [ ,...expressionN ] )
Examples:
SELECT GREATEST ( '6.62', 3.1415, N'7' ) AS GreatestVal;
GO
GreatestVal
--------
7.0000
(1 rows affected)
SELECT GREATEST ('Glacier', N'Joshua Tree', 'Mount Rainier') AS GreatestString;
GO
GreatestString
-------------
Mount Rainier
(1 rows affected)
SELECT P.Name, P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate AS ModelModifiedDate
, GREATEST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) AS LatestDate
FROM SalesLT.Product AS P
INNER JOIN SalesLT.ProductModel AS PM on P.ProductModelID = PM.ProductModelID
WHERE GREATEST(P.SellStartDate, P.DiscontinuedDate, PM.ModifiedDate) >='2007-01-01'
AND P.SellStartDate >='2007-01-01'
AND P.Name LIKE 'Touring %'
ORDER BY P.Name;
Name SellStartDate DiscontinuedDate ModelModifiedDate LatestDate
-------------------- ----------------------- ------------------- ----------------------- -----------------------
Touring Pedal 2007-07-01 00:00:00.000 NULL 2009-05-16 16:34:29.027 2009-05-16 16:34:29.027
Touring Tire 2007-07-01 00:00:00.000 NULL 2007-06-01 00:00:00.000 2007-07-01 00:00:00.000
Touring Tire Tube 2007-07-01 00:00:00.000 NULL 2007-06-01 00:00:00.000 2007-07-01 00:00:00.000
(3 rows affected)