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
1
vote
1 answer

INSERT + SELECT data type mismatch on similar fields

I'm running the following SQLite workaround to add a primary key to a table that did not have one. I am getting a datatype mismatch on INSERT INTO cities SELECT id, name FROM old_cities; However, the fields have exactly the same type. Is it…
onlyf
  • 767
  • 3
  • 19
  • 39
1
vote
2 answers

Determing correct key values for multiple MySQL tables

I am trying to determine how the tables need to be linked in which ways. The employees tables is directly linked to a number of tables which provide more information. A few of those tables have even more details. Employees have a unique employeeid…
Astron
  • 1,211
  • 5
  • 20
  • 42
1
vote
0 answers

Calculating a field value based on PK in Django

Goal: Set customer_number to a calculated value of b_country + id + 10000. models.py class Customer(models.Model): id = models.BigAutoField(primary_key=True) customer_number = models.CharField("Customer #", max_length=10, default=0) …
Aiden
  • 309
  • 2
  • 16
1
vote
2 answers

How to modify a primary key index to become serial?

I have a table that has a primary key which I'd like to become SERIAL (auto increment). How to do that? => select * from information_schema.table_constraints where table_name='role'; constraint_catalog | constraint_schema | constraint_name |…
Stéphane de Luca
  • 12,745
  • 9
  • 57
  • 95
1
vote
0 answers

Custom User PK (Primary Key) - Django - Python

I built a website with Python Django and part of it displays lines of already input data with the primary key next to it. Now I have separate user data by using a foreign key field in each one of my models and the specific user's data is only shown…
Russell Hertel
  • 121
  • 3
  • 14
1
vote
0 answers

SQL Error executing INSERT: [SQLITE_BUSY] The database file is locked

I am using sqlite as db in my Micronaut application getting the sqlite busy error in the below code: @SneakyThrows @TransactionalAdvice(value = EmpDao.DATASOURCE, propagation = TransactionDefinition.Propagation.REQUIRES_NEW) public void…
Manish
  • 1,274
  • 3
  • 22
  • 59
1
vote
3 answers

sqlite text as primary key vs autoincrement integers

I'm currently debating between two strategies to using a text column as a key. The first one is to simply use the text column itself as a key, as such: create table a( key_a text primary key, ) create table b( key_b text primary…
Filipe Rodrigues
  • 1,843
  • 2
  • 12
  • 21
1
vote
1 answer

Postgresql: why no automatic updates of a id sequence after bulk insert

Assuming, I have this table: CREATE TABLE IF NOT EXISTS public.test ( "Id" smallint NOT NULL GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, "Value" character varying(10) ); and I insert some rows: INSERT INTO public.test ("Id", "Value")…
Dave_B.
  • 173
  • 10
1
vote
1 answer

Dynamo DB ERD for Chat application

I am trying to migrate my chat application from Firestore to DynamoDB. Currently I have 2 collections in firebase: Rooms and Users. Users collection have all roomsIds the user is part of. Rooms collection have some meta data such as name, icon etc.…
1
vote
2 answers

How to insert values into two SQL Server tables updating primary key and foreign key simultaneously, using a procedure?

I have something like this: CREATE TABLE [dbo].[table1] ( [id1] [int] IDENTITY(1,1) NOT NULL, [data] [varchar](255) NOT NULL, CONSTRAINT [PK_table1] PRIMARY KEY(id1) ) CREATE TABLE [dbo].[table2] ( [id2] [int] IDENTITY(1,1) NOT…
Snoke
  • 75
  • 7
1
vote
3 answers

Database schema design and foreign keys in MySQL

I'm trying to create a normalized database for a blog allowing reply to comments. Given a few answers I found, it seems that I need to look at the adjacency list model and the modified preorder tree traversal algorithm. However, after reading a bit…
r_31415
  • 8,752
  • 17
  • 74
  • 121
1
vote
2 answers

New with databases, having problems wiith primary key

I have a table where events organized by a sports center are stored. I created it like this: create table events( name varchar(20) primary key, description varchar(150), type varchar(20) not null, event_date not null, event_start time not…
1
vote
1 answer

what is a better way to create table?

I have mechanic that provide some services and there may be several services provided by a mechanic and how is better way to make tables in this case? What i have now is : Mechanic table : create table mechanic( id_master int not null…
1
vote
0 answers

Creating a Foreign Key in MySQL Using SQLAlchemy ORM in Python

I have the following class which creates 3 tables in a MySQL database, I would like the tables to be connected with primary key for the first table and foreign keys in the other tables that link to that primary key. I've constructed this using…
orie
  • 541
  • 6
  • 20
1
vote
1 answer

what is the cost of updating a clustered column in sql server 2008

I'm new in SQL Server development and I'm currently reading a book, the thing is that in this book I read that if I update an indexed column I will affect all the records in that column because an index is like the index of a book. In my work, the…