Will a table with varchar(255) PRIMARY KEY hurt anything?

别来无恙 提交于 2019-12-08 00:27:20

问题


I know it's not a good idea, but I would like to double check that this won't do something crazy like crash the server.

CREATE TABLE [dbo].[Items](
    [Id] [nvarchar](255) NOT NULL PRIMARY KEY,
    [Value] [nvarchar](max) NOT NULL,
)

It would be interesting to know details about how a key like this compares to an [int] key, but just confirmation that this will not hurt anything is sufficient.


回答1:


Can you use VARCHAR(#) as a primary key?

Yes.
From the documentation, a VARCHAR(255) will take upwards of 257 (255+2) bytes (depends on the length of the actual data), for that column -- per row.

It would be interesting to know details about how a key like this compares to an INT key

INT takes 4 bytes, according to documentation. Depending on your data, there are numeric data types that take less space:

  • SMALLINT: 2 bytes
  • TINYINT: 1 byte

The lower the number of bytes, the faster accessing data in the column will be. That includes JOINs. Additionally, the database (and backups) will be smaller.

I would greatly question the need for such a large VARCHAR as the primary key -- GUIDs aren't even that long.




回答2:


No, you can create a primary key on almost any SQL type. SQL will not allow it if it would crash the server. As you already stated, this will not be great for the server memory or performance, though.

In fact, here is the SO answer to the performance part of this question.




回答3:


There is a performance overhead with this, but it won't 'crash the server'.



来源:https://stackoverflow.com/questions/9780427/will-a-table-with-varchar255-primary-key-hurt-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!