3

I'm just wondering if either the spec of the implementation (PostgreSQL) provides for generating identity columns from UUIds or the like.

Is there an alternative to,

CREATE TABLE f (
  id uuid DEFAULT gen_random_uuid()
);

Especially one that can protect the column under GENERATED ALAWYS

1

It seems that currently PostgreSQL only provides the following

GENERATED { ALWAYS | BY DEFAULT } AS IDENTITY [ ( sequence_options ) ]

The PostgreSQL docs go on to say

This clause creates the column as an identity column. It will have an implicit sequence attached to it and the column in new rows will automatically have values from the sequence assigned to it.

So it seems it's sequence specific. The SLQ 2011 spec implies there is nothing more to it,

The declared type of an identity column is either an exact numeric type with scale 0 (zero), INTEGER for example, or a distinct type whose source type is an exact numeric type with scale 0 (zero). An identity column has a start value, an increment, a maximum value, a minimum value, and a cycle option. An identity column is associated with an internal sequence generator SG.

0

You can use returning clause. It's called output_expression in documentation and it works for any (lets say) calculated field.

Here is a sample for your case;

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE f (
  id uuid DEFAULT gen_random_uuid(),
  my_data text
);

INSERT INTO f(my_data)
VALUES ('data 1'),
       ('data 3'),
       ('data 2') 
RETURNING f.* ;

Output;

                  id                  | my_data
--------------------------------------+---------
 b506f8fd-a2db-446d-926d-6de67d640147 | data 1
 be666ca2-0df0-4a76-bfb4-d8247cfef853 | data 3
 54248bcb-0bab-4bf1-bea0-e2261280ca30 | data 2
(3 rows)

INSERT 0 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.