Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good idea to use a computed column as part of a primary key?

I've got a table defined as :

OrderID bigint NOT NULL,
IDA varchar(50) NULL,
IDB bigint NULL,
[ ... 50 other non relevant columns ...]

The natural primary key for this table would be (OrderID,IDA,IDB), but this it not possible because IDA and IDB can be null (they can both be null, but they are never both defined at the same time). Right now I've got a unique constraint on those 3 columns.

Now, the thing is I need a primary key to enable transactional replication, and I'm faced with two choices :

  • Create an identity column and use it as a primary key
  • Create a non-null computed column C containing either IDA or IDB or '' if both columns were null, and use (OrderID,C) as my primary key.

The second alternative seams cleaner as my PK would be meaningful, and is feasible (see msdn link), but since I've never seen this done anywhere, I was wondering if they were some cons to this approach.

like image 660
Brann Avatar asked May 04 '10 08:05

Brann


1 Answers

Columns, that can be null don't qualify as part of a pk, because a pk must also be unique.

Also a PK should never be meaningful, because the meaning of a value might change.

Do Table A and B have a relation? Look at the Relational Data model. There might be a mistake in the design.

OrderID should be unique and therefore enough for a PK.

like image 82
Michael Avatar answered Sep 30 '22 20:09

Michael