User Defined Data Types

yours truely

CREATE DOMAIN

  • Create user defined data type with a range, optional, DEFAULT, NOT NULL and CHECK Constraint.

  • They are unique within schema scope.

  • Helps standardise your database types in one place.

  • Composite Type : Only single value return

CREATE DOMAIN name datatype constraint

-- ex 1
-- 'addr' with domain VARCHAR(100)
CREATE DOMAIN addr VARCHAR(100) NOT NULL;

CREATE TABLE locations (
    address addr
);

            Table "public.locations"
 Column  | Type | Collation | Nullable | Default 
---------+------+-----------+----------+---------
 address | addr |           |          | 


-- Dropping Constraints
-- if domain isnt used anywhere
drop domain addr;    

-- this will drop the column in the table it is present in
-- use this with caution
drop domain addr CASCADE;

-- List all domains inside a schema
select typname from pg_catalog.pg_type 
 join pg_catalog.pg_namespace 
 on pg_namespace.oid = pg_type.typnamespace
 where typtype = 'd' and nspname = 'public';
 
      typname      
------------------
 positive_numeric
 valid_color
 addr

Number Based Components

Text Based Domain

Enum Based Domain

Composite Data Types

Syntax : (composite_column).city

Example 1

Example 2

Alter

Alter TYPE

ALTER ENUM

Updating/Replacing ENUM domain

Default value ENUM

CREATE DOMAIN IF NOT EXISTS

Last updated

Was this helpful?