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
125
votes
9 answers

Why use multiple columns as primary keys (composite primary key)

This example is taken from w3schools. CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY…
117
votes
6 answers

Using a UUID as a primary key in Django models (generic relations impact)

For a number of reasons^, I'd like to use a UUID as a primary key in some of my Django models. If I do so, will I still be able to use outside apps like "contrib.comments", "django-voting" or "django-tagging" which use generic relations via…
mitchf
  • 3,697
  • 4
  • 26
  • 29
116
votes
11 answers

sql primary key and index

Say I have an ID row (int) in a database set as the primary key. If I query off the ID often do I also need to index it? Or does it being a primary key mean it's already indexed? Reason I ask is because in MS SQL Server I can create an index on this…
danifo
  • 1,635
  • 3
  • 13
  • 12
108
votes
6 answers

Reset PostgreSQL primary key to 1

Is there a way to reset the primary key of a PostgreSQL table to start at 1 again on a populated table? Right now it's generating numbers from 1000000 and up. I want it all to reset and start to 1, keeping all my existing data intact.
David
  • 4,235
  • 12
  • 44
  • 52
106
votes
7 answers

Foreign key referring to primary keys across multiple tables?

I have to two tables namely employees_ce and employees_sn under the database employees. They both have their respective unique primary key columns. I have another table called deductions, whose foreign key column I want to reference to primary…
None
106
votes
8 answers

How to retrieve the last autoincremented ID from a SQLite table?

I have a table Messages with columns ID (primary key, autoincrement) and Content (text). I have a table Users with columns username (primary key, text) and Hash. A message is sent by one Sender (user) to many recipients (user) and a recipient (user)…
Dabblernl
  • 15,831
  • 18
  • 96
  • 148
101
votes
5 answers

Why does select SCOPE_IDENTITY() return a decimal instead of an integer?

So I have a table with an identity column as the primary key, so it is an integer. So, why does SCOPE_IDENTITY() always return a decimal value instead of an int to my C# application? This is really annoying since decimal values will not implicitly…
Earlz
  • 62,085
  • 98
  • 303
  • 499
101
votes
14 answers

How to get primary key of table?

Is there a way to get the name of primary key field from mysql-database? For example: I have a table like this: id name 1 Foo1 2 Foo2 3 Foo3 Where the field id is primary key (it has auto increment but I can't use that). How can I…
Martti Laine
  • 12,655
  • 22
  • 68
  • 102
97
votes
26 answers

How do you like your primary keys?

In a fairly animated discussion in my team I was made to think what most people like as primary keys. We had the following groups- Int/ BigInt which autoincrement are good enough primary keys. There should be at least 3 columns that make up the…
96
votes
7 answers

Can a foreign key refer to a primary key in the same table?

I just think that the answer is false because the foreign key doesn't have uniqueness property. But some people said that it can be in case of self joining the table. I am new to SQL. If its true please explain how and why? Employee table | e_id |…
AmanS
  • 1,490
  • 2
  • 13
  • 22
93
votes
13 answers

ADO.NET Entity Framework: Update Wizard will not add tables

I added a new ADO.Net Entity Data Model into my project and used the Update Wizard to add tables into the model. Five of the selected tables were added to the design surface. Two other tables will not add. I select them in the wizard and click…
92
votes
18 answers

Auto Increment after delete in MySQL

I have a MySQL table with a primary key field that has AUTO_INCREMENT on. After reading other posts on here I've noticed people with the same problem and with varied answers. Some recommend not using this feature, others state it can't be 'fixed'. I…
OmidTahouri
  • 1,312
  • 2
  • 13
  • 19
88
votes
14 answers

Using Rails, how can I set my primary key to not be an integer-typed column?

I'm using Rails migrations to manage a database schema, and I'm creating a simple table where I'd like to use a non-integer value as the primary key (in particular, a string). To abstract away from my problem, let's say there's a table employees…
Rudd Zwolinski
  • 26,712
  • 17
  • 57
  • 60
81
votes
4 answers

Can I use VARCHAR as the PRIMARY KEY?

I have a table for storing coupons/discounts, and I want to use the coupon_code column as the primary key, which is a VARCHAR. My rationale is that, each coupon will have a unique code, and the only commands I will be running are SELECT ... FROM ...…
Mike Brady
  • 843
  • 1
  • 6
  • 6
77
votes
3 answers

Primary key for multiple columns in PostgreSQL?

How to provide primary key for multiple column in a single table using PostgreSQL? Example: Create table "Test" ( "SlNo" int not null primary key, "EmpID" int not null, /* Want to become primary key */ "Empname" varchar(50) null, …