Using “varchar” as the primary key? bad idea? or ok?

前端 未结 5 2045
一整个雨季
一整个雨季 2021-01-01 12:43

Is it really that bad to use \"varchar\" as the primary key?

(will be storing user documents, and yes it can exceed 2+ billion documents)

5条回答
  •  星月不相逢
    2021-01-01 13:29

    I realize I'm a bit late to the party here, but thought it would be helpful to elaborate a bit on previous answers.

    It is not always bad to use a VARCHAR() as a primary key, but it almost always is. So far, I have not encountered a time when I couldn't come up with a better fixed size primary key field.

    VARCHAR requires more processing than an integer (INT) or a short fixed length char (CHAR) field does.

    In addition to storing extra bytes which indicate the "actual" length of the data stored in this field for each record, the database engine must do extra work to calculate the position (in memory) of the starting and ending bytes of the field before each read.

    Foreign keys must also use the same data type as the primary key of the referenced parent table, so processing further compounds when joining tables for output.

    With a small amount of data, this additional processing is not likely to be noticeable, but as a database grows you will begin to see degradation.

    You said you are using a GUID as your key, so you know ahead of time that the column has a fixed length. This is a good time to use a fixed length CHAR(36) field, which incurs far less processing overhead.

提交回复
热议问题