Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the right data type for unique key in postgresql DB?

which data type should I choose for a unique key (id of a user for example) in postgresql database's table?
does bigint is the one?

thanks

like image 959
socksocket Avatar asked Aug 02 '12 13:08

socksocket


People also ask

What is unique key in PostgreSQL?

The PostgreSQL UNIQUE constraint ensures that the uniqueness of the values entered into a column or a field of a table. The UNIQUE constraint in PostgreSQL can be applied as a column constraint or a group of column constraint or a table constraint.

What data type has unique keys?

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.

How do I create a unique column in PostgreSQL?

The syntax for creating a unique constraint using an ALTER TABLE statement in PostgreSQL is: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n); table_name.

What is the datatype for primary key in PostgreSQL?

The primary key column value must be unique. Each table can have only one primary key. If we are using the primary key, we should use INT or BIGINT data type as it is recommended.


3 Answers

Use the serial type for automatically incrementing unique ids.

If you plan to have more than two billion entries, use bigserial. serial is the PostgresSQL equivalent of MySQL's AUTO_INCREMENT.

PostgresSQL Documentation: Numeric Types

like image 188
Mark Loiseau Avatar answered Oct 03 '22 01:10

Mark Loiseau


bigint (or bigserial if you need auto-incrementing keys) is just fine.

If know for certain that you are not going to load too many rows, you might consider integer (or a regular serial) and potentially save some harddisk space.

like image 34
a_horse_with_no_name Avatar answered Oct 03 '22 02:10

a_horse_with_no_name


According to this answer the current recommended approach to doing auto-increment unique IDs is to use the generated as identity syntax instead of serial.

Here's an example:

-- the old way
create table t1 (id serial primary key);

-- the new way
create table t2 (id integer primary key generated always as identity);
like image 35
Vivek Seth Avatar answered Oct 03 '22 00:10

Vivek Seth