I need to make a query in PostgreSQL, which will put in a column that has the BIGINT type, a value and this value should be obtained uniquely from the connection of data from two adjacent columns, and in them, the records are stored in rows. And these lines are not numbers, but just words. Is it possible?
1 Answer
There is no need to generate anything. Create a sequence/identity column with datatype bigint. Just allow Postgres the generate the number. Then as mentioned create a unique constraint on the 2 strings.
-- Postgres v10 and update
create table some_table( st_id bigint generated always as identity
, col_1 varchar
, col_2 varchar
, constraint some_table_pk
primary key (st_id)
, constraint some_table_bk
unique (col_1, col_2)
) ;
-- For prior to v10
create table some_table( st_id bigserial
, col_1 varchar
, col_2 varchar
, constraint some_table_pk
primary key (st_id)
, constraint some_table_bk
unique (col_1, col_2)
) ;
2 Comments
Viktor Andriichuk
Thnx a lot! Can you please tell me what will happen цгер st_id from your code if the (col_1, col_2) is not unique?
Belayer
It the combination is not unique Postgres throws the error
SQL Error [23505]: ERROR: duplicate key value violates unique constraint ... when you attempt to insert the second set. Of course if they were not unique then you could never have a value and this value should be obtained uniquely from the connection anyway.
constraint col_ab_unique unique (a,b)