Home > Software design >  How To Define Type Nickname in in PostgreSQL?
How To Define Type Nickname in in PostgreSQL?

Time:09-14

I'm new to SQL so please forgive if this question is dumb.

I'm googling "How to create a type alias in postgresql?" and the answers all seem to get into types as tables, and stuff that is overkill for what I want to do.

I need PostgreSQL's version of this:

#define t_my_int int

The motivation for doing this is that a lot of my tables have the same field name, say, my_field, and they are all of type VARCHAR(X), where X is a random number. I want to make all my my_field's the same. All VARCHAR(100), for example.

How do I do that?

CodePudding user response:

A domain would be one solution:

create domain name_type as varchar(100);

However, using domains like that has a serious limitation: once you have defined it, you can't change the data type anymore. So you can't e.g. increase the maximum length.

One way to avoid that, is to use an unbounded type, and use a check constraint to validate the length

create domain name_type as text
   constraint check_name_length 
   check (length(value) <= 100);
  

The check constraint can be dropped and re-created with a different condition.

  • Related