How to Create a Secondary Primary Key in a Database

databasedatabase-design

To some of my tables I want to add "second_primary_key" which will be uuid or some random long key. I need it because for some tables I don't want to expose integers to my web application. That is, on a page "/invoices" I have a list of invoices and a link to "/invoices/:id" where :id is an integer. I don't want a user to know how many invoices in my system there, hence instead of "/invoices/123" I want to use its "second_primary_key" so that the url will be "/invoices/N_8Zk241vNa"

The same goes for other tables where I want to hide real id.

I wonder, is this a common practice? What's the best way to implement this?

And what is this technique called after all, so that I do a search on it?

Best Answer

You could add a UUID column but you really don't need to (and shouldn't). This is a presentation layer concern. You wouldn't dream of say, storing a currency value as $1,999 as well as 1999.

You just want some way of obscuring the value on the fly for the application. You could either do this in the application itself or as a database view.

Since we're only talking about a single value, maybe look at 2 way encryption such as AES or similar - the more lightweight the better.

Hashing could be another possibility - it depends on whether you want to get the invoice number back, since hashing is one way.

Related Topic