In today’s article, I will be explaining How to Create a PostgreSQL Data Type using the concept of Domain.
It is very similar to the concept of check constraint, but unlike the check constraint, we can create the changes made as a new data type.
Let’s reinforce the subject by explaining through an example;
First we need to create a domain. When using the domain, you can use the following parameters according to your needs.
-Default
-Constraint
-Not null
-Null
-Check
I will be using the check parameter from the above parameters, so I am using the value parameter to specify the value.
Below we create a domain named int_values_f and when we use this domain as a data type, we define so that data is not used except for values of 0,1,2.
1 |
create domain int_values_f as integer check (value>=0 and value <3); |
We have created our domain under the Postgres database.
You can use the command below to check.
1 |
\dD |
Below the public schema, we see the value we use in the check section, since we use the check value with the data type integer.
1 |
CREATE TABLE d1_t1 (id int_values_f); |
The part that is written next to the integer above is the name we give to the domain.
We saw that our table was created and now let’s check the accuracy by printing the data.
In the picture below, we printed the data 0,1,2,3 in the id column, but we got an error while inserting the number 3.
The reason for this is that we have set the int_values_f data type to take values between 0 and 3, but 3 is not included because we said 3 is not included.