Viktor Andriichuk
Viktor Andriichuk

Reputation: 123

Postgres: how to generate a unique number based on a string?

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?

Upvotes: 0

Views: 1552

Answers (1)

Belayer
Belayer

Reputation: 14934

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)
                        ) ;


                    
               

Upvotes: 1

Related Questions