Questions tagged [primary-key]

A key is a set of attributes that is irreducibly unique and non-nullable within a table.

A key is a set of attributes that is irreducibly unique and non-nullable within a table. Irreducible means that all the attributes of the key are necessary to guarantee uniqueness - remove any one attribute and the uniqueness property would be lost. A key may consist of zero, one or more attributes and a relational table (relation variable) must have at least one key and may have more than one.

When a table has more than one key then by convention one of the keys is designated the primary one (meaning it is the preferred identifier or has some other significance for the database designer or user). The others are called secondary keys or alternate keys.

In relational database design the primary key is frequently the one referenced by foreign keys in other tables. That's not always the case however. In principle a primary key is no different in features or function from a non-primary key. The primary-key tag is therefore appropriate for any discussion about keys in general.

Keys are more formally known as candidate keys or minimal superkeys.

Attributes of a key are called prime attributes. Attributes which are not part of any key are called non-prime.

In SQL, keys are optional on tables. Primary keys are defined in the ISO SQL Standard, through the PRIMARY KEY constraint. The syntax to add such a constraint to an existing table is defined in SQL:2003 like this:

ALTER TABLE <TABLE identifier> 
      ADD [ CONSTRAINT <CONSTRAINT identifier> ] 
      PRIMARY KEY ( <COLUMN expression> {, <COLUMN expression>}... )

The primary key can also be specified directly during table creation. In the SQL Standard, primary keys may consist of one or multiple columns. Each column participating in the primary key is implicitly defined as NOT NULL. Note that some DBMS require explicitly marking primary-key columns as NOT NULL.

CREATE TABLE TABLE_NAME (
    id_col  INT,
    col2    CHARACTER VARYING(20),
    ...
    CONSTRAINT tab_pk PRIMARY KEY(id_col),
    ...
)

If the primary key consists only of a single column, the column can be marked as such using the following syntax:

CREATE TABLE TABLE_NAME (
    id_col  INT  PRIMARY KEY,
    col2    CHARACTER VARYING(20),
    ...
)
4532 questions
39
votes
6 answers

Define a unique primary key based on 2 columns

I would like to define a unique key for records based on 2 columns : 'id' and 'language' to let the user submits the following strings : id=1 language=en value=blabla english id=1 language=fr value=blabla french I tried to use set_primary_key…
Stéphane V
  • 1,094
  • 2
  • 11
  • 25
37
votes
9 answers

Hibernate/persistence without @Id

I have a database view that yields a result set that has no true primary key. I want to use Hibernate/Persistence to map this result set onto Java objects. Of course, because there is no PK, I cannot decorate any field with @Id. When deploying,…
Miguel
37
votes
3 answers

Superkey, candidate key & primary key

Can any kind soul clarify my doubts with a simple example below and identify the superkey, candidate key and primary key? I know there are a lot of posts and websites out there explaining the differences between them. But it looks like all are…
JLearner
  • 1,271
  • 9
  • 27
  • 40
37
votes
18 answers

MySQL duplicate entry error even though there is no duplicate entry

I am using MySQL 5.1.56, MyISAM. My table looks like this: CREATE TABLE IF NOT EXISTS `my_table` ( `number` int(11) NOT NULL, `name` varchar(50) NOT NULL, `money` int(11) NOT NULL, PRIMARY KEY (`number`,`name`) ) ENGINE=MyISAM; It contains…
user1763581
  • 605
  • 1
  • 8
  • 17
37
votes
4 answers

I need to auto_increment a field in MySQL that is not primary key

Right now, I have a table whose primary key is an auto_increment field. However, I need to set the primary key as username, date (to ensure that there cannot be a duplicate username with a date). I need the auto_increment field, however, in order to…
littleK
  • 19,521
  • 30
  • 128
  • 188
36
votes
7 answers

Django BigInteger auto-increment field as primary key?

I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users. By default,…
letoosh
  • 511
  • 2
  • 6
  • 13
36
votes
3 answers

Multi-Column Primary Key in MySQL 5

I'm trying to learn how to use keys and to break the habit of necessarily having SERIAL type IDs for all rows in all my tables. At the same time, I'm also doing many-to-many relationships, and so requiring unique values on either column of the…
Kaji
  • 2,220
  • 6
  • 30
  • 45
36
votes
12 answers

Do link tables need a meaningless primary key field?

I am working on a couple of link tables and I got to thinking (Danger Will Robinson, Danger) what are the possible structures of a link table and what are their pro's and con's. I came up with a few possible strictures for the link…
Tyson of the Northwest
  • 2,086
  • 2
  • 21
  • 34
36
votes
4 answers

newid() vs newsequentialid() What are the differences/pros and cons?

In a database where all of your primary keys are GUIDs, what are the differences/implications and/or pros and cons using newid() versus newsequentialid() as the "default value or binding". The only difference that I know of is that newid() creates a…
7wp
  • 12,505
  • 20
  • 77
  • 103
35
votes
2 answers

Android: Use UUID as primary key in SQLite

My app needs to get synced with other app users (on there own devices). I also want to support offline editing, that are synchronized to the other collaborative users when the user gets connected to the internet. So the User A changes (while he is…
sockeqwe
  • 15,574
  • 24
  • 88
  • 144
35
votes
5 answers

Create view with primary key?

I create a view with following codes SELECT CONVERT(NVARCHAR, YEAR(okuma_tarihi)) + 'T1' AS sno, YEAR(okuma_tarihi) AS Yillar, SUM(toplam_kullanim_T1) AS TotalUsageValue, 'T1' AS UsageType FROM TblSayacOkumalari GROUP BY …
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
34
votes
3 answers

Why is negative id or zero considered a bad practice?

Why is negative id or zero considered a bad practice when inserting a primary key in a database table? I think it could be useful in some cases, but people say that it is not recommended, despite the fact that they never say/know why. So, I was…
34
votes
2 answers

Primary key Ascending vs Descending

In Sql Server, I have a table with an Identity primary key. Often I want the latest few new records, so I grab the Top n sorted by descending the primary key. Should I define the Primary Key index as Descending, or does it make no difference? i.e.…
peterorum
  • 1,401
  • 2
  • 15
  • 21
34
votes
7 answers

Django model instances primary keys do not reset to 1 after all instances are deleted

I have been working on an offline version of my Django web app and have frequently deleted model instances for a certain ModelX. I have done this from the admin page and have experienced no issues. The model only has two fields: name and order and…
pj2452
  • 905
  • 3
  • 10
  • 22
33
votes
5 answers

Can a table have two foreign keys?

I have the following tables (Primary key in bold. Foreign key in Italic) Customer table ID---Name---Balance---Account_Name---Account_Type Account Category table Account_Type----Balance Customer Detail…
Rav
  • 1,163
  • 4
  • 16
  • 18