We have a SQL Server 2005 database for which we want to improve performance of bulk delete/insert/selects and I notice it uses decimal(18,0) for its primary keys. I understand this will give us many more values than bigint but was hoping it might be a quick win and should last us for many million years of growth by my calculations.
I see in the .net docs decimals take 16 bytes instead of the 8 required by longs but in SQL Server it looks like bigint take 8 bytes but the decimal(18,0) takes only 5 bytes – as also seen by select DATALENGTH(max(id)) from table. Is this correct?
Is there any other reason bigint might be slower or should I stick to decimal(18,0)?
DATALENGTH is casting to varchar before counting bytes. So your max value is < 100000.
The 9 bytes can be proved with this. sys.columns has a max_length column (decimal is fixed length so it is always 9 bytes, before you ask otherwise)
For legacy reasons,
decimal(18, 0)was often used as a surrogate for “64 bit integer” before bigint was added with SQL Server 2000.decimal(18, 0)andbigintare roughly the same in range: decimal is one byte more at 9 bytes as per the documentationOn top of that, plain integer will be fractionally (maybe not measurable) faster then decimal. Saying that, if expect to have more then 4 billion rows in the next year or 5, then the performance should matter. If it doesn’t, then just use
int