Confusion with primary key - sql

I am new to designing database. Maybe its a stupid question so please pardon me for that. So the thing is I am designing the database for users. After user fills registration information he gets the unique receipt number. So my question is since receipt no. is unique can I use it as a primary key in Users table or should I stick with standard method of assigning userID to each row in table and use userID as primary key?

A table can have more than one key. If the receipt number is intended to be unique and you want the DBMS to enforce key dependencies on that attribute as a data integrity constraint then yes you should make it a key (with uniqueness implemented by a PRIMARY KEY or UNIQUE constraint or whatever mechanisms your DBMS provides).
Designating any one key to be a "primary" one isn't especially important - or at least it is only as important as you want it to be. What really matters is the full set of key(s) you choose. The requirements for any key are Uniqueness and Irreducibility. Sensible criteria for choosing a key are also: Familiarity, Simplicity and Stability

if your receipt number contains only integer number then, may be you can make your receipt-no field as auto-increment number,

If your receipt no. is complicated enough - built using numbers and characters, or 20 digits in length - better use the surrogate UserId
If receipt No can be simple integer and may be generated from DB - better use UserId and assign its value to ReceiptNo
If ReceiptNo is simple integer and its identifies the user AND the only user - use it as PKey.

Related

Can I set this column as the primary key?

I'm new to SQL Server and would really appreciate it if you could help me out here.
So are a healthcare provider and internally we assign an ID to each patient (for example, 1234). I'm currently constructing another database, and I just wonder can I use our internal IDs as primary key, given they are unique? If so, since I am not going to do any calculation on the primary key, can I set them to string/char datatype for primary key?
In short, yes you can but it is not recommended at all!
To give you some heads up:
Primary keys should never change
You cannot use a natural key or a key form other system
They cannot have any formula
Use short but suitable key type
If you have an external key that you want to use to find some patients, create another column for it and add UNIQUE Constraint to it.
just don't forget to add index for that column
Read this post of mine for more information:
http://pilpag.blogspot.dk/2016/06/relational-database-designsimple-rules.html
The conditions for a primary key are that the key is unique in the table and never NULL.
Your patient id would appear to have these characteristics.
That said, there are good reasons for developing a synthetic primary key (auto-incremented/identity/serial depending on the database). More importantly, the actual patient ID may be sensitive information. For instance, patients might use the id when logging in or it might be printed on invoices.
It might not be a good idea to have sensitive information repeated throughout the database. For this reason, an "internal" id would be used to refer to patients in table and all the sensitive information would be contained in one or a handful of tables.
This would perhaps be more obvious if the "patient id" were a government id ("social security number") or email address.
Yes, but the ID can also be numeric and a primary key - it doesn't have to be a string. As long as the ID is unique, you should be fine.
Yes, you can use your internal IDs if they are unique;PK limit is 900 bytes for char/varchar data types.So if your IDs are int is fine. But if your IDs can change with time or can be reused them for more than one patient I strong recommend not to use them to avoid chaos. I prefer a surrogate key, like an identity
If I understand correctly, you are assigning each patient a number so as to uniquely identify them. So a report would contain the patient number rather than only a patient's name which can be ambiguous. You won't ever change the patient numbers, because then you'd have to change this in all databases and would have to re-print all documents on the patient that are still needed. This makes this number a perfect primary key for a patient table in any of your databases.
You could use a generated technical ID instead as the table's primary key and have the patient number only as another field in the table (which would still have a unique constraint of course, because it is still the business key uniquely identifying a patient). Whether to do this or not is mainly a matter of personal preference and experience. I prefer natural keys over IDs (so I would make the patient number the primary key). This stems from having worked with rather large databases with thousands of tables and much hierarchy where the natural keys proved to result in faster queries, enhanced data consistency and easier maintenance. Others may have different experience, though.
So yes, the patient number seems to be the perfect natural primary key in my opinion.

What is the difference between a primary key and a surrogate key?

I googled a lot, but I did not find the exact straight forward answer with an example.
Any example for this would be more helpful.
The primary key is a unique key in your table that you choose that best uniquely identifies a record in the table. All tables should have a primary key, because if you ever need to update or delete a record you need to know how to uniquely identify it.
A surrogate key is an artificially generated key. They're useful when your records essentially have no natural key (such as a Person table, since it's possible for two people born on the same date to have the same name, or records in a log, since it's possible for two events to happen such they they carry the same timestamp). Most often you'll see these implemented as integers in an automatically incrementing field, or as GUIDs that are generated automatically for each record. ID numbers are almost always surrogate keys.
Unlike primary keys, not all tables need surrogate keys, however. If you have a table that lists the states in America, you don't really need an ID number for them. You could use the state abbreviation as a primary key code.
The main advantage of the surrogate key is that they're easy to guarantee as unique. The main disadvantage is that they don't have any meaning. There's no meaning that "28" is Wisconsin, for example, but when you see 'WI' in the State column of your Address table, you know what state you're talking about without needing to look up which state is which in your State table.
A surrogate key is a made up value with the sole purpose of uniquely identifying a row. Usually, this is represented by an auto incrementing ID.
Example code:
CREATE TABLE Example
(
SurrogateKey INT IDENTITY(1,1) -- A surrogate key that increments automatically
)
A primary key is the identifying column or set of columns of a table. Can be surrogate key or any other unique combination of columns (for example a compound key). MUST be unique for any row and cannot be NULL.
Example code:
CREATE TABLE Example
(
PrimaryKey INT PRIMARY KEY -- A primary key is just an unique identifier
)
All keys are identifiers used as surrogates for the things they identify. E.F.Codd explained the concept of system-assigned surrogates as follows [1]:
Database users may cause the system to generate or delete a surrogate,
but they have no control over its value, nor is its value ever
displayed to them.
This is what is commonly referred to as a surrogate key. The definition is immediately problematic however because Codd was assuming that such a feature would be provided by the DBMS. DBMSs in general have no such feature. The keys are normally visible to at least some DBMS users as, for obvious reasons, they have to be. The concept of a surrogate has therefore morphed slightly in usage. The term is generally used in the data management profession to mean a key that is not exposed and used as an identifier in the business domain. Note that this is essentially unrelated to how the key is generated or how "artificial" it is perceived to be. All keys consist of symbols invented by humans or machines. The only possible significance of the term surrogate therefore relates how the key is used, not how it is created or what its values are.
[1] Extending the database relational model to capture more meaning, E.F.Codd, 1979
This is a great treatment describing the various kinds of keys:
http://www.agiledata.org/essays/keys.html
A surrogate key is typically a numeric value. Within SQL Server, Microsoft allows you to define a column with an identity property to help generate surrogate key values.
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain UNIQUE values.
A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE primary key.
http://www.databasejournal.com/features/mssql/article.php/3922066/SQL-Server-Natural-Key-Verses-Surrogate-Key.htm
I think Michelle Poolet describes it in a very clear way:
A surrogate key is an artificially produced value, most often a
system-managed, incrementing counter whose values can range from 1 to
n, where n represents a table's maximum number of rows. In SQL Server,
you create a surrogate key by assigning an identity property to a
column that has a number data type.
http://sqlmag.com/business-intelligence/surrogate-key-vs-natural-key
It usually helps you use a surrogate key when you change a composite key with an identity column.

Warning message for a primary key constraint

I have a problem with assigning a primary key in one of the tables containing employee info. There is no unique column in that table, The only option I am left with is taking combination of three columns as a primary key.
But it gives a warning message as Warning! The maximum key length is 900 bytes. The index 'pk_hrempid' has maximum length of 1530 bytes.For some combination of large values, the insert/update operation will fail I came to know that this would be a major problem in the future for inserting the data. Is there a solution for this warning?
Other question is can I put an auto-increment value as a unique id, is it recommended? I want to make sure that it does not give problems in the future as I have many tables containing employee info from the other departments. Some employees may be present in two or more tables
Any help is appreciated!
Whilst is it sounds from your attempt at a compound primary key that you're attempting the best-practice of using a "natural key", there's nothing 'wrong' with using an auto-incrementing ID field.
If your suggested fields are too large to be used as a key, perhaps they weren't the best choice in the first place. Could you add another "natural" key column with a better datatype perhaps?
Don't forget to take into account the optimizations that are possible by choosing good indexes and suitable datatypes for tables that are going to be heavily-queried.
This is a limitation of a primary key. You can not have a PK larger that 900 bytes.
You could add a identity column to the table and set it as the primary key. I prefer to use Guids as they are globally unique.
I'd go with an auto-increment type solution for the primary key, problem with using personal data for this sort of thing is that you cannot guarantee uniqueness which is the fundamental requirement of a primary key.

Database "key/ID" design ideas, Surrogate Key, Primary Key, etc

So I've seen several mentions of a surrogate key lately, and I'm not really sure what it is and how it differs from a primary key.
I always assumed that ID was my primary key in a table like this:
Users
ID, Guid
FirstName, Text
LastName, Text
SSN, Int
however, wikipedia defines a surrogate key as "A surrogate key in a database is a unique identifier for either an entity in the modeled world or an object in the database. The surrogate key is not derived from application data."
According to Wikipedia, it looks like ID is my surrogate key, and my primary key might be SSN+ID? Is this right? Is that a bad table design?
Assuming that table design is sound, would something like this be bad, for a table where the data didn't have anything unique about it?
LogEntry
ID, Guid
LogEntryID, Int [sql identity field +1 every time]
LogType, Int
Message, Text
No, your ID can be both a surrogate key (which just means it's not "derived from application data", e.g. an artificial key), and it should be your primary key, too.
The primary key is used to uniquely and safely identify any row in your table. It has to be stable, unique, and NOT NULL - an "artificial" ID usually has those properties.
I would normally recommend against using "natural" or real data for primary keys - are not REALLY 150% sure it's NEVER going to change?? The Swiss equivalent of the SSN for instance changes each time a woman marries (or gets divorced) - hardly an ideal candidate. And it's not guaranteed to be unique, either......
To spare yourself all that grief, just use a surrogate (artificial) ID that is system-defined, unique, and never changes and never has any application meaning (other than being your unique ID).
Scott Ambler has a pretty good article here which has a "glossary" of all the various keys and what they mean - you'll find natural, surrogate, primary key and a few more.
First, a Surrogate key is a key that is artificially generated within the database, as a unique value for each row in a table, and which has no dependency whatsoever on any other attribute in the table.
Now, the phrase Primary Key is a red herring. Whether a key is primary or an alternate doesn't mean anything. What matters is what the key is used for. Keys can serve two functions which are fundementally inconsistent with one another.
They are first and foremost there to ensure the integrity and consistency of your data! Each row in a table represents an instance of whatever entity that table is defined to hold data for. No Surrogate Key, by definition, can ever perform this function. Only a properly designed natural Key can do this. (If all you have is a surrogate key, you can always add another row with every other attributes exactly identical to an existing row, as long as you give it a different surrogate key value)
Secondly they are there to serve as references (pointers) for the foreign Keys in other tables which are children entities of an entity in the table with the Primary Key. A Natural Key, (especially if it is a composite of multiple attributes) is not a good choice for this function because it would mean tha that A) the foreign keys in all the child tables would also have to be composite keys, making them very wide, and thereby decreasing performance of all constraint operations and of SQL Joins. and B) If the value of the key changed in the main table, you would be required to do cascading updates on every table where the value was represented as a FK.
So the answer is simple... Always (wherever you care about data integrity/consistency) use a natural key and, where necessary, use both! When the natural key is a composite, or long, or not stable enough, add an alternate Surrogate key (as auto-incrementing integer for example) for use as targets of FKs in child tables. But at the risk of losing data consistency of your table, DO NOT remove the natural key from the main table.
To make this crystal clear let's make an example.
Say you have a table with Bank accounts in it... A natural Key might be the Bank Routing Number and the Account Number at the bank. To avoid using this twin composite key in every transaction record in the transactions table you might decide to put an artificially generated surrogate key on the BankAccount table which is just an integer. But you better keep the natural Key! If you didn't, if you did not also have the composite natural key, you could quite easily end up with two rows in the table as follows
id BankRoutingNumber BankAccountNumber BankBalance
1 12345678932154 9876543210123 $123.12
2 12345678932154 9876543210123 ($3,291.62)
Now, which one is right?
To marc from comments below, What good does it do you to be able to "identify the row"?? No good at all, it seems to me, because what we need to be able to identify is which bank account the row represents! Identifying the row is only important for internal database technical functions, like joins in queries, or for FK constraint operations, which, if/when they are necessary, should be using a surrogate key anyway, not the natural key.
You are right in that a poor choice of a natural key, or sometimes even the best available choice of a natural key, may not be truly unique, or guaranteed to prevent duplicates. But any choice is better than no choice, as it will at least prevent duplicate rows for the same values in the attributes chosen as the natural key. These issues can be kept to a minimum by the appropriate choice of key attributes, but sometimees they are unavoidable and must be dealt with. But it is still better to do so than to allow incorrect inaccurate or redundant data into the database.
As to "ease of use" If all you are using the natural key for is to constrain the insertion of duplicate rows, and you are using another, surrogate, key as the target for FK constraints, I do not see any ease of use issues of concern.
Wow, you opened a can of worms with this question. Database purists will tell you never to use surrogate keys (like you have above). On the other hand, surrogate keys can have some tremendous benefits. I use them all the time.
In SQL Server, a surrogate key is typically an auto-increment Identity value that SQL Server generates for you. It has NO relationship to the actual data stored in the table. The opposite of this is a Natural key. An example might be Social Security number. This does have a relationship to the data stored in the table. There are benefits to natural keys, but, IMO, the benefits to using surrogate keys outweigh natural keys.
I noticed in your example, you have a GUID for a primary key. You generally want to stay away from GUIDS as primary keys. The are big, bulky and can often be inserted into your database in a random way, causing major fragmentation.
Randy
The reason that database purists get all up in arms about surrogate keys is because, if used improperly, they can allow data duplication, which is one of the evils that good database design is meant to banish.
For instance, suppose that I had a table of email addresses for a mailing list. I would want them to be unique, right? There's no point in having 2, 3, or n entries of the same email address. If I use email_address as my primary key ( which is a natural key -- it exists as data independently of the database structure you've created ), this will guarantee that I will never have a duplicate email address in my mailing list.
However, if I have a field called id as a surrogate key, then I can have any number of duplicate email addresses. This becomes bad if there are then 10 rows of the same email address, all with conflicting subscription information in other columns. Which one is correct, if any? There's no way to tell! After that point, your data integrity is borked. There's no way to fix the data but to go through the records one by one, asking people what subscription information is really correct, etc.
The reason why non-purists want it is because it makes it easy to use standardized code, because you can rely on refering to a single database row with an integer value. If you had a natural key of, say, the set ( client_id, email, category_id ), the programmer is going to hate coding around this instance! It kind of breaks the encapsulation of class-based coding, because it requires the programmer to have deep knowledge of table structure, and a delete method may have different code for each table. Yuck!
So obviously this example is over-simplified, but it illustrates the point.
Users Table
Using a Guid as a primary key for your Users table is perfect.
LogEntry table
Unless you plan to expose your LogEntry data to an external system or merge it with another database, I would simply use an incrementing int rather than a Guid as the primary key. It's easier to work with and will use slightly less space, which could be significant in a huge log stretching several years.
The primary key is whatever you make it. Whatever you define as the primary key is the primary key. Usually its an integer ID field.
The surrogate key is also this ID field. Its a surrogate for the natural key, which defines uniqueness in terms of your application data.
The idea behind having an integer ID as the primary key (even it doesnt really mean anything) is for indexing purposes. You would then probably define a natural key as a unique constraint on your table. This way you get the best of both worlds. Fast indexing with your ID field and each row still maintains its natural uniqueness.
That said, some people swear by just using a natural key.
There are actually three kinds of keys to talk about. The primary key is what is used to uniquely identify every row in a table. The surrogate key is an artificial key that is created with that property. A natural key is a primary key which is derived from the actual real life data.
In some cases the natural key may be unwieldy so a surrogate key may be created to be used as a foreign key, etc. For example, in a log or diary the PK might be the date, time, and the full text of the entry (if it is possible to add two entries at the exact same time). Obviously it would be a bad idea to use all of that every time that you wanted to identify a row, so you might make a "log id". It might be a sequential number (the most common) or it might be the date plus a sequential number (like 20091222001) or it might be something else. Some natural keys may work well as a primary key though, such as vehicle VIN numbers, student ID numbers (if they are not reused), or in the case of joining tables the PKs of the two tables being joined.
This is just an overview of table key selection. There's a lot to consider, although in most shops you'll find that they go with, "add an identity column to every table and that's our primary key". You then get all of the problems that go with that.
In your case I think that a LogEntryID for your log items seems reasonable. Is the ID an FK to the Users table? If not then I might question having both the ID and the LogEntryID in the same table as they are redundant. If it is, then I would change the name to user_id or something similar.

Should I use a unique string as a primary key or should I make it as a separate autoincrement INT? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Surrogate Vs. Natural/Business Keys
When not to use surrogate primary keys?
So, I would prefer having an INT as a primary key with AI. But, here is the reason why I am considering making a unique string as a primary key: I don't have to query related tables to fetch the primary key since I will already know it.
For example:
I have a many to many relation:
Customer - Order - Product
Let's say I want to add a new customer and a new order, and I already know what they bought. I have to do a query on product table to get the INT, but if I have the string (unique) that is a primary key I don't have to do the query (this seems cleaner to me, I am not talking about optimization/run-time-speeds, not at all).
If you are not worried about optimization, the main 2 criteria for primary key are:
Uniqueness
Constanteness (never changes)
E.g. if your problem domain is - and will always be - such that 2 product names are always distinct, AND that no product will ever change its name (think Norton Antivirus -> Symantec Antivirus for a simple example of name change), then you may use the product name as the unique key.
The two MUST be 100% true not only today, but for any foreseeable future lifetime of the database.
Therefore using numeric ID is highly recommended as you may not always be able to forecee such things - and changing the DB structure later on to have a product ID is of course orders of magnitude worse than a minor inconvenience of needing to map and ID from the name in your queries.
If you can guarantee that your VARCHAR field is indeed unique and hopefully stable (not changing), then you can definitely use it as a primary key without any conceptual problems.
The only real reasons against using it as your primary key (or even more importantly: your clustering key in SQL Server) are indeed performance-based. A wider and varying size clustering key is suboptimal in many ways, and affects not just your table and its clustering index, but also all non-clustered indices on that table. But if that's none of your concern, again - you'll be fine with a VARCHAR as your primary key.
Er... both are correct in a way
Your logical model and design will use the unique string. This is the natural key.
The actual implementation may use a numeric auto number column (surrogate key) because of architecture/performance