Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalar Max in Sql Server

Tags:

sql

sql-server

How to implement the scalar MAX in Sql server (like Math.Max). (In essense I want to implement something like Max(expression, 0), to make negative values replaced by 0.)

I've seen in other threads solutions with

  • creating a scalar function (how's that with performance?)
  • case when expression > 0 THEN expression ELSE 0) (then 'expression' is evaluated twice?)
  • complicated uses of Max(aggregate).

What's the best? Why does Sql Server not have something like this built in? Any complications I don't see?

like image 293
Rein Avatar asked Aug 20 '09 15:08

Rein


People also ask

Is Max a scalar function?

Notes. The MAX scalar function is a synonym for the GREATEST scalar function. The MAX function cannot be used as a source function when creating a user-defined function.

What is Max in SQL Server?

MAX returns NULL when there is no row to select. For character columns, MAX finds the highest value in the collating sequence. MAX is a deterministic function when used without the OVER and ORDER BY clauses. It is nondeterministic when specified with the OVER and ORDER BY clauses.

Can you use MAX () on strings SQL?

The MAX() function can be used on the string column.

How does Max work in SQL?

The SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.


2 Answers

In all other major systems this function is called GREATEST.

SQL Server seriously lacks it.

You can make a bunch of case statements, or use something like this:

SELECT  (
        SELECT  MAX(expression)
        FROM    (
                SELECT  expression
                UNION ALL
                SELECT  0
                ) q
        ) AS greatest
FROM    table_that_has_a_field_named_expression

The latter one is a trifle less performant than CASE statements.

like image 142
Quassnoi Avatar answered Sep 22 '22 21:09

Quassnoi


you want to create a user-defined scalar function named MAX in sql server to take two parameters as input, an expression and a min value, and return the expression if it exceeds the min value, otherwise return the min value?

I wouldn't worry about the performance of scalar functions, let the server do that. I'd also use IF instead of CASE to test for > min value.

SQL server doesn't have a built in function for you because they didn't think it would be widely enough used, I guess.

like image 33
Beth Avatar answered Sep 20 '22 21:09

Beth