Re: create unique constraint on jsonb->filed during create table - Mailing list pgsql-general

From David G. Johnston
Subject Re: create unique constraint on jsonb->filed during create table
Date
Msg-id CAKFQuwbGEE-vVnFvtY-xQ7pHkQ=PAP9W-z=1TKe_VFL0yKgqKg@mail.gmail.com
Whole thread Raw
In response to create unique constraint on jsonb->filed during create table  (Andy Fan <zhihui.fan1213@gmail.com>)
Responses Re: create unique constraint on jsonb->filed during create table
List pgsql-general
On Wednesday, February 27, 2019, Andy Fan <zhihui.fan1213@gmail.com> wrote:

The following way works with 2 commands:

zhifan=# create table t1 (a jsonb);
CREATE TABLE
zhifan=# create unique index t1_a_name on t1 ((a->'name'));
CREATE INDEX

but know I want to merge them into 1 command, is it possible?

zhifan=# create table t2 (a jsonb, constraint uk_t2_a_name unique((a->'name')));
ERROR:  syntax error at or near "("
LINE 1: ...table t2 (a jsonb, constraint uk_t2_a_name unique((a->'name'...

Not according to the documentation.  Unique table constraints can only reference columns in the table as a whole.  An expression index must be created separately from the table to which it is attached.

Or add a trigger to the table, populate an actual second column (making it unique), and add a table check constraint that that column and the expression are equal.  I suspect you’ll be happier having the PK as actual column data anyway.

David J.

pgsql-general by date:

Previous
From: Andy Fan
Date:
Subject: create unique constraint on jsonb->filed during create table
Next
From: Achilleas Mantzios
Date:
Subject: Re: Barman disaster recovery solution