Re: Domains vs data types - Mailing list pgsql-general

From Merlin Moncure
Subject Re: Domains vs data types
Date
Msg-id CAHyXU0wHFNY=N8T4pdWFMpBiKeZmCYjr4cmF7ycxE0o_Ozp1QQ@mail.gmail.com
Whole thread Raw
In response to Re: Domains vs data types  (Dominique Devienne <ddevienne@gmail.com>)
List pgsql-general
On Thu, Aug 21, 2025 at 2:11 AM Dominique Devienne <ddevienne@gmail.com> wrote:
> On Wed, Aug 20, 2025 at 7:37 PM Florents Tselai
> <florents.tselai@gmail.com> wrote:
> > > On 20 Aug 2025, at 7:47 AM, Ertan Küçükoglu <ertan.kucukoglu@gmail.com> wrote:
> > > I would like to learn if there is any benefit of using domains over data types for table column definitions in
termsof performance gain/loss. 
>
> > I know that this doesn’t answer your question, but before exploring custom types / domains,
> > and based on experience, I’d strongly recommend exploring jsonb instead as an alternative.
>
> I stayed out of that thread, but this makes me step out and react.
> domains are typically out constraining the value space of a type.
> I.e. a type with a CHECK constraint. W/o one, it's pretty useless IMHO.

+1 this.

The main use for domains is to allow for standard constraints.   If
you find yourself writing the same constraint over and over, that's
when you might consider using them.

For example, in the USA, vehicle identification numbers must be
exactly 17 characters long.

postgres@postgres=# create domain vin as text check (length(VALUE) = 17);
CREATE DOMAIN
postgres@postgres=# select 'abc'::TEXT::VIN;
ERROR:  value for domain vin violates check constraint "vin_check"

The other use for domains I see is global sequences where you have
many tables pulling from the same sequence.

postgres@postgres=# create sequence global_id_seq;
CREATE SEQUENCE
postgres@postgres=# create domain global_id as bigint default
nextval('global_id_seq');
CREATE DOMAIN

Using domains is not really a performance thing, it's more regarding
establishing rigor around type rules.  In general, I tend not to use
length constraints for tex columns anymore for most cases (just use
text!), but I could get behind setting some standard length
constraints, say, capped at 1k characters as a safety precaution.

merlin

merlin



pgsql-general by date:

Previous
From: hubert depesz lubaczewski
Date:
Subject: Re: Streaming replica hangs periodically for ~ 1 second - how to diagnose/debug
Next
From: Adrian Klaver
Date:
Subject: Re: Q: GRANT ... WITH ADMIN on PG 17