简体   繁体   English

为 SQL 服务器中的数字列选择最佳数据类型

[英]Choosing best datatype for numeric column in SQL Server

I have a table in SQL Server with large amount of data - around 40 million rows.我在 SQL 服务器中有一张表,其中包含大量数据 - 大约 4000 万行。 The base structure is like this:基本结构是这样的:

Title标题 type类型 length长度 Null distribution Null经销
Customer-Id客户ID number数字 8 8 60% 60%
Card-Serial卡系列 number数字 5 5 70% 70%
- - - - - - - -
- - - - - - - -
Note笔记 string-unicode字符串-unicode 2000 2000 40% 40%

Both numeric columns are filled by numbers with specific length.两个数字列都由具有特定长度的数字填充。

I have no idea which data type to choose to have a database in the smallest size and having good performance by indexing the customerId column.我不知道选择哪种数据类型来拥有最小大小的数据库并通过索引customerId列来获得良好的性能。 Refer to this Post if I choose CHAR(8) , database consume 8 bytes per row even in null data.如果我选择CHAR(8) ,请参阅这篇文章,即使在 null 数据中,数据库每行消耗 8 个字节。

I decided to use INT to reduce the database size and having good index, but null data will use 4 bytes per rows again.我决定使用INT来减小数据库大小并拥有良好的索引,但 null 数据将再次使用每行 4 个字节。 If I want to reduce this size, I can use VARCHAR(8) , but I don't know, the system has good performance on setting index on this type or not.如果我想减小这个大小,我可以使用VARCHAR(8) ,但我不知道,系统在设置索引这个类型上是否有很好的性能。 The main question is reducing database size is important or having good index on numeric type.主要问题是减少数据库大小很重要,或者对数字类型有良好的索引。

Thanks.谢谢。

If it is a number - then by all means choose a numeric datatype!!如果它是一个数字- 那么一定选择一个数字数据类型! Don't store your numbers as char(n) or varchar(n) .!不要将您的数字存储为char(n)varchar(n) 。! That'll just cause you immeasurable grief and headaches later on.那只会在以后给你带来无法估量的悲伤和头痛。

The choice is pretty clear:选择很明确:

  • if you have whole numbers - use TINYINT , SMALLINT , INT or BIGINT - depending on the number range you need如果你有整数- 使用TINYINTSMALLINTINTBIGINT - 取决于你需要的数字范围

  • if you need fractional numbers - use DECIMAL(p,s) for the best and most robust behaviour (no rounding errors like FLOAT or REAL )如果您需要小数- 使用DECIMAL(p,s)以获得最佳和最稳健的行为(没有像FLOATREAL这样的舍入错误)

Picking the most appropriate datatype is much more important than any micro-optimization for storage.选择最合适的数据类型比任何存储的微优化都重要得多。 Even with 40 million rows - that's still not a big issue, whether you use 4 or 8 bytes.即使有 4000 万行 - 这仍然不是一个大问题,无论您使用 4 字节还是 8 字节。 Whether you use a numeric type vs. a string type - that makes a huge difference in usability and handling of your database!无论您使用数字类型还是字符串类型 - 这都会对数据库的可用性和处理产生巨大影响!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM