Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Surrogate key
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Unique identifier for either an entity in the modeled world or an object in the database}} {{More footnotes needed|date=July 2009}} A '''surrogate key''' (or '''synthetic key''', '''pseudokey''', '''entity identifier''', '''factless key''', or '''technical key'''{{citation needed|date=December 2010}}) 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, unlike a [[natural key|''natural'' (or ''business'') key]].<ref>{{Cite web|url=https://www.techopedia.com/definition/22403/surrogate-key|title=What is a Surrogate Key? - Definition from Techopedia|website=Techopedia.com|date=15 June 2017 |language=en|access-date=2020-02-21}}</ref> == Definition == There are at least two definitions of a surrogate: ; Surrogate (1) – Hall, Owlett and Todd (1976): A surrogate represents an ''entity'' in the outside world. The surrogate is internally generated by the system but is nevertheless visible to the user or application.<ref>P A V Hall, J Owlett, S J P Todd, "Relations and Entities", [[Modelling in Data Base Management Systems (ed GM Nijssen)]], North Holland 1976. </ref> ; Surrogate (2) – Wieringa and De Jonge (1991): A surrogate represents an ''object'' in the database itself. The surrogate is internally generated by the system and is invisible to the user or application. The ''Surrogate (1)'' definition relates to a [[data model]] rather than a [[storage model]] and is used throughout this article. See Date (1998). An important distinction between a surrogate and a primary key depends on whether the database is a [[current database]] or a [[temporal database]]. Since a ''current database'' stores only ''currently'' valid data, there is a one-to-one correspondence between a surrogate in the modeled world and the primary key of the database. In this case the surrogate may be used as a primary key, resulting in the term ''surrogate key''. In a temporal database, however, there is a many-to-one relationship between primary keys and the surrogate. Since there may be several objects in the database corresponding to a single surrogate, we cannot use the surrogate as a primary key; another attribute is required, in addition to the surrogate, to uniquely identify each object. Although Hall ''et al.'' (1976) say nothing about this, others{{specify|date=December 2010}} have argued that a surrogate should have the following characteristics: * the value is never reused * the value is system generated * the value is not manipulable by the user or application * the value contains no semantic meaning * the value is not visible to the user or application * the value is not composed of several values from different domains. == Surrogates in practice == In a [[current database]], the surrogate key can be the [[primary key]], generated by the [[database management system]] and ''not'' derived from any application data in the database. The only significance of the surrogate key is to act as the primary key. It is also possible that the surrogate key exists in addition to the database-generated [[Universally unique identifier|UUID]] (for example, an HR number for each employee other than the UUID of each employee). A surrogate key is frequently a sequential number (e.g. a [[Adaptive Server Enterprise|Sybase]] or [[Microsoft SQL Server|SQL Server]] "identity column", a [[PostgreSQL]] or [[Informix]] <code>serial</code>, an [[Oracle Corporation|Oracle]] or SQL Server <code>SEQUENCE</code> or a column defined with <code>AUTO_INCREMENT</code> in [[MySQL]]). Some databases provide [[UUID]]/[[GUID]] as a possible data type for surrogate keys (e.g. PostgreSQL <code>UUID</code><ref>{{cite web | url=http://www.postgresql.org/docs/current/static/datatype-uuid.html | title=8.12. UUID Type | date=9 May 2024 }}</ref> or SQL Server <code>UNIQUEIDENTIFIER</code><ref>{{cite web | url=http://msdn.microsoft.com/en-us/library/ms187942.aspx | title=Uniqueidentifier (Transact-SQL) - SQL Server | date=23 May 2023 }}</ref>). Having the key independent of all other columns insulates the database relationships from changes in data values or database design<ref>{{FOLDOC|Surrogate+key}}</ref> (making the database more [[agile software development|agile]]) and guarantees uniqueness. In a [[temporal database]], it is necessary to distinguish between the surrogate key and the [[natural key|business key]]. Every row would have both a business key and a surrogate key. The surrogate key identifies one unique row in the database, the business key identifies one unique entity of the modeled world. One table row represents a slice of time holding all the entity's attributes for a defined timespan. Those slices depict the whole lifespan of one business entity. For example, a table ''EmployeeContracts'' may hold temporal information to keep track of contracted working hours. The business key for one contract will be identical (non-unique) in both rows however the surrogate key for each row is unique. {| class="wikitable" |- ! SurrogateKey !! BusinessKey !! EmployeeName !! WorkingHoursPerWeek !! RowValidFrom !! RowValidTo |- | 1 || BOS0120 || John Smith || 40 || 2000-01-01 || 2000-12-31 |- | 56 || P0000123 || Bob Brown || 25 || 1999-01-01 || 2011-12-31 |- | 234 || BOS0120 || John Smith || 35 || 2001-01-01 || 2009-12-31 |} Some database designers use surrogate keys systematically regardless of the suitability of other [[candidate key]]s, while others will use a key already present in the data, if there is one. Some of the alternate names ("system-generated key") describe the way of ''generating'' new surrogate values rather than the ''nature'' of the surrogate concept. Approaches to generating surrogates include: * [[Universally Unique Identifier]]s (UUIDs) * [[Globally Unique Identifier]]s (GUIDs) * [[Object identifier|Object Identifier]]s (OIDs) * [[Adaptive Server Enterprise|Sybase]] or SQL Server identity column <code>IDENTITY</code> OR <code>IDENTITY(n,n)</code> * [[Oracle Corporation|Oracle]] <code>SEQUENCE</code>, or <code>GENERATED AS IDENTITY</code> (starting from version 12.1)<ref>{{Cite web|url=http://docs.oracle.com/database/121/SQLRF/statements_7002.htm#SQLRF01402|title=Database SQL Language Reference}}</ref> * SQL Server <code>SEQUENCE</code> (starting from SQL Server 2012)<ref>{{cite web | url=https://msdn.microsoft.com/en-us/library/ff878091.aspx | title=CREATE SEQUENCE (Transact-SQL) - SQL Server | date=29 December 2022 }}</ref> * [[PostgreSQL]] or [[IBM Informix]] serial * MySQL <code>AUTO_INCREMENT</code> * [[SQLite]] <code>INTEGER PRIMARY KEY</code> (if <code>AUTOINCREMENT</code> is used it will prevent the reuse of numbers that have already been used but are available)<ref>{{cite web |url=https://sqlite.org/autoinc.html |title=SQLite Autoincrement |author=<!--Not stated--> |date=2017-02-02 |website=SQLite |publisher= |access-date=2022-12-02 |quote=}}</ref> * AutoNumber data type in [[Microsoft Access]] * <code>AS IDENTITY GENERATED BY DEFAULT</code> in [[IBM Db2]] and [[PostgreSQL]]. * Identity column (implemented in [[Data definition language|DDL]]) in [[Teradata]] * Table Sequence when the sequence is calculated by a procedure and a sequence table with fields: id, sequenceName, sequenceValue and incrementValue ==Advantages== ===Stability=== Surrogate keys typically do not change while the row exists. This has the following advantages: * Applications cannot lose their reference to a row in the database (since the identifier does not change). * The primary or natural key data can always be modified, even with databases that do not support cascading updates across related [[foreign key]]s. ===Requirement changes=== Attributes that uniquely identify an entity might change, which might invalidate the suitability of natural keys. Consider the following example: :An employee's network user name is chosen as a natural key. Upon merging with another company, new employees must be inserted. Some of the new network user names create conflicts because their user names were generated independently (when the companies were separate). In these cases, generally a new attribute must be added to the natural key (for example, an ''original_company'' column). With a surrogate key, only the table that defines the surrogate key must be changed. With natural keys, all tables (and possibly other, related software) that use the natural key will have to change. Some problem domains do not clearly identify a suitable natural key. Surrogate keys avoid choosing a natural key that might be incorrect. ===Performance=== Surrogate keys tend to be a compact data type, such as a four-byte integer. This allows the database to query the single key column faster than it could multiple columns (which are often text - which is slower still). Furthermore, a non-redundant distribution of keys causes the resulting [[b-tree]] index to be completely balanced. Surrogate keys are also less expensive to join (fewer columns to compare) than [[compound key]]. ===Compatibility=== While using several database application development systems, drivers, and [[object–relational mapping]] systems, such as [[Ruby on Rails]] or [[Hibernate (Java)|Hibernate]], it is much easier to use an integer or GUID surrogate keys for every table instead of natural keys in order to support database-system-agnostic operations and object-to-row mapping. ===Uniformity=== When every table has a uniform surrogate key, some tasks can be easily automated by writing the code in a table-independent way. ===Validation=== It is possible to design key-values that follow a well-known pattern or structure which can be automatically verified. For instance, the keys that are intended to be used in some column of some table might be designed to "look differently from" those that are intended to be used in another column or table, thereby simplifying the detection of application errors in which the keys have been misplaced. However, this characteristic of the surrogate keys should never be used to drive any of the logic of the applications themselves, as this would violate the principles of [[database normalization]]. ===Simplicity of Relationships=== Surrogate keys simplify the creation of foreign key relationships because they only require a single column (as opposed to composite keys - which require multiple columns). When creating a query on the database, forgetting to include all the columns in a composite foreign key when joining tables can lead to unexpected results in the form of an undesired [[cartesian product]]. ==Disadvantages== ===Disassociation=== The values of generated surrogate keys have no relationship to the real-world ''meaning'' of the data held in a row. When inspecting a row holding a foreign key reference to another table using a surrogate key, the meaning of the surrogate key's row cannot be discerned from the key itself. Every foreign key must be joined to see the related data item. If appropriate database constraints have not been set, or data imported from a legacy system where [[referential integrity]] was not employed, it is possible to have a foreign-key value that does not correspond to a primary-key value and is therefore invalid. (In this regard, [[C.J. Date]] regards the meaninglessness of surrogate keys as an advantage.<ref>C.J. Date. The primacy of primary keys. From "Relational Database Writings, 1991-1994. Addison-Wesley, Reading, MA.</ref>) To discover such errors, one must perform a query that uses a left [[outer join]] between the table with the foreign key and the table with the primary key, showing both key fields in addition to any fields required to distinguish the record; all invalid foreign-key values will have the primary-key column as NULL. The need to perform such a check is so common that Microsoft Access actually provides a "Find Unmatched Query" wizard that generates the appropriate SQL after walking the user through a dialog. (It is, however, not too difficult to compose such queries manually.) "Find Unmatched" queries are typically employed as part of a [[data cleansing]] process when inheriting legacy data. Surrogate keys are unnatural for data that is exported and shared. A particular difficulty is that tables from two otherwise identical schemas (for example, a test schema and a development schema) can hold records that are equivalent in a business sense, but have different keys. This can be mitigated by not exporting surrogate keys, except as transient data (most obviously, in executing applications that have a "live" connection to the database). When surrogate keys supplant natural keys, then domain specific [[referential integrity]] will be compromised. For example, in a customer master table, the same customer may have multiple records under separate customer IDs, even though the natural key (a combination of customer name, date of birth, and e-mail address) would be unique. To prevent compromise, the natural key of the table must not be supplanted: it must be preserved as a [[unique constraint]], which is implemented as a unique index on the combination of natural-key fields. ===Query optimization=== Relational databases assume a unique [[Index (database)|index]] is applied to a table's primary key. The unique index serves two purposes: (i) to enforce entity integrity, since primary key data must be unique across rows and (ii) to quickly search for rows when queried. Since surrogate keys replace a table's identifying attributes—the [[natural key]]—and since the identifying attributes are likely to be those queried, then the query optimizer is forced to perform a full table scan when fulfilling likely queries. The remedy to the full table scan is to apply indexes on the identifying attributes, or sets of them. Where such sets are themselves a [[candidate key]], the index can be a unique index. These additional indexes, however, will take up disk space and slow down inserts and deletes. ===Normalization=== Surrogate keys can result in duplicate values in any [[natural key]]s. To prevent duplication, one must preserve the role of the natural keys as unique constraints when defining the table using either SQL's <code>CREATE TABLE</code> statement or <code>ALTER TABLE ... ADD CONSTRAINT</code> statement, if the constraints are added as an afterthought. ===Business process modeling=== Because surrogate keys are unnatural, flaws can appear when modeling the business requirements. Business requirements, relying on the natural key, then need to be translated to the surrogate key. A strategy is to draw a clear distinction between the logical model (in which surrogate keys do not appear) and the physical implementation of that model, to ensure that the logical model is correct and reasonably well normalised, and to ensure that the physical model is a correct implementation of the logical model. ===Inadvertent disclosure=== Proprietary information can be leaked if surrogate keys are generated sequentially. By subtracting a previously generated sequential key from a recently generated sequential key, one could learn the number of rows inserted during that time period. This could expose, for example, the number of transactions or new accounts per period. For example see [[German tank problem]]. There are a few ways to overcome this problem: * increase the sequential number by a random amount; * generate a random key such as a [[Universally unique identifier|UUID]]. ===Inadvertent assumptions=== Sequentially generated surrogate keys can imply that events with a higher key value occurred after events with a lower value. This is not necessarily true, because such values do not guarantee time sequence as it is possible for inserts to fail and leave gaps which may be filled at a later time. If chronology is important then date and time must be separately recorded. ==See also== * [[Natural key]] * [[Object identifier]] * [[Persistent object identifier]] == References == === Citations === {{Reflist}} === Sources === {{Refbegin}} * {{cite book | last = Nijssen | first = G.M. | title = Modelling in Data Base Management Systems | publisher = North-Holland Pub. Co. | year = 1976 | isbn = 0-7204-0459-2 }} * Engles, R.W.: (1972), ''A Tutorial on Data-Base Organization'', Annual Review in Automatic Programming, Vol.7, Part 1, Pergamon Press, Oxford, pp. 1–64. * [[Börje Langefors|Langefors, B]] (1968). ''Elementary Files and Elementary File Records'', Proceedings of File 68, an IFIP/IAG International Seminar on File Organisation, Amsterdam, November, pp. 89–96. * {{cite tech report | citeseerx=10.1.1.16.3195 | title = The identification of objects and roles - Object identifiers revisited | first1 = Roel | last1 = Wieringa | first2 = Wiebren | last2 = de Jonge | year = 1991 | publisher = Faculty of Mathematics and Computer Science, Vrije Universiteit | publication-place = Amsterdam | series = Technical Report / Faculty of Mathematics and Computer Science | volume = IR-267 | url = https://ris.utwente.nl/ws/portalfiles/portal/5125559/Wieringa_De_Jonge_-_The_identification_of_objects_and_roles%3B_object_identifiers_revisited.pdf | format = PDF | access-date = 2022-12-02 }} * {{cite book |isbn = 0201398141 | title = Relational Database Writings 1994–1997 | first = C. J. | last = Date | year = 1998 | chapter = Chapters 11 and 12 | publisher = Addison-Wesley }} * {{cite web | last = Carter | first = Breck | title = Intelligent Versus Surrogate Keys | url = http://www.bcarter.com/intsurr1.htm | access-date = 2006-12-03 }} * {{cite web |last = Richardson |first = Lee |title = Create Data Disaster: Avoid Unique Indexes – (Mistake 3 of 10) |url = http://www.nearinfinity.com/blogs/page/lrichard?entry=create_data_disaster_avoid_unique |access-date = 2008-01-19 |url-status = dead |archive-url = https://web.archive.org/web/20080130152547/http://www.nearinfinity.com/blogs/page/lrichard?entry=create_data_disaster_avoid_unique |archive-date = 2008-01-30 }} * {{cite web | last = Berkus | first = Josh | title = Database Soup: Primary Keyvil, Part I | url = http://it.toolbox.com/blogs/database-soup/primary-keyvil-part-i-7327 | access-date = 2006-12-03 }} {{Refend}} {{Clear}} {{Databases}} {{DEFAULTSORT:Surrogate Key}} [[Category:Data modeling]] [[Category:Database management systems]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Citation needed
(
edit
)
Template:Cite book
(
edit
)
Template:Cite tech report
(
edit
)
Template:Cite web
(
edit
)
Template:Clear
(
edit
)
Template:Databases
(
edit
)
Template:FOLDOC
(
edit
)
Template:More footnotes needed
(
edit
)
Template:Refbegin
(
edit
)
Template:Refend
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)
Template:Specify
(
edit
)
Template:Talk other
(
edit
)