Unique key

In relational database management systems, a unique key is a candidate key. All the candidate keys of a relation can uniquely identify the records of the relation, but only one of them is used as the primary key of the relation. The remaining candidate keys are called unique keys because they can uniquely identify a record in a relation. Unique keys can consist of multiple columns. Unique keys are also called alternate keys. Unique keys are an alternative to the primary key of the relation. In SQL, the unique keys have a UNIQUE constraint assigned to them in order to prevent duplicates (a duplicate entry is not valid in a unique column). Alternate keys may be used like the primary key when doing a single-table select or when filtering in a where clause, but are not typically used to join multiple tables.

Summary

Keys provide the means for database users and application software to identify, access and update information in a database table. There may be several keys in any given table. For example, in a table of employees, both employee number and login name are individually unique. The enforcement of a key constraint (i.e. a uniqueness constraint) in a table is also a data integrity feature of the database. The DBMS prevents updates that would cause duplicate key values and thereby ensures that tables always comply with the desired rules for uniqueness. Proper selection of keys when designing a database is therefore an important aspect of database integrity.

A relational database table may have one or more available unique keys (formally called candidate keys). One of those keys per table may be designated the primary key; other keys are called alternate keys.

Any key may consist of one or more attributes. For example, a Social Security Number might be a single attribute key for an employee; a combination of flight number and date might be a key consisting of two attributes for a scheduled flight.

There are several types of keys used in database modeling and implementations.

Key Name Definition
Simple A key made from only one attribute.
Concatenated A key made from more than one attribute joined together as a single key, such as part or whole name with a system generated number appended as often used for E-mail addresses.
Compound A key made from at least two attributes or simple keys, only simple keys exist in a compound key.
Composite Like a compound key, but the individual attributes need not be simple keys.
Natural A key made from data that exists outside the current database. In other words, the data is not system generated, such as a social security number imported from another system.
Surrogate An artificial key made from data that is system assigned or generated when another candidate key exists. Surrogate keys are usually numeric ID values and often used for performance reasons.[citation needed]
Candidate A key that may become the primary key.
Primary The key that is selected as the primary key. Only one key within an entity is selected to be the primary key. This is the key that is allowed to migrate to other entities to define the relationships that exist among the entities. When the data model is instantiated into a physical database, it is the key that the system uses the most when accessing the table, or joining the tables together when selecting data.
Alternate A non-primary key that can be used to identify only one row in a table. Alternate keys may be used like a primary key in a single-table select.
Foreign A key that has migrated to another entity.

At the most basic definition, "a key is a unique identifier",[1] so unique key is a pleonasm. Keys that are within their originating entity are unique within that entity. Keys that migrate to another entity may or may not be unique, depending on the design and how they are used in the other table. Foreign keys may be the primary key in another table; for example a PersonID may become the EmployeeID in the Employee table. In this case, the EmployeeID is both a foreign key and the unique primary key, meaning that the tables have a 1:1 relationship. In the case where the person entity contained the biological father ID, the father ID would not be expected to be unique because a father may have more than one child.

Here is an example of a primary key becoming a foreign key on a related table. ID migrates from the Author table to the Book table.

Author Table Schema:

Author(ID, Name, Address, Born)

Book Table Schema:

Book(ISBN, AuthorID, Title, Publisher, Price)

Here ID serves as the primary key in the table 'Author', but also as AuthorID serves as a Foreign Key in the table 'Book'. The Foreign Key serves as the link, and therefore the connection, between the two related tables in this sample database.

In a relational database, a candidate key uniquely identifies each row of data values in a database table. A candidate key comprises a single column or a set of columns in a single database table. No two distinct rows or data records in a database table can have the same data value (or combination of data values) in those candidate key columns since NULL values are not used. Depending on its design, a database table may have many candidate keys but at most one candidate key may be distinguished as the primary key.

A key constraint applies to the set of tuples in a table at any given point in time. A key is not necessarily a unique identifier across the population of all possible instances of tuples that could be stored in a table but it does imply a data integrity rule that duplicates should not be allowed in the database table. Some possible examples of keys are Social Security Numbers, ISBNs, vehicle registration numbers or user login names.

In principle any key may be referenced by foreign keys. Some SQL DBMSs only allow a foreign key constraint against a primary key but most systems will allow a foreign key constraint to reference any key of a table.

Defining keys in SQL

The definition of keys in SQL:

  ALTER TABLE <table identifier> 
      ADD [ CONSTRAINT <constraint identifier> ] 
      { PRIMARY KEY | UNIQUE } ( <column name> [ {, <column name>}... ] )

Likewise, keys can be defined as part of the CREATE TABLE SQL statement.

  CREATE TABLE table_name (
     id_col   INT,
     col2     CHARACTER VARYING(20),
     key_col  SMALLINT NOT NULL,
     ...
     CONSTRAINT key_unique UNIQUE(key_col),
     ...
  )
  CREATE TABLE table_name (
     id_col  INT  PRIMARY KEY,
     col2    CHARACTER VARYING(20),
     ...
     key_col  SMALLINT NOT NULL UNIQUE,
     ...
  )

Differences between primary key constraint and unique constraint

Primary key constraint

  1. A primary key cannot allow null (a primary key cannot be defined on columns that allow nulls).
  2. Each table cannot have more than one primary key.
  3. On some RDBMS a primary key generates a clustered index by default.

Unique constraint

  1. A unique constraint can be defined on columns that allow nulls, in which case rows that include nulls may not actually be unique across the set of columns defined by the constraint.
  2. Each table can have multiple unique constraints.
  3. On some RDBMS a unique constraint generates a nonclustered index by default.

Note that unlike the PRIMARY KEY constraint a UNIQUE constraint does not imply NOT NULL for the columns participating in the constraint. NOT NULL must be specified to make the column(s) a key. It is possible to put UNIQUE constraints on nullable columns but the SQL standard states that the constraint does not guarantee uniqueness of nullable columns (uniqueness is not enforced for rows where any of the columns contains a null).

According to the SQL[2] standard a unique constraint does not enforce uniqueness in the presence of nulls and can therefore contain several rows with identical combinations of nulls and non-null values — however not all RDBMS implement this feature according to the SQL standard.[3][4]

See also

References

  1. ^ Awad, Elias (1985), Systems Analysis and Design, Second Edition, Richard D. Irwin, Inc., ISBN 0-256-02824-9
  2. ^ Summary of ANSI/ISO/IEC SQL Archived April 25, 2012, at the Wayback Machine
  3. ^ "Constraints - SQL Database Reference Material - Learn sql, read an sql manual, follow an sql tutorial, or learn how to structure an SQL query!". www.sql.org. Retrieved 16 August 2018.
  4. ^ "Comparison of different SQL implementations". troels.arvin.dk. Retrieved 16 August 2018.

Read other articles:

Aung Yay ChanNama asalbahasa Burma: အောင်ရေချမ်းLahirAung Yay Chan7 Juli 1991 (umur 32)Yangon, MyanmarKebangsaanBurmaAlmamaterUniversitas Pendidikan Jarak Jauh, YangonPekerjaanPemeran, peraga busanaTahun aktif2010–kiniTinggi5 ft 9 in (1,75 m)Suami/istriKhine Mar Win ​(m. 2024)​ Aung Yay Chan (bahasa Burma: အောင်ရေချမ်း; lahir 7 Juli 1991) adalah seorang pemeran film dan televi...

 

Doctor Neo Cortex. Doctor Neo Cortex, sering disingkat N. Cortex, Doctor Cortex, atau hanya Cortex, adalah karakter permainan video dan antagonis serial Crash Bandicoot. Ia secara langsung muncul di semua permainan Crash Bandicoot kecuali Crash Bandicoot 2: N-Tranced untuk Game Boy Advance. Ia merupakan ilmuwan gila dengan tanda 'N' besar di kepalanya. Pranala luar Wikiquote memiliki koleksi kutipan yang berkaitan dengan: Doctor Neo Cortex. Crash Mania's Crash-O-Pedia article on Doctor Neo Co...

 

Questa voce sull'argomento centri abitati della Georgia (Stati Uniti d'America) è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. NewnancomuneNewnan, Georgia Newnan – Veduta LocalizzazioneStato Stati Uniti Stato federato Georgia ConteaCoweta TerritorioCoordinate33°22′27.36″N 84°47′51.81″W / 33.374266°N 84.797725°W33.374266; -84.797725 (Newnan)Coordinate: 33°22�...

Radio station in Garland, TexasKAAMGarland, TexasBroadcast areaDallas/Fort Worth MetroplexFrequency770 kHzProgrammingLanguage(s)EnglishFormatChristian Talk/BrokeredOwnershipOwnerDonald B. Crawford, Jr.(DJRD Broadcasting, LLC)HistoryFirst air date1990 (as KPBC)Former call signsKPBC (1990-1999)Call sign meaningKeep Absolutely Awesome Music[1] (Oldies/Standards era)Technical informationFacility ID17303ClassBPower10,000 watts (day)1,000 watts (Night)Transmitter coordinates33°1′58″N ...

 

الفطريات الجذرية أو الجذريات الفطرية أو الفطريات التكافلية (باللاتينية: mycorrhiza) (جمع : mycorrhizae أو mycorrhizas) هي عبارة عن اتحاد تكافلي بين فطر ونبات.[1][2][3] يحدث هذا التعايش في مستوى جذور النباتات، حيث تمتد الخيطان الفطرية hyphae من الأفطورة mycelium الفطرية لتستعمر جذور ال...

 

Edward JenksFBABorn(1861-02-20)20 February 1861Lambeth, LondonDied10 November 1939(1939-11-10) (aged 78)Bishop's Tawton, DevonshireNationalityBritishCitizenshipUnited KingdomAwards1889  Thirlwall PrizeAcademic backgroundEducationKing's College, Cambridge (BA, LLB)Academic workDisciplineJurisprudenceInstitutionsJesus College, CambridgeUniversity of MelbourneUniversity College, LiverpoolVictoria University of ManchesterUniversity of OxfordUniversity of LondonLondon School of Eco...

Osas Saha Osas Saha bersama TIRA-PersikaboInformasi pribadiNama lengkap Osas Marvellous IkpefuaTanggal lahir 23 Oktober 1986 (umur 37)Tempat lahir Lagos, NigeriaTinggi 1,80 m (5 ft 11 in)Posisi bermain PenyerangInformasi klubKlub saat ini Persita TangerangNomor 8Karier senior*Tahun Tim Tampil (Gol)2003–2004 Chykes Davies 18 (7)2005–2007 Prime 27 (12)2007–2008 PSDS Deli Serdang 37 (18)2008 KRC Mechelen 18 (7)2008-2009 KS Elbasani 19 (7)2009–2010 PSMS Medan 15 (4)20...

 

British actor (1923–2014) The Right HonourableThe Lord AttenboroughCBE FRSAAttenborough in 1975BornRichard Samuel Attenborough(1923-08-29)29 August 1923Cambridge, EnglandDied24 August 2014(2014-08-24) (aged 90)Northwood, London, EnglandResting placeSt Mary Magdalene, Richmond, LondonOccupationsActorfilm directorproducerPolitical partyLabourSpouse Sheila Sim ​(m. 1945)​ChildrenMichaelJaneCharlotteParentFrederick Attenborough (father)Relatives David ...

 

この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)出典検索?: コルク – ニュース · 書籍 · スカラー · CiNii · J-STAGE · NDL · dlib.jp · ジャパンサーチ · TWL(2017年4月) コルクを打ち抜いて作った瓶の栓 コルク(木栓、�...

National beauty pageant competition in Ecuador Organización Miss EcuadorLogo of Organización Miss EcuadorFormation1955; 69 years ago (1955)TypeBeauty pageantHeadquartersGuayaquilLocationEcuadorMembership Miss UniverseMiss InternationalReina HispanoamericanaOfficial language SpanishPresidentMaría del Carmen de Aguayo[1]Key peopleMarco TapiaWebsitewww.missecuador.tv Miss Ecuador is a national beauty pageant in Ecuador. The current Miss Ecuador is Delary Stoffers fro...

 

Joseph-Benoît Cottolengo Peinture d'Agostino Cottolengo (v. 1850). Saint, prêtre, fondateur Naissance 3 mai 1786,Bra, Piémont, royaume de Sardaigne Décès 30 avril 1842  (55 ans) Chieri, royaume de Sardaigne Nationalité Italien Ordre religieux Ordre des Frères mineurs de saint François Vénéré à Petite Maison de la Divine Providence à Turin Béatification 28 avril 1917par Benoît XV Canonisation 19 mars 1934par Pie XI Vénéré par Église catholique romaine Fête 30 avril mo...

 

Este artículo o sección necesita referencias que aparezcan en una publicación acreditada. Busca fuentes: «William Le Lacheur» – noticias · libros · académico · imágenesEste aviso fue puesto el 12 de febrero de 2017. William Le Lacheur Óleo de William Le Lacheur hacia 1850. Museo de Guernsey.Información personalNombre de nacimiento Guillaume Le LacheurNacimiento 15 de octubre de 1802 Guernsey, Islas del CanalFallecimiento 27 de junio de 1863 Londres, Reino Uni...

العلاقات النمساوية البليزية النمسا بليز   النمسا   بليز تعديل مصدري - تعديل   العلاقات النمساوية البليزية هي العلاقات الثنائية التي تجمع بين النمسا وبليز.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين: وجه المقارنة النمسا ب...

 

Gallium(III) trioxide β-Ga2O3 crystal Crystal structure of β-Ga2O3 Names Other names gallium trioxide, gallium sesquioxide Identifiers CAS Number 12024-21-4 Y 3D model (JSmol) Interactive image ChemSpider 139522 Y ECHA InfoCard 100.031.525 EC Number 234-691-7 PubChem CID 5139834 RTECS number LW9650000 UNII 46F059V66A Y CompTox Dashboard (EPA) DTXSID9031359 InChI InChI=1S/2Ga.3O YKey: QZQVBEXLDFYHSR-UHFFFAOYSA-N YInChI=1/2Ga.3O/rGa2O3/c3-1-5-2-4Key: QZQVBE...

 

Provincial park in Ontario, Canada Otoskwin–Attawapiskat River Provincial ParkIUCN category II (national park)LocationKenora District, Ontario, CanadaCoordinates52°10′17″N 87°35′02″W / 52.17139°N 87.58389°W / 52.17139; -87.58389[1]Length420 km (260 mi)Area82,529.00 ha (318.6463 sq mi)[2]DesignationWaterwayEstablished1989Named forOtoskwin and Attawapiskat RiversGoverning bodyOntario Parkswww.ontarioparks.com/pa...

Boundary of the Antarctic Map of the Antarctic with the Antarctic Circle in blue. The Antarctic Circle is the most southerly of the five major circles of latitude that mark maps of Earth. The region south of this circle is known as the Antarctic, and the zone immediately to the north is called the Southern Temperate Zone. South of the Antarctic Circle, the Sun is above the horizon for 24 continuous hours at least once per year (and therefore visible at midnight) and the centre of the Sun (ign...

 

Prince William Sound, di pantai selatan Alaska. Prince William Sound adalah sound (bagian perairan pedalaman yang lebih besar dan dalam dari teluk dan fyord) yang berada lepas Teluk Alaska, Amerika Serikat. Prince William Sound berada di sisi timur Semenanjung Kenai. Pelabuhan terbesarnya adalah Valdez, di ujung selatan Sistem Jalur Pipa Trans-Alaska. Permukiman lain di sana, yang memiliki sejumlah pulau kecil, antara lain Cordova dan Whittier serta desa asli Alaska bernama Chenega dan Tatitl...

 

Personal computer company, founded 1975 Processor Technology Corporation6200 Hollis Street in Emeryville, California, site of Processor Technology Corporation's former headquartersIndustryComputerFoundedApril 1975; 49 years ago (1975-04) in Berkeley, CaliforniaFounderGary IngramBob MarshDefunctMay 1979; 45 years ago (1979-05)FateDissolved Processor Technology Corporation was a personal computer company founded in April 1975, by Gary Ingram and Bob...

North-south avenue in Manhattan, New York For other uses, see Fifth Avenue (disambiguation). Fifth AvenueMuseum MileFifth Avenue spanning Museum Mile on the Upper East Side of ManhattanOwnerCity of New YorkMaintained byNYCDOTLength6.197 mi (9.973 km)[1][2]LocationManhattan, New York CitySouth endWashington Square North in Greenwich VillageMajorjunctionsMadison Square in FlatironGrand Army Plaza in MidtownDuke Ellington Circle in East HarlemMarcus Garvey Park in ...

 

Bw Schulterklappen, DienstanzugLeutnantUnteroffizierSoldat Eine Schulterklappe (in Österreich: Achselspange; in Deutschland bis 1920 amtlich Achselklappe) ist eine auf den Schultern von Uniformen angebrachte Tuchlasche, die im Allgemeinen in der Ärmelnaht festgenäht ist und an der Halsseite mit einem Knopf befestigt wird. Schulterklappen dien(t)en zur Fixierung des Bandeliers sowie zur Anbringung von Rangabzeichen, Truppenteilmarkierung und Sonderverwendungs-Kennzeichen, wie zum Beispiel d...