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
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.
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.
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.
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.
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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With