f1erce.netlify.app

Menu

  • Home

How Do You Make Postgres Auto Generate Primary Key

17.12.2020by admin
How Do You Make Postgres Auto Generate Primary Key Rating: 6,2/10 3644 votes
  • How Do You Make Postgres Auto Generate Primary Key Example
  • How Do You Make Postgres Auto Generate Primary Keys

This PostgreSQL tutorial explains how to create, drop, disable, and enable a primary key in PostgreSQL with syntax and examples.

What is a primary key in PostgreSQL?

It's important to note that if the primary key is used as a foreign key constraint in other tables, you'll have to include the keyword CASCADE at the end of the DROP CONSTRAINT command. Subsequently, you will also need to individually recreate the foreign keys in the other tables. If you wish a serial column to have a unique constraint or be a primary key, it must now be specified, just like any other data type. The type name serial creates an integer columns. The type name bigserial creates a bigint column. Bigserial should be used if you anticipate the use.

In PostgreSQL, a primary key is a single field or combination of fields that uniquely defines a record. None of the fields that are part of the primary key can contain a NULL value. A table can have only one primary key.

Note

  • In PostgreSQL, a primary key is created using either a CREATE TABLE statement or an ALTER TABLE statement.
  • You use the ALTER TABLE statement in PostgreSQL to add or drop a primary key.

Create Primary Key - Using CREATE TABLE statement

You can create a primary key in PostgreSQL with the CREATE TABLE statement.

Syntax

The syntax to create a primary key using the CREATE TABLE statement in PostgreSQL is:

OR

table_name
The name of the table that you wish to create.
column1, column2
The columns that you wish to create in the table. See the PostgreSQL CREATE TABLE statement for more detailed CREATE TABLE syntax as this is an over-simplification to demonstrate how to create a Primary Key.
constraint_name
The name of the primary key.
index_col1, index_col2, .. index_col_n
The columns that make up the primary key.

Example

Let's look at an example of how to create a primary key using the CREATE TABLE statement in PostgreSQL.

Or you could also create the primary key on the order_details table using the following syntax:

In these two examples, we've created a primary key on the order_details table called order_details_pk. It consists of only one column - the order_detail_id column.

We could also create a primary key with more than one field as in the example below:

This example creates a primary key called order_details_pk that is made up of a combination of the order_date and customer_id columns. So each combination of order_date and customer_id must be unique in the order_details table.

Create Primary Key - Using ALTER TABLE statement

You can create a primary key in PostgreSQL with the ALTER TABLE statement.

Syntax

The syntax to create a primary key using the ALTER TABLE statement in PostgreSQL is:

How do you make postgres auto generate primary key in excel
table_name
The name of the table to modify.
constraint_name
The name of the primary key.
index_col1, index_col2, .. index_col_n
The columns that make up the primary key.

Example

Let's look at an example of how to create a primary key using the ALTER TABLE statement in PostgreSQL.

In this example, we've created a primary key on the existing order_details table called order_details_pk. It consists of the order_detail_id column.

We could also create a primary key with more than one field as in the example below:

This example we've created a primary key called contacts_pk that is made up of a combination of the last_name and first_name columns.

Drop Primary Key

You can drop a primary key in PostgreSQL using the ALTER TABLE statement.

Syntax

The syntax to drop a primary key in PostgreSQL is:

table_name
The name of the table to modify.
constraint_name
The name of the primary key that you wish to drop.

Example

Let's look at an example of how to drop a primary key using the ALTER TABLE statement in PostgreSQL.

In this example, we've dropped the primary key on the contacts table. We do not need to specify the name of the primary key as there can only be one on a table.

How Do You Make Postgres Auto Generate Primary Key Example

This weekend Dr Nic shared with us a well written article discussing the shortcomings of auto-incrementing (serial) keys and an alternative approach. While discussing the article the question came up about how to go about using UUID keys in our applications and what we have to do within PostgreSQL in order to use them. PostgreSQL out of the box defines a UUID Data Type which is a great start. We then have three options for generating UUID's,

  1. Within your application code
  2. Within the database using the extension uuid-ossp
  3. Within the database using the extension pgcrypto

Generating them within our application will work quite nicely and is a good way to go, unless you want the database to handle creating these automatically for you which is usually where our point of view.

Only use uuid-ossp if you have a real and specific need for the functions it provides If your only need is to generate and index them then you do not need uid-ossp. (Update: See below.) For generating UUID's within the database an easy place to start is to use the gen_random_uuid () function from the pgcrypto extension.

So how do we use this function? First we need to create the extension in the database we wish to use it with,

This is how you load pre-compiled shared library code which adds functionality into your PostgreSQL database.

How Do You Make Postgres Auto Generate Primary Keys

Note specifically that the extension must be created (loaded) once for each database in which you wish to use it. Once it has been loaded into a running instance of the database server it will be there for use from then on spanning restarts.

Also be aware that if you have dumped and restored the database from one server to another running instance then depending on the method of the dump/restore you may need to load it into this new instance after restoring.

Once you have done this you can generate a random id,

Which returns a UUID Data Type.

Let's create a table with a UUID primary key and see how we use the gen_random_uuid() function to populate our IDs for us,

We can now add entries into our newly created Stark & Wayne Contacts table,

Let's examine our table now, /euro-truck-simulator-2-activation-key-generator.html.

We see that each row has a UUID id field which is the primary key and was automatically generated for us.

Discussion

It was pointed out by @drewblas (thank you Drew!) that using gen_random_uuid() from pgcrypto has a negative side effect with respect to keyspace fragmentation on disk for the tables. Drew told us that:

Random produces very fragmented inserts that destroy tables. Use uuid_generate_v1mc() [instead] .. the keys are seq because they're time based. So all inserts go to the same data page without random io.

This makes sense due to the random probability distribution of the keys, it should be fragemented. This fragmentation however is not so good for efficiency of the database system itself. In order to gain the benefits of using UUID primary keys with lower keyspace fragmentation perhaps Drew points out that it is better to use uuid_generate_v1mc() from the uuid-ossp extension because underneath it is using a time based seq algorithm which you can read about in the postgresql documentation.

Find more great articles with similar tagspostgresqluuidextension

Post navigation

Cisco Asa Generate Ssh Key Asdm
Visual Studio 2012 Professional Key Generator

Archive

  • Civilization 6 Key Code Generator
  • Rocket League Key Generator Online
  • Garmin Key Generator 1.5 Download
  • Cities Xl 2012 Serial Key Generator
  • Far Cry 2 Serial Key Generator Free
  • Keil Uvision 4 Key Generator Download
  • Think Cell 8 Key Generator
  • Save The World Keys Generator
f1erce.netlify.app