HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

What does SELECT MIN(+ - Column) do?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
whatcolumnmindoesselect

Problem

I ran into a query today that did something I haven't seen before. It did something like this:

SELECT 
    MIN(+ - schema_id) AS [WhatInTheWorld?], 
    MIN(schema_id) AS MinimumID, 
    MAX(+ - schema_id) AS [Uhhh], 
    MAX(schema_id) AS MaxID
FROM sys.objects


Which gives the following results:

WhatInTheWorld? MinimumID    Uhhh       MaxID
-4              1            -1         4


What exactly are the "+" and "-" doing?

Solution

MIN(+ - schema_id) is parsed as MIN( + (- schema_id) ) which is the same as MIN(- schema_id), so it's (mathematicaly)* the same as -MAX(schema_id). Likewise for the MAX.

*: There are some edge cases when the MIN/MAX(-x) might raise an error while the - MAX/MIN(x) will not (because the negation is applied in all values of the column vs only to the MAX/MIN value).

Context

StackExchange Database Administrators Q#211940, answer score: 11

Revisions (0)

No revisions yet.