SQL: Primary key or not for primary key?

I have a table with presets for users, it has the following columns:

UserID INT
Set VARCHAR(50)
Key VARCHAR(50)
Value NVARCHAR(MAX)
TimeStamp DATETIME

UserID along with Set and Key is unique. Therefore, a specific user cannot have two identical keys in a particular set of parameters. Settings are retrieved using a set, so if a user requests a specific key from a specific set, the entire set is loaded, so the next time a key from the same set is required, he does not need to access the database.

Should I create a primary key in all three columns (userid, set and key) or do I need to create an additional field with a primary key (for example, an integer number of auto-increments called SettingID, a bad idea, I think) or not create a primary key and just create unique index?

----- UPDATE -----

Just to clarify the situation: this is the end of the table row, in any case it is not combined. UserID is the FK for the Users table. The set is not FC. This is a pretty useful table for my GUI. As an example: users receive the first time they visit parts of a website, a help ball that they can close if they want. As soon as they recall it, I will add some settings to the "GettingStarted" set, which will indicate that helpballoon X is disabled. The next time the user goes to the same page, the setting will indicate that X help should not be displayed anymore.

+3
source share
8 answers

Should I create a primary key for all three columns (userid, set, and key)

Do it.

, .

UNIQUE INDEX PRIMARY KEY KEY lookup, .

UNIQUE INDEX PRIMARY KEY HEAP-organized, RID lookup : .

+2

.

- . , . , , script.

, , .

:

, , ( ).

+7

? varchar (50) ? Set Key SetId KeyId, 3 , .

+1

, , , UserID , , UserID . , , .

, - , , , , . . . , , SettingId .

0

. , , Key VARCHAR (50) - -.

0

, FK. , 3 FK?

FK . .

0

It is better to have UserID as 32-bit newid () or a unique identifier, because UserID as int gives a hint to the user of the likely UserID. This will also solve your composite key problem.

0
source

I am not a supporter of compound keys, but in this case, like the end of a line of a line, this may make sense. However, if you allow nulls in any of these three fields because one or more values ​​are unknown at the time of insertion, there may be difficulties, and a unique index may be better.

0
source

Source: https://habr.com/ru/post/1707745/


All Articles