Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reason why min and max not working on bit fields

Tags:

sql

sql-server

Probably I'm missing something, but it still looks strange for me why it's impossible to use max and min aggregates on bit fields. So if I try to do something like this:

declare @temp table (data bit)

insert into @temp
select 1 union all
select 0

select max(data) from @temp

I'll get an error Operand data type bit is invalid for max operator. But if I do something like this:

declare @temp table (data bit)

insert into @temp
select 1 union all
select 0

select top 1 * from @temp order by data desc

It works fine, so SQL Server does know how to sort bit fields. But the possibility to order data implies that we can get a maximum or minimum. What's the reason behind this restriction then?

like image 219
Roman Pekar Avatar asked Mar 25 '15 10:03

Roman Pekar


1 Answers

Unless we can get some inside information from the SQL Server team we might have to accept that sometimes the answer is just "because". The documentation is quite clear though, for example the MSDN page for MIN states;

MIN can be used with numeric, char, varchar, uniqueidentifier, or datetime columns, but not with bit columns.

My guess (yes, I am prepared to be flamed for hazarding a guess in an SO answer!) is that the benefit doesn't outweigh the risk of the change to the code. What exactly would the benefit be?

You're not the first to ask but the response to Aggregate functions on BIT columns: MIN and MAX on MS Connect suggests it's not likely to change.

like image 102
Rhys Jones Avatar answered Oct 15 '22 15:10

Rhys Jones